@unbrained/pm-cli 2026.8.9 → 2026.8.11

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 (249) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +142 -80
  3. package/dist/cli/commander-usage.js +94 -17
  4. package/dist/cli/error-guidance.d.ts +10 -0
  5. package/dist/cli/error-guidance.js +76 -25
  6. package/dist/cli/help-json-payload.js +51 -16
  7. package/dist/cli/main.js +11 -6
  8. package/dist/cli/register-assurance.d.ts +8 -0
  9. package/dist/cli/register-assurance.js +52 -0
  10. package/dist/cli/register-files-lookup.js +14 -3
  11. package/dist/cli/register-mutation.js +30 -9
  12. package/dist/cli/register-operations.js +16 -11
  13. package/dist/cli-bundle/bundle-manifest.json +163 -163
  14. package/dist/cli-bundle/chunks/{chunk-RJC7TPF4.js → chunk-2OOU2AFH.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-2RA2YTHJ.js +33 -0
  16. package/dist/cli-bundle/chunks/chunk-A2SJGHSI.js +3 -0
  17. package/dist/cli-bundle/chunks/chunk-DSKYD4LG.js +13 -0
  18. package/dist/cli-bundle/chunks/chunk-HC3GM6YY.js +194 -0
  19. package/dist/cli-bundle/chunks/chunk-IUNRVDAI.js +2 -0
  20. package/dist/cli-bundle/chunks/chunk-W7CPZGSB.js +2 -0
  21. package/dist/cli-bundle/chunks/{chunk-YC3UF2IO.js → chunk-WMEZHCFI.js} +66 -60
  22. package/dist/cli-bundle/chunks/{chunk-GMX5YOI3.js → chunk-ZU34C3LH.js} +48 -48
  23. package/dist/cli-bundle/chunks/chunk-ZXOC6HG5.js +5 -0
  24. package/dist/cli-bundle/chunks/{register-list-query-BUE7PTCU.js → register-list-query-HAUXVUPY.js} +8 -8
  25. package/dist/cli-bundle/chunks/register-mutation-7Y5U7ABT.js +20 -0
  26. package/dist/cli-bundle/chunks/register-operations-EQX3DLAZ.js +2 -0
  27. package/dist/cli-bundle/chunks/{register-setup-UQDTNTLJ.js → register-setup-NOCOOWQY.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-KNEHLPBF.js → chunk-23FTGO3W.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-6DO4YQWZ.js → chunk-2DL3MRTD.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/chunk-3AYKXMYX.js +2 -0
  31. package/dist/cli-bundle/focused-chunks/chunk-4AHEC74N.js +2 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-MRWVJ3ZG.js → chunk-4H5IA6AV.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-4SV3ZKG3.js +16 -0
  34. package/dist/cli-bundle/focused-chunks/chunk-55BIB6DV.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/chunk-6JW6Z2P5.js +8 -0
  36. package/dist/cli-bundle/focused-chunks/chunk-BKPIY34S.js +2 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-D4PIWE6D.js +2 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-DPO7TEFX.js +31 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-3WVHTUAW.js → chunk-E3KCL7AY.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/chunk-ERAAFLPS.js +153 -0
  41. package/dist/cli-bundle/focused-chunks/chunk-F6E4JZKG.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/chunk-FPSYO5ZG.js +18 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-73FIJONU.js → chunk-J5EKAIVD.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-KDH5OX3D.js +4 -0
  45. package/dist/cli-bundle/focused-chunks/chunk-OJ3LVVIS.js +2 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-TL5M2PAY.js +3 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-UDAZWT25.js +6 -0
  48. package/dist/cli-bundle/focused-chunks/chunk-VABB4L5Y.js +17 -0
  49. package/dist/cli-bundle/main.js +13 -13
  50. package/dist/cli-bundle/sdk-authoring.js +1 -1
  51. package/dist/cli-bundle/sdk-contracts.js +1 -1
  52. package/dist/cli-bundle/sdk-core.js +41 -39
  53. package/dist/cli-bundle/sdk-governance.js +1 -1
  54. package/dist/cli-bundle/sdk-graph.js +1 -1
  55. package/dist/cli-bundle/sdk-merge.js +1 -1
  56. package/dist/cli-bundle/sdk-query.js +1 -1
  57. package/dist/cli-bundle/sdk-runtime.js +1 -1
  58. package/dist/cli-bundle/sdk-testing.js +1 -1
  59. package/dist/cli-bundle/sdk.js +2 -2
  60. package/dist/core/diagnostics/remediation.js +9 -9
  61. package/dist/core/fs/fs-utils.d.ts +10 -0
  62. package/dist/core/fs/fs-utils.js +16 -4
  63. package/dist/core/item/item-format.js +3 -32
  64. package/dist/core/schema/fields-file.d.ts +1 -2
  65. package/dist/core/schema/fields-file.js +4 -11
  66. package/dist/core/schema/runtime-schema.js +3 -10
  67. package/dist/core/schema/status-defs-file.d.ts +1 -2
  68. package/dist/core/schema/status-defs-file.js +4 -32
  69. package/dist/core/schema/status-token.d.ts +2 -0
  70. package/dist/core/schema/status-token.js +32 -0
  71. package/dist/core/schema/type-workflows.d.ts +1 -2
  72. package/dist/core/schema/type-workflows.js +4 -11
  73. package/dist/core/session/session-state.d.ts +47 -0
  74. package/dist/core/session/session-state.js +207 -6
  75. package/dist/core/shared/author.d.ts +8 -2
  76. package/dist/core/shared/author.js +85 -52
  77. package/dist/core/shared/errors.d.ts +12 -0
  78. package/dist/core/shared/errors.js +2 -2
  79. package/dist/core/shared/text-normalization.d.ts +1 -1
  80. package/dist/core/shared/text-normalization.js +2 -2
  81. package/dist/sdk/agent/command-recovery.d.ts +4 -0
  82. package/dist/sdk/agent/command-recovery.js +52 -0
  83. package/dist/sdk/agent/command-suggestions.d.ts +4 -0
  84. package/dist/sdk/agent/command-suggestions.js +67 -0
  85. package/dist/sdk/agent/create-option-policy.d.ts +12 -0
  86. package/dist/sdk/agent/create-option-policy.js +32 -0
  87. package/dist/sdk/agent/item-addressing.d.ts +19 -0
  88. package/dist/sdk/agent/item-addressing.js +208 -0
  89. package/dist/sdk/agent/refusal-reachability.d.ts +40 -0
  90. package/dist/sdk/agent/refusal-reachability.js +72 -0
  91. package/dist/sdk/agent/subcommand-recovery.d.ts +40 -0
  92. package/dist/sdk/agent/subcommand-recovery.js +84 -0
  93. package/dist/sdk/cli-bootstrap.d.ts +9 -1
  94. package/dist/sdk/cli-bootstrap.js +25 -10
  95. package/dist/sdk/cli-contracts/commander-mutation-options.js +16 -4
  96. package/dist/sdk/cli-contracts/completeness.js +13 -3
  97. package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
  98. package/dist/sdk/cli-contracts/enum-contracts.js +3 -2
  99. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  100. package/dist/sdk/cli-contracts/flag-contracts.js +77 -21
  101. package/dist/sdk/cli-contracts/registration-helpers.js +10 -2
  102. package/dist/sdk/cli-contracts/runtime-contracts.js +6 -3
  103. package/dist/sdk/cli-contracts/schemas/assurance-definition.d.ts +513 -0
  104. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +251 -0
  105. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
  106. package/dist/sdk/cli-contracts/tool-option-contracts.js +4 -2
  107. package/dist/sdk/cli-contracts/tool-parameter-tables.js +96 -4
  108. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  109. package/dist/sdk/cli-contracts/tool-schema.js +49 -6
  110. package/dist/sdk/cli-contracts.d.ts +1 -1
  111. package/dist/sdk/cli-contracts.js +3 -3
  112. package/dist/sdk/completion.js +9 -3
  113. package/dist/sdk/config.js +9 -3
  114. package/dist/sdk/context/semantic-session-attribution.d.ts +32 -0
  115. package/dist/sdk/context/semantic-session-attribution.js +83 -0
  116. package/dist/sdk/context-intent-runtime.js +8 -5
  117. package/dist/sdk/context-signal-store.d.ts +34 -0
  118. package/dist/sdk/context-signal-store.js +24 -2
  119. package/dist/sdk/core-governance.d.ts +3 -1
  120. package/dist/sdk/core-governance.js +5 -3
  121. package/dist/sdk/core.d.ts +1 -1
  122. package/dist/sdk/core.js +2 -2
  123. package/dist/sdk/dependency-flag-validation.d.ts +15 -1
  124. package/dist/sdk/dependency-flag-validation.js +54 -2
  125. package/dist/sdk/error-code-catalog.d.ts +13 -0
  126. package/dist/sdk/error-code-catalog.js +35 -2
  127. package/dist/sdk/extension.js +18 -17
  128. package/dist/sdk/files.d.ts +11 -0
  129. package/dist/sdk/files.js +82 -24
  130. package/dist/sdk/generated-error-code-catalog.js +104 -13
  131. package/dist/sdk/governance/assurance-action-contracts.d.ts +7 -0
  132. package/dist/sdk/governance/assurance-action-contracts.js +5 -0
  133. package/dist/sdk/governance/assurance-action.d.ts +70 -0
  134. package/dist/sdk/governance/assurance-action.js +198 -0
  135. package/dist/sdk/governance/assurance-limits.d.ts +7 -0
  136. package/dist/sdk/governance/assurance-limits.js +11 -0
  137. package/dist/sdk/governance/assurance-runtime.d.ts +20 -0
  138. package/dist/sdk/governance/assurance-runtime.js +131 -0
  139. package/dist/sdk/governance/assurance.d.ts +432 -0
  140. package/dist/sdk/governance/assurance.js +689 -0
  141. package/dist/sdk/governance/health.js +14 -7
  142. package/dist/sdk/governance/provenance-health.d.ts +13 -0
  143. package/dist/sdk/governance/provenance-health.js +63 -17
  144. package/dist/sdk/governance/validate-item-reader.d.ts +13 -0
  145. package/dist/sdk/governance/validate-item-reader.js +18 -0
  146. package/dist/sdk/governance/validate.d.ts +2 -2
  147. package/dist/sdk/governance/validate.js +15 -6
  148. package/dist/sdk/graph/run.js +8 -3
  149. package/dist/sdk/index.d.ts +10 -1
  150. package/dist/sdk/index.js +12 -3
  151. package/dist/sdk/lifecycle/claim.js +18 -3
  152. package/dist/sdk/lifecycle/close.js +17 -14
  153. package/dist/sdk/lifecycle/create.d.ts +2 -0
  154. package/dist/sdk/lifecycle/create.js +62 -9
  155. package/dist/sdk/lifecycle/focus.js +13 -3
  156. package/dist/sdk/lifecycle/plan.js +8 -3
  157. package/dist/sdk/lifecycle/update-many.js +39 -27
  158. package/dist/sdk/lifecycle/update.d.ts +6 -1
  159. package/dist/sdk/lifecycle/update.js +47 -10
  160. package/dist/sdk/merge/index.d.ts +1 -1
  161. package/dist/sdk/merge/index.js +3 -3
  162. package/dist/sdk/merge/install.d.ts +4 -0
  163. package/dist/sdk/merge/install.js +28 -16
  164. package/dist/sdk/merge/receipts.d.ts +3 -0
  165. package/dist/sdk/merge/receipts.js +81 -17
  166. package/dist/sdk/output-projection.js +24 -4
  167. package/dist/sdk/provenance.d.ts +38 -0
  168. package/dist/sdk/provenance.js +64 -2
  169. package/dist/sdk/query/context.d.ts +2 -0
  170. package/dist/sdk/query/context.js +24 -10
  171. package/dist/sdk/query/light-metadata.d.ts +3 -0
  172. package/dist/sdk/query/light-metadata.js +19 -0
  173. package/dist/sdk/runtime-extended-actions.js +22 -5
  174. package/dist/sdk/runtime-primitives.d.ts +2 -0
  175. package/dist/sdk/runtime-primitives.js +4 -2
  176. package/dist/sdk/runtime.d.ts +8 -1
  177. package/dist/sdk/runtime.js +37 -28
  178. package/dist/sdk/schema-migration.js +7 -9
  179. package/dist/sdk/similarity-scoring.d.ts +1 -2
  180. package/dist/sdk/similarity-scoring.js +4 -16
  181. package/dist/sdk/telemetry.js +7 -4
  182. package/dist/sdk/traceability/runtime-files-lookup.d.ts +8 -0
  183. package/dist/sdk/traceability/runtime-files-lookup.js +33 -0
  184. package/dist/sdk/traceability/source-traceability.d.ts +102 -0
  185. package/dist/sdk/traceability/source-traceability.js +293 -0
  186. package/dist/sdk/workspace-snapshot.d.ts +4 -0
  187. package/dist/sdk/workspace-snapshot.js +24 -11
  188. package/dist/types.d.ts +8 -2
  189. package/dist/types.js +2 -2
  190. package/docs/AGENT_GUIDE.md +3 -1
  191. package/docs/ASSURANCE.md +132 -0
  192. package/docs/COMMANDS.md +8 -5
  193. package/docs/MERGE_SAFETY.md +7 -5
  194. package/docs/README.md +3 -5
  195. package/docs/READ_OUTPUT_CONTRACTS.md +2 -2
  196. package/docs/RELEASING.md +9 -5
  197. package/docs/SDK.md +44 -8
  198. package/docs/SDK_AGENT_SESSION_CONTEXT.md +43 -6
  199. package/docs/SDK_CONTEXT.md +97 -0
  200. package/docs/SDK_CONTEXT_INTEGRITY.md +18 -3
  201. package/docs/SDK_EVIDENCE_TRACEABILITY.md +39 -1
  202. package/docs/SDK_RUNTIME_BOUNDARIES.md +36 -1
  203. package/docs/TESTING.md +12 -9
  204. package/docs/agent-task-token-baseline.json +2 -2
  205. package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -0
  206. package/marketplace.json +2 -2
  207. package/package.json +7 -6
  208. package/packages/pm-beads/package.json +1 -1
  209. package/packages/pm-calendar/package.json +1 -1
  210. package/packages/pm-command-kit/package.json +1 -1
  211. package/packages/pm-digital-twin/package.json +1 -1
  212. package/packages/pm-governance-audit/package.json +1 -1
  213. package/packages/pm-guide-shell/package.json +1 -1
  214. package/packages/pm-kanban/package.json +1 -1
  215. package/packages/pm-lifecycle-hooks/package.json +1 -1
  216. package/packages/pm-linked-test-adapters/package.json +1 -1
  217. package/packages/pm-search-advanced/package.json +1 -1
  218. package/packages/pm-templates/extensions/templates/index.ts +9 -3
  219. package/packages/pm-templates/package.json +1 -1
  220. package/packages/pm-todos/package.json +1 -1
  221. package/packages/pm-vcs/package.json +1 -1
  222. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  223. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  224. package/sdk/public-surface.json +1028 -48
  225. package/dist/cli-bundle/chunks/chunk-2DTCZXSD.js +0 -13
  226. package/dist/cli-bundle/chunks/chunk-5JO6R4BS.js +0 -3
  227. package/dist/cli-bundle/chunks/chunk-5KN4DZYV.js +0 -194
  228. package/dist/cli-bundle/chunks/chunk-EF43KODO.js +0 -2
  229. package/dist/cli-bundle/chunks/chunk-HUV2Z7IS.js +0 -28
  230. package/dist/cli-bundle/chunks/chunk-MHBVCUF2.js +0 -2
  231. package/dist/cli-bundle/chunks/chunk-PYO5GZU6.js +0 -5
  232. package/dist/cli-bundle/chunks/register-mutation-FC3XLVIK.js +0 -20
  233. package/dist/cli-bundle/chunks/register-operations-YH2WAOXU.js +0 -2
  234. package/dist/cli-bundle/focused-chunks/chunk-2VVP5RAA.js +0 -153
  235. package/dist/cli-bundle/focused-chunks/chunk-3GSFUDAI.js +0 -2
  236. package/dist/cli-bundle/focused-chunks/chunk-4H6MVCK3.js +0 -16
  237. package/dist/cli-bundle/focused-chunks/chunk-54TZJ4BM.js +0 -2
  238. package/dist/cli-bundle/focused-chunks/chunk-5NK5TJ5D.js +0 -2
  239. package/dist/cli-bundle/focused-chunks/chunk-C3GCHDSQ.js +0 -31
  240. package/dist/cli-bundle/focused-chunks/chunk-JGRSQZJT.js +0 -18
  241. package/dist/cli-bundle/focused-chunks/chunk-NL57J7BZ.js +0 -4
  242. package/dist/cli-bundle/focused-chunks/chunk-P6BBIQRG.js +0 -6
  243. package/dist/cli-bundle/focused-chunks/chunk-PZAGVQNN.js +0 -3
  244. package/dist/cli-bundle/focused-chunks/chunk-QDAO3XEK.js +0 -14
  245. package/dist/cli-bundle/focused-chunks/chunk-T4IGQCSY.js +0 -2
  246. package/dist/cli-bundle/focused-chunks/chunk-U46GQJNY.js +0 -2
  247. package/dist/cli-bundle/focused-chunks/chunk-VRXJSGIT.js +0 -8
  248. package/dist/cli-bundle/focused-chunks/chunk-XC2ZW3CJ.js +0 -2
  249. package/dist/cli-bundle/focused-chunks/chunk-ZG54B4XG.js +0 -2
@@ -1,16 +1,16 @@
1
- import{a as ua,b as Xe,c as mn,d as $a,e as Pa,f as Fa}from"./chunk-5JO6R4BS.js";import{E as yo,G as Na,M as Wa,b as Di,ba as Ka,e as gt,f as oo,h as Bi,n as co}from"./chunk-PYO5GZU6.js";import{$ as ha,$a as Oa,B as Oe,Ca as wt,D as Vi,Da as Ia,Ea,Fa as xa,Ga as Ra,H as ao,Ha as Aa,Ia as Ca,Pb as bo,V as yt,W as be,Y as fa,Z as _a,_ as b,_a as Ta,a as en,aa as ga,ab as ho,b as qi,bb as go,ca as B,d as Ke,da as ya,e as zi,ea as cn,f as tn,fa as ba,fb as ln,fc as wo,ga as lo,gb as Da,gc as vo,h as Ye,ha as dn,hb as ja,ia as mo,ib as Ua,ic as Ja,ja as we,k as io,ka as po,l as Hi,la as W,m as nn,ma as uo,na as ie,nb as Ga,oa as wa,ob as qa,oc as Xa,pa as va,pb as za,pc as Za,qa as fo,qb as Ha,qc as Qa,ra as ka,rb as Ba,sa as _o,t as Je,tb as Va,yb as Ya,za as Sa}from"./chunk-HUV2Z7IS.js";import{$ as pa,A as $e,B as Ki,C as on,D as Yi,E as Pe,F as Ji,G as sn,H as Xi,I as rn,Ia as an,L as Zi,O as Qi,Oa as La,P as ea,Q as ta,R as na,S as oa,T as sa,U as ra,V as ia,W as aa,X as ca,Y as da,Z as la,_ as ma,b as ji,va as bt,y as Wi}from"./chunk-GMX5YOI3.js";import{I as Gi,Ib as Ma,_ as ye,ab as so,b as Fi,c as Jt,d as no,e as Li,f as Xt,fb as ro,g as Zt,h as Qt,i as Ni,l as Mi,w as Ui}from"./chunk-2DTCZXSD.js";import{$g as Bt,$i as Kt,A as u,Ab as Ks,Ae as ur,Af as pe,Ah as Qn,Ak as $i,Bb as Ys,Bc as er,Bf as Ut,Bg as We,Bh as Jr,C as p,Cc as tr,Ci as ni,De as He,Df as wr,Dk as $,E as Us,Eb as D,Ed as O,F as ge,Fa as F,Fb as Js,Fd as ze,Ff as Y,Fk as Pi,Ga as Pt,Gg as $r,Hc as Ge,He as fr,Jg as R,Kc as nr,Kg as Pr,L as On,Lc as or,Ld as me,Lf as Ve,Lg as Fr,Mg as Lr,Mh as Xr,Na as x,Nc as Ee,Nh as Zr,Nj as mi,Oc as sr,Of as Kn,Oh as Qr,Oj as pi,P as S,Pc as rr,Pf as ut,Qa as A,Qc as xe,Qe as _r,Qf as Yn,R as At,Ra as dt,Rc as ir,Se as hr,T as Gs,Ta as se,Tc as q,U as Ct,Ug as zt,V as Tt,Vc as mt,W as Ot,Wc as ar,Wf as ft,Wg as Ht,Wj as ui,X as $t,Xd as dr,Xf as vr,Xg as Nr,Yb as Mn,Yf as kr,Yg as te,Yi as oi,Yj as fi,Zb as Dn,Zc as cr,Zd as lr,Zf as Sr,Zg as H,_b as jn,_f as Ir,_i as si,ac as Xs,ae as mr,ah as Mr,aj as ri,ba as qs,bh as Dr,c as E,ca as ct,cg as Gt,ch as Vt,d as G,dh as _t,dk as _i,e as V,ea as $n,ed as pt,eg as Er,eh as jr,ei as eo,ek as hi,f as at,fg as xr,g as Fs,gc as Zs,gd as qe,gh as Jn,gi as to,gj as ii,gk as gi,hc as Un,hd as Nt,ic as Gn,ih as Xn,jc as qn,jg as Rr,jk as yi,k as Ls,kb as Ft,kc as zn,kd as Mt,kf as gr,kk as bi,l as Ns,lc as Hn,ld as le,lk as wi,m as Ms,mc as Bn,md as Re,mh as Ur,mk as vi,n as Ds,nc as Vn,ng as Ar,nh as Gr,nk as ki,oc as T,of as re,oh as qr,oj as ai,ok as Si,pb as Ue,pf as Ae,ph as zr,pj as ci,pk as Ii,qg as ue,qh as Hr,qk as Ei,rf as Dt,ri as ei,rj as di,rk as xi,sf as ee,sh as Br,si as ti,sk as Ri,tc as Lt,te as pr,tf as Ce,tg as Cr,th as Vr,tk as Ai,ua as Pn,uc as lt,uf as yr,ug as Tr,uh as Wr,uj as li,uk as Ci,v as js,va as Fn,vb as zs,vf as Te,vh as ht,wa as Ln,wb as Hs,wf as br,wg as qt,wh as Kr,xa as Nn,xb as Bs,xc as N,xh as Wt,xk as Ti,yb as Vs,yc as Qs,yf as Be,yg as Or,yh as Yr,yk as Yt,zb as Ws,zc as Wn,zf as jt,zh as Zn,zk as Oi}from"./chunk-5KN4DZYV.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]="bb16b445-3bd4-520d-becf-c55621bfa186")}catch{}})();var cg=Fs,dg=Ls,lg=Ds,mg=Ns,pg=Ms;function ec(e,t,n,o){let s=e.flag.slice(2).replace(/[-_]([a-z])/gu,(i,a)=>a.toUpperCase()),r=n.has(s);return{long:t,...o?{short:o}:{},description:e.description??`Standard pm ${e.flag} option.`,...e.required===!0?{required:!0}:{},...e.list===!0?{list:!0}:{},...e.repeatable===!0?{repeatable:!0}:{},value_type:r?"string":"boolean",...r?{value_name:e.value_name??"value"}:{}}}function tc(e,t=[]){let n=new Set(t.flatMap(s=>s.keys)),o=[];for(let s of oi(e.map(r=>({...r})))){o.push(ec(s,s.flag,n,s.short));for(let r of s.aliases??[])o.push(ec(s,r,n))}return o}var ug=tc(Kt,ei),gl=tc(Yt,ti);import{AsyncLocalStorage as uh}from"node:async_hooks";import rl 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]="27dd77f6-e53d-55b7-be15-db0e60eaec4e")}catch{}})();function nc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yl(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function ko(e,t){let n=yl(t),o=n==="brief"?n:nc(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:nc(e.filters)?e.filters:{},projection: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]="b9eae1a3-3eb6-5415-86c3-a8e8e1fedd1f")}catch{}})();function oc(e){return e.map(t=>({key:t.key,optionName:ar(t),metadataKey:t.metadata_key,type:t.type,commands:[...t.commands],repeatable:t.repeatable,requiredOnCreate:t.required_on_create,...t.description?{description:t.description}:{}}))}function sc(e){return e.map(t=>({command:t.command,action:t.action,arguments:t.arguments.map(n=>({name:n.name,required:n.required===!0,variadic:n.variadic===!0,description:n.description})),description:t.description,tier:t.tier??"standard"}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c898a52-eba4-5626-8207-5ffefd4990ba")}catch{}})();var bl=50,ve=new Map;function So(){ve.clear()}function rc(e,t){let n=ve.get(e);if(n!==void 0)return n;if(ve.size>=bl){let s=ve.keys().next().value;ve.delete(s)}let o=t().catch(s=>{throw ve.get(e)===o&&ve.delete(e),s});return ve.set(e,o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f62939a-7b99-5687-93ae-834e0032f1d5")}catch{}})();var wl={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function ic(e){return Object.fromEntries(_r.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Io={ctx:{action:"context"},...wl,...ic("extension"),...ic("package")};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41012e87-ed61-56b2-8505-8f786b3952b2")}catch{}})();var ac="PmCliError";function vl(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=u.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function kl(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new p(e,vl(t.exitCode??u.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Eo(e){if(!(e instanceof Error)||e.name!==ac)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}import{constants as vt}from"node:fs";import{lstat as cc,mkdir as Ro,open as dc}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]="c53bb1b7-12b9-5370-a85b-cdd8bef57936")}catch{}})();function xo(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Relationship event ${t} must be non-empty`);return e.trim()}function Ao(e,t){let n=t.require(e.kind),o=n.direction==="undirected"?[e.source,e.target].sort().join("\0"):`${e.source}\0${e.target}`;return`${n.kind}\0${o}`}function Sl(e){return Object.freeze({...e,...e.payload===void 0?{}:{payload:Object.freeze(structuredClone(e.payload))}})}function Il(e,t,n,o){let s=n.require(e.kind),r=o.outgoingOne.get(`${s.kind}\0${e.source}`);if(r!==void 0&&r!==t)throw new TypeError(`Relationship outgoing cardinality exceeded for ${s.kind}`);let i=o.incomingOne.get(`${s.kind}\0${e.target}`);if(i!==void 0&&i!==t)throw new TypeError(`Relationship incoming cardinality exceeded for ${s.kind}`);let a=Ao(e,n),c=o.identities.get(a);if(c!==void 0&&c!==t)throw new TypeError(`Relationship edge already active: ${a}`)}function El(e){let t=new Map;for(let n of e)n.action==="remove"?t.delete(n.relationshipId):t.set(n.relationshipId,n.edge);return t}function xl(e,t,n){if(e.expectedVersion!==void 0&&e.expectedVersion!==t)throw new TypeError(`Relationship event version conflict: expected ${e.expectedVersion}, current ${t}`);let o=xo(e.eventId,"eventId");if(n.has(o))throw new TypeError(`Relationship event already exists: ${o}`);if(e.action!=="add"&&e.action!=="remove"&&e.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${e.action}`);if(!Number.isFinite(Date.parse(e.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:o,relationshipId:xo(e.relationshipId,"relationshipId"),author:xo(e.author,"author"),timestamp:new Date(e.timestamp).toISOString()}}function Rl(e,t,n,o,s,r){let i=n.has(t);if(e.action==="add"&&i)throw new TypeError(`Relationship is already active: ${t}`);if(e.action!=="add"&&!i)throw new TypeError(`Relationship is not active: ${t}`);if(e.action==="remove")return;if(!e.edge)throw new TypeError(`Relationship ${e.action} event requires an edge`);let a=typeof e.edge.source=="string"?e.edge.source.trim():"",c=typeof e.edge.target=="string"?e.edge.target.trim():"";if(!o.has(a)||!o.has(c))throw new TypeError(`Relationship endpoint not found: ${a} -> ${c}`);let d=new Ue([a,c],[e.edge],s).edges()[0];return Il(d,t,s,r),Sl(d)}var kt=class{#t;#n;#o=[];#r=new Set;#e=new Map;#s={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(t,n={}){this.#t=new Set([...t].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)),this.#n=n.registry??Ft()}get version(){return this.#o.length}events(){return Object.freeze([...this.#o])}*stream(t={}){let n=t.fromVersion??1,o=t.toVersion??this.version,s=t.batchSize??100;if(!Number.isInteger(n)||n<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${o}`);if(!Number.isInteger(s)||s<1)throw new TypeError("Relationship event stream batchSize must be positive");if(n>o+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let r=n-1;r<o;r+=s)yield Object.freeze(this.#o.slice(r,Math.min(r+s,o)))}project(t,n,o={}){if(typeof n!="function")throw new TypeError("Relationship event projection requires a reducer");let s=t,r=0,i;for(let a of this.stream({...o,batchSize:256}))for(let c of a)s=n(s,c),r+=1,i=c;return Object.freeze({state:s,version:i?.sequence??Math.max(0,(o.fromVersion??1)-1),processed:r,...i===void 0?{}:{asOf:i.timestamp}})}#i(t,n){let o=this.#n.require(n.kind);this.#s.identities.set(Ao(n,this.#n),t),o.outgoing==="one"&&this.#s.outgoingOne.set(`${o.kind}\0${n.source}`,t),o.incoming==="one"&&this.#s.incomingOne.set(`${o.kind}\0${n.target}`,t)}#a(t){let n=this.#n.require(t.kind);this.#s.identities.delete(Ao(t,this.#n)),n.outgoing==="one"&&this.#s.outgoingOne.delete(`${n.kind}\0${t.source}`),n.incoming==="one"&&this.#s.incomingOne.delete(`${n.kind}\0${t.target}`)}append(t){let n=xl(t,this.version,this.#r),o=this.#e.get(n.relationshipId),s=Rl(t,n.relationshipId,this.#e,this.#t,this.#n,this.#s),r=Object.freeze({eventId:n.eventId,relationshipId:n.relationshipId,action:t.action,...s===void 0?{}:{edge:s},author:n.author,timestamp:n.timestamp,...t.reason?.trim()?{reason:t.reason.trim()}:{},sequence:this.version+1});return this.#o.push(r),this.#r.add(n.eventId),o&&this.#a(o),t.action==="remove"?this.#e.delete(n.relationshipId):(this.#e.set(n.relationshipId,s),this.#i(n.relationshipId,s)),r}snapshot(t={}){if(t.atVersion!==void 0&&t.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let n;if(t.atTimestamp!==void 0){let r=Date.parse(t.atTimestamp);if(!Number.isFinite(r))throw new TypeError("Relationship snapshot timestamp must be valid");n=this.#o.filter(i=>Date.parse(i.timestamp)<=r)}else{let r=t.atVersion??this.version;if(!Number.isInteger(r)||r<0||r>this.version)throw new TypeError(`Relationship snapshot version out of range: ${r}`);n=this.#o.slice(0,r)}let o=El(n),s=new Ue(this.#t,o.values(),this.#n);return Object.freeze({version:n.at(-1)?.sequence??0,...n.at(-1)?{asOf:n.at(-1).timestamp}:{},edges:s.edges(),graph:s})}page(t){if(!Number.isInteger(t.limit)||t.limit<1)throw new TypeError("Relationship event page limit must be positive");let n=dr("relationship-events",{order:"append-sequence"}),o=t.cursor===void 0?this.version:Number(lr(t.cursor,n).snapshot);if(!Number.isSafeInteger(o)||o<0||o>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let s=mr(this.#o.slice(0,o),{cursor:t.cursor,fingerprint:n,limit:t.limit,readId:r=>r.eventId,snapshot:String(o)});return{version:o,events:s.rows,hasMore:s.has_more,...s.next_cursor?{nextCursor:s.next_cursor}:{}}}},Al="relationship-event-store",lc=vt.O_NOFOLLOW;function pn(e){return Y(e,Al,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function Fe(e,t="relationships/events.jsonl"){let n=fe.resolve(e),o=fe.resolve(n,t),s=fe.relative(n,o);if(s.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(s===".."||s.startsWith(`..${fe.sep}`)||fe.isAbsolute(s))throw new TypeError("Relationship event path must stay within the tracker root");if(await Ro(n,{recursive:!0}),(await cc(n)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let i=n;for(let a of s.split(fe.sep)){i=fe.join(i,a);try{if((await cc(i)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(c.code==="ENOENT")break;throw c}}return o}async function un(e,t,n){let o=new kt(t,{registry:n}),s,r;try{r=await dc(e,vt.O_RDONLY|lc),s=await r.readFile("utf8")}catch(a){if(a.code==="ENOENT")return{log:o,raw:""};throw a}finally{await r?.close()}let i=s.split(`
2
- `);for(let a=0;a<i.length;a+=1){let c=i[a].trim();if(!c)continue;let d;try{d=JSON.parse(c)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${a+1}`)}if(d.sequence!==o.version+1)throw new TypeError(`Invalid relationship event sequence at line ${a+1}`);o.append({eventId:d.eventId,relationshipId:d.relationshipId,action:d.action,...d.edge===void 0?{}:{edge:d.edge},author:d.author,timestamp:d.timestamp,...d.reason===void 0?{}:{reason:d.reason},expectedVersion:o.version})}return{log:o,raw:s}}function Cl(e,t,n,o){let s=Date.parse(t.timestamp),r;return t.action!=="remove"&&t.edge!==void 0&&(r=new Ue(n,[t.edge],o).edges()[0]),e.eventId===t.eventId.trim()&&e.relationshipId===t.relationshipId.trim()&&e.action===t.action&&e.author===t.author.trim()&&Number.isFinite(s)&&e.timestamp===new Date(s).toISOString()&&e.reason===(t.reason?.trim()||void 0)&&D(e.edge)===D(r)}var fn=class e{#t;#n;#o;#r;#e;constructor(t,n,o,s){this.#t=t.pmRoot,this.#n=n,this.#o=t.registry,this.#r=o,this.#e=s}static async open(t){let n=Object.freeze([...t.nodes]),o=await Fe(t.pmRoot,t.relativePath),s=await pn(t.pmRoot);try{await Fe(t.pmRoot,o);let{log:r}=await un(o,n,t.registry);return new e(t,n,o,r)}finally{await s()}}get path(){return this.#r}async currentVersion(){return this.#e=await this.#s(),this.#e.version}async append(t){let n=await pn(this.#t);try{let o=await Fe(this.#t,this.#r),{log:s}=await un(o,this.#n,this.#o),r=s.append(t);await Ro(fe.dirname(o),{recursive:!0}),await Fe(this.#t,o);let i=await dc(o,vt.O_APPEND|vt.O_CREAT|vt.O_WRONLY|lc);try{await i.appendFile(`${JSON.stringify(r)}
3
- `,"utf8")}finally{await i.close()}return this.#e=s,r}finally{await n()}}async appendBatch(t,n={}){let o=await pn(this.#t);try{let s=await Fe(this.#t,this.#r),{log:r,raw:i}=await un(s,this.#n,this.#o),a=r.version,c=new Map(r.events().map(m=>[m.eventId,m])),d=[],l=[];for(let m of t){let f=m.eventId.trim(),_=c.get(f);if(_!==void 0){if(n.existingEventPolicy==="skip_identical"&&Cl(_,m,this.#n,this.#o)){l.push(_.eventId);continue}if(n.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${f}`)}let y=r.append(m);c.set(y.eventId,y),d.push(y)}if(d.length>0){let m=i.length===0||i.endsWith(`
1
+ import{a as qa,b as Qe,c as mn,d as Ha,e as Ba,f as Va}from"./chunk-A2SJGHSI.js";import{A as vo,C as Ka,a as vt,b as fo,d as Ma,j as wo}from"./chunk-ZXOC6HG5.js";import{$ as Ra,$b as rc,A as ro,B as tn,Ba as an,C as io,D as be,Db as kt,E as ao,Eb as Ua,F as V,Fb as Ga,G as co,Ga as $a,Gb as ve,H as ie,Ha as cn,I as Zi,Ia as Fa,Ib as za,J as Qi,Jb as Ja,Jc as So,K as lo,Ka as Je,Kb as Xa,Kc as Io,L as ea,La,Lb as Za,M as mo,Ma as dn,Mc as ic,Oa as Xe,Qb as Qa,Ra as yo,Rb as ec,Sa as Na,Sb as tc,Sc as ac,T as ta,Ta as ln,Tb as nc,Tc as cc,Ub as oc,Uc as dc,W as wt,Wb as sc,X as Sa,Y as Ia,Z as Ea,_ as xa,_a as Ze,aa as Aa,gb as Le,hb as Da,jb as ja,nb as bo,qc as ko,r as Wi,s as b,sa as Ca,t as Ki,ta as po,u as Yi,va as Ta,w as te,wa as Oa,x as Ji,xa as uo,y as en,z as Xi}from"./chunk-2RA2YTHJ.js";import{$ as wa,A as na,C as Pe,D as oa,E as nn,F as sa,G as Fe,H as ra,I as on,J as ia,K as sn,Ka as rn,N as aa,P as ca,Q as da,Qa as Wa,R as la,S as ma,T as pa,U as ua,V as fa,W as _a,X as ha,Y as ga,Z as ya,_ as ba,aa as va,b as zi,ba as ka,xa as bt}from"./chunk-ZU34C3LH.js";import{A as Hi,Ha as Pa,Ob as _o,R as Bi,Za as we,b as Di,c as Jt,d as so,e as ji,f as Xt,g as Zt,gc as ho,h as Qt,i as Ui,l as Gi,lc as go,n as qi,nc as Ya,ua as Vi}from"./chunk-DSKYD4LG.js";import{$b as jn,$e as kr,$f as Xn,Aa as Mn,Ab as Js,Ac as or,Ad as ur,Af as Ce,Ah as Xr,Ai as ri,Ak as Ti,B as u,Bb as Xs,Bc as Kn,Bd as fr,Bg as fe,Bk as Oi,Cb as Zs,Cd as _r,Cf as jt,Ch as Zr,Cj as fi,Ck as $i,D as p,Db as Qs,Dc as sr,Df as Q,Dh as Qr,Dk as Pi,Ec as rr,Ee as br,Ef as Te,Eg as Nr,Eh as ei,F as Hs,Ff as Er,Fg as Mr,Fh as yt,G as ye,Gb as D,Gf as Oe,Gh as ti,Gk as Fi,Hb as er,Hf as xr,Hg as zt,Hh as Wt,Hk as Yt,Ia as P,Ih as ni,Ik as Li,Ja as Ft,Jc as ze,Jf as Ke,Jg as Dr,Jh as eo,Jk as Ni,Kf as Ut,Kh as to,Ki as ii,Le as wr,Lf as ue,Lh as oi,M as $n,Mc as ir,Mf as Gt,Mk as $,Nc as ar,Od as Yn,Oe as We,Of as Rr,Ok as Mi,P as k,Pc as He,Pd as C,Qa as I,Qc as xe,Qd as Ve,Qf as K,Qg as jr,R as Ct,Rc as cr,Sc as dr,Se as vr,T as Bs,Ta as A,Tc as Re,Tg as R,U as Tt,Ua as mt,Uc as lr,Ug as Ur,V as Ot,Vg as Gr,Vj as _i,W as $t,Wa as se,Wc as q,Wd as pe,Wf as Ye,Wg as qr,Wj as hi,X as Pt,Yc as ut,Zc as mr,Zf as Jn,_b as Dn,_f as _t,aa as le,ac as Un,ad as pr,bf as Sr,c as x,cc as tr,ch as Ht,ck as gi,d as Ms,e as G,ea as Vs,eh as Bt,ej as ai,ek as yi,f as B,fa as lt,fg as ht,fh as zr,g as dt,ge as hr,gg as Ar,gh as ee,gj as ci,h as Ds,ha as Pn,hd as ft,hg as Cr,hh as H,hj as Kt,ic as nr,ie as gr,ig as Tr,ij as di,jc as Gn,jd as Be,jg as Or,jh as $e,kc as qn,kd as Mt,kh as Hr,l as js,lc as zn,le as yr,lh as Br,lk as bi,m as Us,mb as Lt,mc as Hn,mh as Vt,mi as no,mk as wi,n as Gs,nc as Bn,nd as Dt,ng as qt,nh as gt,o as qs,oc as Vn,od as me,oh as Vr,oi as oo,oj as li,pc as Wn,pd as Ae,pg as $r,pk as vi,qc as O,qg as Pr,qh as Zn,rb as qe,sh as Qn,sk as ki,tk as Si,ug as Fr,uk as Ii,vc as Nt,vf as Ir,vk as Ei,w as zs,wc as pt,wh as Wr,wj as mi,wk as xi,xa as Fn,xb as Ws,xh as Kr,xj as pi,xk as Ri,ya as Ln,yb as Ks,yg as Lr,yh as Yr,yk as Ai,za as Nn,zb as Ys,zc as N,zf as re,zh as Jr,zi as si,zj as ui,zk as Ci}from"./chunk-HC3GM6YY.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]="bb16b445-3bd4-520d-becf-c55621bfa186")}catch{}})();var Sg=Ds,Ig=js,Eg=qs,xg=Us,Rg=Gs;function lc(e,t,n,o){let s=e.flag.slice(2).replace(/[-_]([a-z])/gu,(i,a)=>a.toUpperCase()),r=n.has(s);return{long:t,...o?{short:o}:{},description:e.description??`Standard pm ${e.flag} option.`,...e.required===!0?{required:!0}:{},...e.list===!0?{list:!0}:{},...e.repeatable===!0?{repeatable:!0}:{},value_type:r?"string":"boolean",...r?{value_name:e.value_name??"value"}:{}}}function mc(e,t=[]){let n=new Set(t.flatMap(s=>s.keys)),o=[];for(let s of ai(e.map(r=>({...r})))){o.push(lc(s,s.flag,n,s.short));for(let r of s.aliases??[])o.push(lc(s,r,n))}return o}var Ag=mc(Kt,si),Ol=mc(Yt,ri);import{AsyncLocalStorage as Ah}from"node:async_hooks";import yl 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]="27dd77f6-e53d-55b7-be15-db0e60eaec4e")}catch{}})();function pc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $l(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function Eo(e,t){let n=$l(t),o=n==="brief"?n:pc(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:pc(e.filters)?e.filters:{},projection: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]="6ede8efb-54ec-5b13-a1bf-216b525acc12")}catch{}})();async function uc(e,t){let n=I(t??process.cwd(),e),o=await R(n);return $e(n,o.item_format,P(o,null).type_to_folder,void 0,o.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9eae1a3-3eb6-5415-86c3-a8e8e1fedd1f")}catch{}})();function fc(e){return e.map(t=>({key:t.key,optionName:mr(t),metadataKey:t.metadata_key,type:t.type,commands:[...t.commands],repeatable:t.repeatable,requiredOnCreate:t.required_on_create,...t.description?{description:t.description}:{}}))}function _c(e){return e.map(t=>({command:t.command,action:t.action,arguments:t.arguments.map(n=>({name:n.name,required:n.required===!0,variadic:n.variadic===!0,description:n.description})),description:t.description,tier:t.tier??"standard"}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c898a52-eba4-5626-8207-5ffefd4990ba")}catch{}})();var Pl=50,ke=new Map;function xo(){ke.clear()}function hc(e,t){let n=ke.get(e);if(n!==void 0)return n;if(ke.size>=Pl){let s=ke.keys().next().value;ke.delete(s)}let o=t().catch(s=>{throw ke.get(e)===o&&ke.delete(e),s});return ke.set(e,o),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f62939a-7b99-5687-93ae-834e0032f1d5")}catch{}})();var Fl={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function gc(e){return Object.fromEntries(kr.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Ro={ctx:{action:"context"},...Fl,...gc("extension"),...gc("package")};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="41012e87-ed61-56b2-8505-8f786b3952b2")}catch{}})();var yc="PmCliError";function Ll(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=u.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function Nl(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new p(e,Ll(t.exitCode??u.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Ao(e){if(!(e instanceof Error)||e.name!==yc)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}import{constants as St}from"node:fs";import{lstat as bc,mkdir as To,open as wc}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]="c53bb1b7-12b9-5370-a85b-cdd8bef57936")}catch{}})();function Co(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Relationship event ${t} must be non-empty`);return e.trim()}function Oo(e,t){let n=t.require(e.kind),o=n.direction==="undirected"?[e.source,e.target].sort().join("\0"):`${e.source}\0${e.target}`;return`${n.kind}\0${o}`}function Ml(e){return Object.freeze({...e,...e.payload===void 0?{}:{payload:Object.freeze(structuredClone(e.payload))}})}function Dl(e,t,n,o){let s=n.require(e.kind),r=o.outgoingOne.get(`${s.kind}\0${e.source}`);if(r!==void 0&&r!==t)throw new TypeError(`Relationship outgoing cardinality exceeded for ${s.kind}`);let i=o.incomingOne.get(`${s.kind}\0${e.target}`);if(i!==void 0&&i!==t)throw new TypeError(`Relationship incoming cardinality exceeded for ${s.kind}`);let a=Oo(e,n),c=o.identities.get(a);if(c!==void 0&&c!==t)throw new TypeError(`Relationship edge already active: ${a}`)}function jl(e){let t=new Map;for(let n of e)n.action==="remove"?t.delete(n.relationshipId):t.set(n.relationshipId,n.edge);return t}function Ul(e,t,n){if(e.expectedVersion!==void 0&&e.expectedVersion!==t)throw new TypeError(`Relationship event version conflict: expected ${e.expectedVersion}, current ${t}`);let o=Co(e.eventId,"eventId");if(n.has(o))throw new TypeError(`Relationship event already exists: ${o}`);if(e.action!=="add"&&e.action!=="remove"&&e.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${e.action}`);if(!Number.isFinite(Date.parse(e.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:o,relationshipId:Co(e.relationshipId,"relationshipId"),author:Co(e.author,"author"),timestamp:new Date(e.timestamp).toISOString()}}function Gl(e,t,n,o,s,r){let i=n.has(t);if(e.action==="add"&&i)throw new TypeError(`Relationship is already active: ${t}`);if(e.action!=="add"&&!i)throw new TypeError(`Relationship is not active: ${t}`);if(e.action==="remove")return;if(!e.edge)throw new TypeError(`Relationship ${e.action} event requires an edge`);let a=typeof e.edge.source=="string"?e.edge.source.trim():"",c=typeof e.edge.target=="string"?e.edge.target.trim():"";if(!o.has(a)||!o.has(c))throw new TypeError(`Relationship endpoint not found: ${a} -> ${c}`);let d=new qe([a,c],[e.edge],s).edges()[0];return Dl(d,t,s,r),Ml(d)}var It=class{#t;#n;#o=[];#r=new Set;#e=new Map;#s={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(t,n={}){this.#t=new Set([...t].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)),this.#n=n.registry??Lt()}get version(){return this.#o.length}events(){return Object.freeze([...this.#o])}*stream(t={}){let n=t.fromVersion??1,o=t.toVersion??this.version,s=t.batchSize??100;if(!Number.isInteger(n)||n<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${o}`);if(!Number.isInteger(s)||s<1)throw new TypeError("Relationship event stream batchSize must be positive");if(n>o+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let r=n-1;r<o;r+=s)yield Object.freeze(this.#o.slice(r,Math.min(r+s,o)))}project(t,n,o={}){if(typeof n!="function")throw new TypeError("Relationship event projection requires a reducer");let s=t,r=0,i;for(let a of this.stream({...o,batchSize:256}))for(let c of a)s=n(s,c),r+=1,i=c;return Object.freeze({state:s,version:i?.sequence??Math.max(0,(o.fromVersion??1)-1),processed:r,...i===void 0?{}:{asOf:i.timestamp}})}#i(t,n){let o=this.#n.require(n.kind);this.#s.identities.set(Oo(n,this.#n),t),o.outgoing==="one"&&this.#s.outgoingOne.set(`${o.kind}\0${n.source}`,t),o.incoming==="one"&&this.#s.incomingOne.set(`${o.kind}\0${n.target}`,t)}#a(t){let n=this.#n.require(t.kind);this.#s.identities.delete(Oo(t,this.#n)),n.outgoing==="one"&&this.#s.outgoingOne.delete(`${n.kind}\0${t.source}`),n.incoming==="one"&&this.#s.incomingOne.delete(`${n.kind}\0${t.target}`)}append(t){let n=Ul(t,this.version,this.#r),o=this.#e.get(n.relationshipId),s=Gl(t,n.relationshipId,this.#e,this.#t,this.#n,this.#s),r=Object.freeze({eventId:n.eventId,relationshipId:n.relationshipId,action:t.action,...s===void 0?{}:{edge:s},author:n.author,timestamp:n.timestamp,...t.reason?.trim()?{reason:t.reason.trim()}:{},sequence:this.version+1});return this.#o.push(r),this.#r.add(n.eventId),o&&this.#a(o),t.action==="remove"?this.#e.delete(n.relationshipId):(this.#e.set(n.relationshipId,s),this.#i(n.relationshipId,s)),r}snapshot(t={}){if(t.atVersion!==void 0&&t.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let n;if(t.atTimestamp!==void 0){let r=Date.parse(t.atTimestamp);if(!Number.isFinite(r))throw new TypeError("Relationship snapshot timestamp must be valid");n=this.#o.filter(i=>Date.parse(i.timestamp)<=r)}else{let r=t.atVersion??this.version;if(!Number.isInteger(r)||r<0||r>this.version)throw new TypeError(`Relationship snapshot version out of range: ${r}`);n=this.#o.slice(0,r)}let o=jl(n),s=new qe(this.#t,o.values(),this.#n);return Object.freeze({version:n.at(-1)?.sequence??0,...n.at(-1)?{asOf:n.at(-1).timestamp}:{},edges:s.edges(),graph:s})}page(t){if(!Number.isInteger(t.limit)||t.limit<1)throw new TypeError("Relationship event page limit must be positive");let n=hr("relationship-events",{order:"append-sequence"}),o=t.cursor===void 0?this.version:Number(gr(t.cursor,n).snapshot);if(!Number.isSafeInteger(o)||o<0||o>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let s=yr(this.#o.slice(0,o),{cursor:t.cursor,fingerprint:n,limit:t.limit,readId:r=>r.eventId,snapshot:String(o)});return{version:o,events:s.rows,hasMore:s.has_more,...s.next_cursor?{nextCursor:s.next_cursor}:{}}}},ql="relationship-event-store",vc=St.O_NOFOLLOW;function pn(e){return K(e,ql,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function Ne(e,t="relationships/events.jsonl"){let n=_e.resolve(e),o=_e.resolve(n,t),s=_e.relative(n,o);if(s.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(s===".."||s.startsWith(`..${_e.sep}`)||_e.isAbsolute(s))throw new TypeError("Relationship event path must stay within the tracker root");if(await To(n,{recursive:!0}),(await bc(n)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let i=n;for(let a of s.split(_e.sep)){i=_e.join(i,a);try{if((await bc(i)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(c.code==="ENOENT")break;throw c}}return o}async function un(e,t,n){let o=new It(t,{registry:n}),s,r;try{r=await wc(e,St.O_RDONLY|vc),s=await r.readFile("utf8")}catch(a){if(a.code==="ENOENT")return{log:o,raw:""};throw a}finally{await r?.close()}let i=s.split(`
2
+ `);for(let a=0;a<i.length;a+=1){let c=i[a].trim();if(!c)continue;let d;try{d=JSON.parse(c)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${a+1}`)}if(d.sequence!==o.version+1)throw new TypeError(`Invalid relationship event sequence at line ${a+1}`);o.append({eventId:d.eventId,relationshipId:d.relationshipId,action:d.action,...d.edge===void 0?{}:{edge:d.edge},author:d.author,timestamp:d.timestamp,...d.reason===void 0?{}:{reason:d.reason},expectedVersion:o.version})}return{log:o,raw:s}}function zl(e,t,n,o){let s=Date.parse(t.timestamp),r;return t.action!=="remove"&&t.edge!==void 0&&(r=new qe(n,[t.edge],o).edges()[0]),e.eventId===t.eventId.trim()&&e.relationshipId===t.relationshipId.trim()&&e.action===t.action&&e.author===t.author.trim()&&Number.isFinite(s)&&e.timestamp===new Date(s).toISOString()&&e.reason===(t.reason?.trim()||void 0)&&D(e.edge)===D(r)}var fn=class e{#t;#n;#o;#r;#e;constructor(t,n,o,s){this.#t=t.pmRoot,this.#n=n,this.#o=t.registry,this.#r=o,this.#e=s}static async open(t){let n=Object.freeze([...t.nodes]),o=await Ne(t.pmRoot,t.relativePath),s=await pn(t.pmRoot);try{await Ne(t.pmRoot,o);let{log:r}=await un(o,n,t.registry);return new e(t,n,o,r)}finally{await s()}}get path(){return this.#r}async currentVersion(){return this.#e=await this.#s(),this.#e.version}async append(t){let n=await pn(this.#t);try{let o=await Ne(this.#t,this.#r),{log:s}=await un(o,this.#n,this.#o),r=s.append(t);await To(_e.dirname(o),{recursive:!0}),await Ne(this.#t,o);let i=await wc(o,St.O_APPEND|St.O_CREAT|St.O_WRONLY|vc);try{await i.appendFile(`${JSON.stringify(r)}
3
+ `,"utf8")}finally{await i.close()}return this.#e=s,r}finally{await n()}}async appendBatch(t,n={}){let o=await pn(this.#t);try{let s=await Ne(this.#t,this.#r),{log:r,raw:i}=await un(s,this.#n,this.#o),a=r.version,c=new Map(r.events().map(m=>[m.eventId,m])),d=[],l=[];for(let m of t){let f=m.eventId.trim(),_=c.get(f);if(_!==void 0){if(n.existingEventPolicy==="skip_identical"&&zl(_,m,this.#n,this.#o)){l.push(_.eventId);continue}if(n.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${f}`)}let y=r.append(m);c.set(y.eventId,y),d.push(y)}if(d.length>0){let m=i.length===0||i.endsWith(`
4
4
  `)?i:`${i}
5
- `;await Ro(fe.dirname(s),{recursive:!0}),await Fe(this.#t,s),await V(s,`${m}${d.map(f=>JSON.stringify(f)).join(`
5
+ `;await To(_e.dirname(s),{recursive:!0}),await Ne(this.#t,s),await B(s,`${m}${d.map(f=>JSON.stringify(f)).join(`
6
6
  `)}
7
- `)}return this.#e=r,Object.freeze({version_before:a,version_after:r.version,appended:Object.freeze(d),skipped_event_ids:Object.freeze(l)})}finally{await o()}}async snapshot(t={}){return this.#e=await this.#s(),this.#e.snapshot(t)}async page(t){return this.#e=await this.#s(),this.#e.page(t)}async*stream(t={}){this.#e=await this.#s(),yield*this.#e.stream(t)}async project(t,n,o={}){return this.#e=await this.#s(),this.#e.project(t,n,o)}async#s(){let t=await pn(this.#t);try{let n=await Fe(this.#t,this.#r);return(await un(n,this.#n,this.#o)).log}finally{await t()}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff13ec2a-64a8-5512-973f-5447be945978")}catch{}})();function Co(e){let t=Ft();for(let n of e)t.register(n);return t}function mc(e,t){return{client:t,isItemNotFoundError:n=>Eo(n)&&n.exitCode===u.NOT_FOUND,getItemAt:(n,o)=>Mi(n,o,{pmRoot:e}),openRelationshipEventStore:n=>fn.open({pmRoot:e,nodes:n.nodes,registry:Co(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new Ue(n.nodes,n.edges,Co(n.definitions)),analyzeRelationshipImpact:(n,o,s)=>Di(n,o,s),validateRelationshipEvents:n=>{let o=new kt(n.nodes,{registry:Co(n.definitions)});return n.events.map(s=>o.append({...s,expectedVersion:o.version}))},commitWorkspaceTransaction:n=>ji({...n,pmRoot:e})}}import{readFile as Tl}from"node:fs/promises";import Ol 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]="55ecd7ff-0047-5fd1-9f6f-f45602fce1bb")}catch{}})();var To="context-intents.json";function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $l(e,t,n){if(!St(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let o=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(o)||!o.every(s=>typeof s=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:o,token_budget:e.token_budget}}function pc(e,t){let n=Array.isArray(e)?e:St(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((o,s)=>$l(o,t,s))}async function Pl(e){let t=Ol.join(e,To),n;try{n=await Tl(t,"utf8")}catch(s){if(St(s)&&typeof s.code=="string"&&s.code==="ENOENT")return[];throw s}let o;try{o=JSON.parse(n)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`Invalid ${To}: ${r}`,{cause:s})}return pc(o,To)}function Fl(e){if(!St(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return St(n)?n.contextIntents??n.context_intents:void 0}function Ll(e){return e.flatMap(t=>{let n=Fl(t.module);return n===void 0?[]:pc(n,`package ${t.name}`)})}async function Nl(e){let t=await Pl(e.pmRoot),n=Ll(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Oo(e,t){let n=await Nl(e);return await ur(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e3ba7e9-8822-53ba-981e-e177be5219f3")}catch{}})();async function fc(e,t,n){if(t.body===void 0)throw new p("Missing required --body text",u.USAGE);let o=Gt(),s=x(process.cwd(),n.path);if(!await E(A(s)))throw new p(`Tracker is not initialized at ${s}. Run pm init first.`,u.NOT_FOUND);let r=await R(s),i=O(t.author,r.author_default),c=(await o.resolveValue(t.body,"--body")).trim();if(c.length===0)throw new p("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",u.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let d=await _t({pmRoot:s,settings:r,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(l){let m=l.body.trim().length>0?`
7
+ `)}return this.#e=r,Object.freeze({version_before:a,version_after:r.version,appended:Object.freeze(d),skipped_event_ids:Object.freeze(l)})}finally{await o()}}async snapshot(t={}){return this.#e=await this.#s(),this.#e.snapshot(t)}async page(t){return this.#e=await this.#s(),this.#e.page(t)}async*stream(t={}){this.#e=await this.#s(),yield*this.#e.stream(t)}async project(t,n,o={}){return this.#e=await this.#s(),this.#e.project(t,n,o)}async#s(){let t=await pn(this.#t);try{let n=await Ne(this.#t,this.#r);return(await un(n,this.#n,this.#o)).log}finally{await t()}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff13ec2a-64a8-5512-973f-5447be945978")}catch{}})();function $o(e){let t=Lt();for(let n of e)t.register(n);return t}function kc(e,t){return{client:t,isItemNotFoundError:n=>Ao(n)&&n.exitCode===u.NOT_FOUND,getItemAt:(n,o)=>Gi(n,o,{pmRoot:e}),openRelationshipEventStore:n=>fn.open({pmRoot:e,nodes:n.nodes,registry:$o(n.definitions),...n.relativePath===void 0?{}:{relativePath:n.relativePath}}),createRelationshipGraph:n=>new qe(n.nodes,n.edges,$o(n.definitions)),analyzeRelationshipImpact:(n,o,s)=>qi(n,o,s),validateRelationshipEvents:n=>{let o=new It(n.nodes,{registry:$o(n.definitions)});return n.events.map(s=>o.append({...s,expectedVersion:o.version}))},commitWorkspaceTransaction:n=>zi({...n,pmRoot:e})}}import{readFile as Hl}from"node:fs/promises";import Bl from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ba0243e-98d1-5aef-bd47-54f0b630be58")}catch{}})();var Po="context-intents.json";function _n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vl(e,t,n){if(!_n(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let o=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(o)||!o.every(s=>typeof s=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:o,token_budget:e.token_budget}}function Sc(e,t){let n=Array.isArray(e)?e:_n(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((o,s)=>Vl(o,t,s))}async function Wl(e){let t=Bl.join(e,Po),n;try{n=await Hl(t,"utf8")}catch(s){if(Ms(s))return[];throw s}let o;try{o=JSON.parse(n)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`Invalid ${Po}: ${r}`,{cause:s})}return Sc(o,Po)}function Kl(e){if(!_n(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return _n(n)?n.contextIntents??n.context_intents:void 0}function Yl(e){return e.flatMap(t=>{let n=Kl(t.module);return n===void 0?[]:Sc(n,`package ${t.name}`)})}async function Jl(e){let t=await Wl(e.pmRoot),n=Yl(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Fo(e,t){let n=await Jl(e);return await wr(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e3ba7e9-8822-53ba-981e-e177be5219f3")}catch{}})();async function Ec(e,t,n){if(t.body===void 0)throw new p("Missing required --body text",u.USAGE);let o=qt(),s=I(process.cwd(),n.path);if(!await x(A(s)))throw new p(`Tracker is not initialized at ${s}. Run pm init first.`,u.NOT_FOUND);let r=await R(s),i=C(t.author,r.author_default),c=(await o.resolveValue(t.body,"--body")).trim();if(c.length===0)throw new p("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",u.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let d=await gt({pmRoot:s,settings:r,id:e,op:"append",author:i,message:t.message,force:t.force,mutate(l){let m=l.body.trim().length>0?`
8
8
 
9
9
  `:"";return l.body=`${l.body.trimEnd()}${m}${c}
10
- `,{changedFields:["body"]}}});return{item:d.item,appended:c,changed_fields:d.changedFields}}import Ml from"fast-json-patch";import $o from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="353be665-9f67-5d0e-99c9-6bbb7e927e0b")}catch{}})();function Dl(e,t){return Fi(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function jl(e){let t=no(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Re(Ce(t))}async function Ul(e,t,n,o){let s=await te(e,t,n.id_prefix,n.item_format,o);if(s){let c=se(e,s.id),d=await wr({pmRoot:e,settings:n,itemId:s.id,commandLabel:"restore"});return{id:s.id,historyPath:c,located:s,historyPolicyWarnings:d.warnings}}let r=ut(t,n.id_prefix),i=Kn(t),a=r===i?[r]:[r,i];for(let c of a){let d=se(e,c);if(await E(d))return{id:c,historyPath:d,located:null,historyPolicyWarnings:[]}}throw new p(`Item ${t} not found`,u.NOT_FOUND)}function Gl(e,t){let n=Te(e),o=Te(t),s=Ml.compare(n,o),r=new Set;for(let i of s){if(i.path==="/body"||i.path.startsWith("/body/")){r.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];r.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(r).sort((i,a)=>i.localeCompare(a))}async function ql(e){if(await G(e.subject.historyPath)!==e.historyRawBeforeLock)throw new p(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,u.CONFLICT);let n=await te(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),o=n?await H(n,{schema:e.settings.schema}):null;if((o?.raw??null)!==e.currentItemRawBeforeLock)throw new p(`Item ${e.resolvedId} changed while waiting for lock; retry restore.`,u.CONFLICT);return{loadedItemUnderLock:o,existingItemPath:n?.itemPath??null}}function zl(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:jl(t),originalRaw:null}}function Hl(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new p(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,u.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function Bl(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await V(e.existingItemPath,e.resolvedOriginalRaw),await $o.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await V(e.existingItemPath,e.resolvedOriginalRaw);return}await $o.rm(e.restoredItemPath,{force:!0})}async function Vl(e){return[...await N({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await N({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Le(e,t,n,o){let s=x(process.cwd(),o.path);if(!await E(A(s)))throw new p(`Tracker is not initialized at ${s}. Run pm init first.`,u.NOT_FOUND);let r=await R(s),i=F(r,T()),a=await Ul(s,e,r,i.type_to_folder),c=a.id,d=await G(a.historyPath),l=await ze(a.historyPath,c);if(l.length===0)throw new p(`No history exists for ${c}; restore is unavailable.`,u.NOT_FOUND);let m=Dl(t,l),f=Li(no(l,m.historyIndex),m),_=yr(f,{schema:r.schema});if(_.metadata.id!==c)throw new p(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,u.GENERIC_FAILURE);let w=(a.located?await H(a.located,{schema:r.schema}):null)?.raw??null,g=O(n.author,r.author_default),h=await Y(s,c,r.locks.ttl_seconds,g,!!n.force,r.governance.force_required_for_stale_lock,r.locks.wait_ms);try{let{loadedItemUnderLock:k,existingItemPath:I}=await ql({pmRoot:s,resolvedId:c,subject:a,settings:r,typeToFolder:i.type_to_folder,historyRawBeforeLock:d,currentItemRawBeforeLock:w}),P="toon",C=zl(k,l),j=Hl({document:C.document,author:g,force:n.force,enforcement:r.governance.ownership_enforcement,resolvedId:c}),U=Gl(C.document,_);await Qs({pm_root:s,operation:"restore",before:C.document,after:_,changed_fields:U,sdk:Dr({pmRoot:s,settings:r,typeToFolder:i.type_to_folder})});let Q=le(_,{format:P,schema:r.schema}),de=dt(s,_.metadata.type,c,P,i.type_to_folder),Ie=await zt(s,g),oe=[];try{await V(de,Q),I&&de!==I&&await $o.rm(I);let _l=re({nowIso:S(),author:g,op:"restore",before:C.document,after:_,message:n.message});try{await Ae(a.historyPath,_l)}catch(hl){throw await Bl({existingItemPath:I,resolvedOriginalRaw:C.originalRaw,restoredItemPath:de}),hl}oe=await Ht({pmRoot:s,preferredFormat:r.item_format,typeToFolder:i.type_to_folder,schema:r.schema,itemPath:de,previousItemPath:I??void 0,document:_})}finally{await Ie()}let fl=await Vl({restoredItemPath:de,historyPath:a.historyPath,before:C.document,after:_});Lt({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:C.document.metadata.status,status:_.metadata.status,previous:lt(C.document.metadata,U),current:lt(_.metadata,U),changed_fields:U});let Ps=l[m.historyIndex];return{item:_.metadata,restored_from:{kind:m.kind,target:m.raw,history_index:m.historyIndex+1,entry_ts:Ps.ts,entry_op:Ps.op},changed_fields:U,warnings:[...a.historyPolicyWarnings,...j,...oe,...fl]}}finally{await h()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4da07a98-855e-59cf-a6a4-2f59a8b3c0bd")}catch{}})();var hc=1,Po="close-many",Wl=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function Kl(e,t){return gt(e,t,{includePagination:!1})}function Yl(e,t){return gt(e,t)}function Jl(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new p("--ids requires at least one non-empty item ID",u.USAGE)}function Xl(e){let t={};if(!e)return t;for(let[n,o]of Object.entries(e))o==null||typeof o=="string"&&!o.split(",").some(s=>s.trim().length>0)||(t[n]=o);return t}function Zl(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new p("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",u.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function Ql(e,t){let n=q(t.schema),o=F(t,T()),s=await Bt(e,t.item_format,o.type_to_folder,void 0,t.schema),r=new Map,i=new Map;for(let a of s){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),qe(a.status,n)))continue;let c=r.get(a.parent);c?c.push(a.id):r.set(a.parent,[a.id])}for(let a of r.values())a.sort((c,d)=>c.localeCompare(d));return{childrenByParent:r,parentByChild:i}}function _c(e,t,n){let o=n?.get(e);if(o!==void 0)return o;let s=0,r=t.get(e),i=[],a=new Set,c=!1;for(;r!==void 0&&!a.has(r);){let d=n?.get(r);if(d!==void 0){s+=d+1;break}a.add(r),i.push(r),s+=1,r=t.get(r)}if(r!==void 0&&a.has(r)&&(c=!0),!c){n?.set(e,s);for(let[d,l]of i.entries())n?.set(l,s-d-1)}return s}async function em(e){let t=await Ot(e.pmRoot,Po,e.rollbackId,hc),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,o=await $t(t.items,(s,r)=>Le(s,r,{author:e.options.author,message:n,force:!0},e.global));return{...Oe({applied:o.restored_ids.length,skipped:0,failed:o.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:o.restored_ids.length,failed_count:o.failed_count,rows:o.rows,ids:o.restored_ids}}function tm(e,t,n,o,s){return e.map(r=>{let i=(t.get(r.id)??[]).filter(c=>!n.has(c)),a=!gc(r,o,s);return{id:r.id,title:typeof r.title=="string"?r.title:"",status:r.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function nm(e){let t=await Tt(e.pmRoot,Po,e.checkpointId,{schema_version:hc,id:e.checkpointId,created_at:e.nowValue,author:O(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function om(e){let t=[],n=[];for(let o of e.matched){if(!e.closableIds.has(o.id)){t.push({id:o.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let s=await Je(o.id,e.reason,e.closeOptions,e.global);t.push({id:o.id,status:"closed",changed_fields:s.changed_fields,...s.warnings&&s.warnings.length>0?{warnings:s.warnings}:{}}),n.push(o.id)}catch(s){t.push({id:o.id,status:"failed",error:ge(s)})}}return{rows:t,closedIds:n}}function sm(e){return typeof e.rollback=="string"?e.rollback:void 0}function rm(e,t){if(t.trim().length===0)throw new p("--rollback requires a checkpoint id",u.USAGE);if(e.dryRun===!0)throw new p("--dry-run cannot be combined with --rollback",u.USAGE);if(Yl(e.list,e.status))throw new p("Rollback mode does not accept filter options",u.USAGE)}function im(e){if(!Kl(e.list,e.status))throw new p(`close-many requires at least one filter to scope the close (for example: ${Wl}). Refusing to match every item.`,u.USAGE)}function am(e,t){let n=new Map;return[...e].sort((o,s)=>{let r=_c(s.id,t,n)-_c(o.id,t,n);return r!==0?r:o.id.localeCompare(s.id)})}function gc(e,t,n){return n||!qe(e.status,t)}function cm(e,t,n){return new Set(e.filter(o=>gc(o,t,n)).map(o=>o.id))}async function dm(e){im(e.options);let t=q(e.settings.schema),n=Zl(e.options.reason,e.settings.governance.require_close_reason),o=e.options.force===!0,s=await ye(e.options.status,Xl(e.options.list),e.global),{childrenByParent:r,parentByChild:i}=await Ql(e.pmRoot,e.settings),a=am(s.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(m=>m.trim()).filter(m=>m.length>0))],d=new Set(a.map(m=>m.id)),l=cm(a,t,o);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:o,listed:s,matched:a,unmatchedIds:c.filter(m=>!d.has(m)),planRows:tm(a,r,l,t,o)}}function lm(e){return{outcome:"effect",exit_code:u.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds.length>0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function mm(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return nm({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function yc(e,t){let n=x(process.cwd(),t.path);if(!await E(A(n)))throw new p(`Tracker is not initialized at ${n}. Run pm init first.`,u.NOT_FOUND);let o=await R(n),s=e.dryRun===!0,r=sm(e);if(Jl(e.list),r!==void 0)return rm(e,r),em({pmRoot:n,rollbackId:r,options:e,global:t});let i=await dm({pmRoot:n,settings:o,options:e,global:t});if(s)return lm(i);let a=new Set(i.planRows.filter(h=>h.action==="close").map(h=>h.id)),c=S(),d=Ct(Po,c),l=await mm({context:i,options:e,closableIds:a,checkpointId:d,nowValue:c}),m={author:e.author,message:e.message??`close-many apply ${d}`,completedAt:e.completedAt,validateClose:i.validateCloseMode,force:i.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await om({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:m,global:t}),y=f.filter(h=>h.status==="closed").length,w=f.filter(h=>h.status==="skipped").length,g=f.filter(h=>h.status==="failed").length;return{...Oe({applied:y,skipped:w,failed:g,unmatched:i.unmatchedIds.length}),mode:"apply",matched_count:i.matched.length,dry_run:!1,...i.reason!==void 0?{reason:i.reason}:{},filters:i.listed.filters,...i.validateCloseMode?{validate_close:i.validateCloseMode}:{},...l?{checkpoint:l}:{},closed_count:y,skipped_count:w,failed_count:g,rows:f,ids:_,...i.unmatchedIds.length>0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as pm}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="667218ac-866c-59b1-8309-18ad92434fca")}catch{}})();async function Fo(e,t){let n=e.add!==void 0,o=e.stdin===!0,s=typeof e.file=="string",r=Number(n)+Number(o)+Number(s);if(r===0)return;if(r>1)throw new p("Specify comment text using only one input source: --add, --stdin, or --file",u.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add")??"",emptyFlag:"--add"};if(o)return{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new p("--file path cannot be empty",u.USAGE);try{return{value:await pm(i,"utf8"),emptyFlag:"--file"}}catch(a){if(zi(a)&&a.code==="ENOENT")throw new p(`--file path not found: ${i}`,u.USAGE);let c=a instanceof Error?a.message:String(a);throw new p(`Failed to read --file path "${i}": ${c}`,u.USAGE)}}async function um(e,t){let n=e.edit,o=e.delete,s=n!==void 0,r=o!==void 0;if(s&&r)throw new p("Specify only one of --edit or --delete",u.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new p("--edit must be a positive integer",u.USAGE);if(o!==void 0&&(!Number.isInteger(o)||o<1))throw new p("--delete must be a positive integer",u.USAGE);if(r){if(await Fo(e,t)!==void 0)throw new p("--delete does not take comment text",u.USAGE);return{mode:"delete",index:o}}if(s){let c=await Fo(e,t);if(c===void 0)throw new p("--edit requires replacement text via positional [text], --add, --stdin, or --file",u.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let i=await Fo(e,t);return i===void 0?{mode:"list"}:{mode:i.emptyFlag==="--add"?"add":i.emptyFlag==="--stdin"?"stdin":"file",value:i.value,emptyFlag:i.emptyFlag}}async function bc(e,t,n){let o=Gt(),s=await um(t,o),r=s.mode==="add"||s.mode==="edit",i=s.value??"";return Ye(e,t,n,{input:{...s,rawValue:t.add??i,value:r?Ke(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(s.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="93184f29-f215-5413-9628-fb5b34523995")}catch{}})();async function wc(e,t,n){return Ye(e,t,n,{input:await tn(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:o=>Ke(o),createEntry:o=>o,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm learnings pm-a1b2 --add "review learning" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebd9f151-593f-5081-97da-d78f83de4914")}catch{}})();function fm(e){if(e===void 0)return;if(e.trim().length===0)throw new p("--add-json must contain a JSON value",u.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new p("--add-json must be valid JSON",u.USAGE,{code:"structured_event_json_invalid"})}return t}function _m(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function hm(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new p("--since must be a valid ISO timestamp",u.USAGE,{code:"structured_event_since_invalid"});return t}async function vc(e,t,n){let o=fm(t.addJson),s=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(o!==void 0&&s)throw new p("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",u.USAGE,{code:"structured_event_input_conflict"});let r=o===void 0?void 0:D(o),i=[t.since,t.eventType].some(y=>y!==void 0),a=hm(t.since),c=Ar(t.limit),d=await Ye(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await tn(r===void 0?t:{add:r},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:y=>Ke(y),createEntry:y=>o===void 0?y:{...y,format:"json",data:o,event_type:_m(o)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),l=t.eventType?.trim(),m=d.notes.filter(y=>{let w=[y.format==="json",y.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(y.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),h=[!l,y.event_type===l].includes(!0);return[!i,[w,g,h].every(Boolean)].includes(!0)}),f=i?qi(m,c):m,_=f.filter(y=>y.format==="json").length;return{...d,notes:f,count:f.length,...i?{total_count:m.length,returned_count:f.length,has_more:f.length<m.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67f8958d-60d5-5657-93ce-9803859acd9e")}catch{}})();var Sc=1,No="update-many",gm=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass"]),ym=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),bm={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},wm=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],vm={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},Ic=e=>{let t={};for(let[n,o]of Object.entries(e))gm.has(n)||o!==void 0&&(t[n]=o);return t},km=e=>Object.keys(Ic(e)).length>0,Ec=e=>typeof e=="string"?e.trim():e,Sm=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Lo=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},Im=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Ec(e)},Em={priority:Sm,estimatedMinutes:Lo,order:Lo,rank:Lo,regression:Im},xm=(e,t)=>{if(t!==void 0)return(Em[e]??Ec)(t)},Rm=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return vm[t]??t},_n=(e,t)=>Js(e,t),Am=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],Cm=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,Tm=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",kc=(e,t)=>t===void 0?void 0:e[t],Ze=e=>Array.isArray(e)?e.length:0,Om=(e,t,n)=>{let o=n[e.addKey],s=kc(n,e.removeKey),r=Ze(o),i=Ze(s),a=n[e.clearKey]===!0,c=kc(n,e.replaceKey)===!0;if(![a,c,r>0,i>0].includes(!0))return;let d=Am(e.field,t[e.field]);return{field:e.field,before:d,after:{operation:Tm({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:r,remove_count:i,before_count:Cm(e.field,d)}}},$m=(e,t)=>{let n=[];for(let o of wm){let s=Om(o,e,t);s!==void 0&&n.push(s)}return n},Pm=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],Fm=(e,t)=>{if(![t.tags!==void 0,Ze(t.addTags)>0,Ze(t.removeTags)>0].includes(!0))return;let n=Pm(e.tags),o=t.tags===void 0?n:ft(t.tags),s=Sr(o,t.addTags),r=Ir(s,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!_n(i,r))return{field:"tags",before:n,after:r}},Lm=(e,t)=>{let n=e.acceptance_criteria,o=t.acceptanceCriteria===void 0?n:String(t.acceptanceCriteria).trim(),s=kr(vr(o),t.addAc,t.removeAc),r=s.unmatchedRemovals.map(a=>`remove_ac_unmatched:${a}`),i=s.criteria.join("; ");return _n(n,i)||n===void 0&&i===""?{warnings:r}:{change:{field:"acceptance_criteria",before:n,after:i},warnings:r}},Nm=(e,t,n)=>{for(let[o,s]of Object.entries(bm)){let r=n[o];if(r===void 0)continue;let i=t[s],a=xm(o,r);_n(i,a)||e.push({field:s,before:i,after:a})}},Mm=(e,t,n,o)=>{let s=cr(n,o,["update_many"]);for(let[r,i]of Object.entries(s)){let a=t[r];_n(a,i)||e.push({field:r,before:a,after:i})}},Dm=(e,t,n)=>{for(let o of n??[]){let s=Rm(o),r=t[s];r!==void 0&&e.push({field:s,before:r,after:null})}},jm=(e,t,n={})=>{let o=e,s=[],r=[],i=Fm(o,n);if(i&&s.push(i),Nm(s,o,n),Ze(n.addAc)>0||Ze(n.removeAc)>0){let a=Lm(o,n),c=s.filter(d=>d.field!=="acceptance_criteria");s.splice(0,s.length,...c),a.change!==void 0&&s.push(a.change),r.push(...a.warnings)}return s.push(...$m(o,n)),Mm(s,o,n,t),Dm(s,o,n.unset),{id:e.id,changes:s,...r.length>0?{warnings:r}:{}}},Um=(e,t)=>Rr(e,t,{strict:!0,flagLabel:"--filter-status"}),Gm=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new p("--ids requires at least one non-empty item ID",u.USAGE)},qm=[({update:e})=>{e.priority!==void 0&&xr(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let o=F(t,T());if(!Pt(e.type,o))throw new p(Or(e.type,o.types,ir(n,t.schema)),u.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!pt(e.status,t)){let n=t.definitions.map(o=>o.id);throw new p(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,u.USAGE)}},({update:e})=>{e.deadline!==void 0&&Gs(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&Er(e.estimatedMinutes,"estimated-minutes")}],zm=(e,t,n,o)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:o};for(let r of qm)r(s)},Hm=async e=>{let t=await Ot(e.pmRoot,No,e.rollbackId,Sc),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,o=await $t(t.items,(s,r)=>Le(s,r,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Oe({applied:o.restored_ids.length,skipped:0,failed:o.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:o.restored_ids.length,failed_count:o.failed_count,rows:o.rows,ids:o.restored_ids}},Bm=async e=>{let t={schema_version:Sc,id:e.checkpointId,created_at:e.nowValue,author:O(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Tt(e.pmRoot,No,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},Vm=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(s=>s.trim()).filter(s=>s.length>0))],o=new Set(t.map(s=>s.id));return n.filter(s=>!o.has(s))},Mo=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},Wm=async e=>{let t=x(process.cwd(),e.path);if(!await E(A(t)))throw new p(`Tracker is not initialized at ${t}. Run pm init first.`,u.NOT_FOUND);let n=await R(t);return{pmRoot:t,settings:n,statusRegistry:q(n.schema),runtimeFieldRegistry:mt(n.schema)}},Km=e=>{if(e.options.dryRun===!0)throw new p("--dry-run cannot be combined with --rollback",u.USAGE);if(gt(e.options.list,e.options.status))throw new p("Rollback mode does not accept filter options",u.USAGE);if(Object.keys(e.updateSummary).length>0)throw new p("Rollback mode does not accept update mutation flags",u.USAGE);return Hm({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},Ym=async e=>{Um(e.options.status,e.runtime.statusRegistry);let t=await ye(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(s=>jm(s,e.runtime.runtimeFieldRegistry,e.options.update)),o=e.options.list?.ids==null?[]:(await ye(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(s=>s.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:Vm(e.options.list?.ids,o)}},Jm=e=>({outcome:"effect",exit_code:u.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...Mo(e)}),Xm=e=>({...Oe({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped",...t.warnings?{warnings:t.warnings}:{}})),ids:[],...Mo(e)}),Zm=async e=>{let t=[],n=[],o=e.options.update.message??`update-many apply ${e.checkpointId}`,s=new Map(e.plans.map(i=>[i.id,i])),r=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!r.has(i.id)){let a=s.get(i.id)?.warnings;t.push({id:i.id,status:"skipped",...a?{warnings:a}:{}});continue}try{let a=await be(i.id,{...e.options.update,message:o,runtimeFieldCommands:["update_many"]},e.global);t.push({id:i.id,status:"updated",changed_fields:a.changed_fields,warnings:a.warnings}),n.push(i.id)}catch(a){t.push({id:i.id,status:"failed",error:ge(a)})}}return{rows:t,updatedIds:n}},Qm=async e=>{if(e.plan.actionable.length===0)return Xm(e.plan);let t=S(),n=Ct(No,t),o=new Set(e.plan.actionable.map(m=>m.id)),s=e.plan.listed.items.filter(m=>o.has(m.id)).map(m=>({id:m.id,target_updated_at:m.updated_at})),r=e.options.checkpoint===!1?void 0:await Bm({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:s}),i=await Zm({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=m=>i.rows.filter(f=>f.status===m).length,c=a("updated"),d=a("skipped"),l=a("failed");return{...Oe({applied:c,skipped:d,failed:l,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...r?{checkpoint:r}:{},updated_count:c,skipped_count:d,failed_count:l,rows:i.rows,ids:i.updatedIds,...Mo(e.plan)}},xc=async(e,t)=>{let n=await Wm(t),o=typeof e.rollback=="string"?e.rollback:void 0,s=Ic(e.update);if(Gm(e.list),o!==void 0)return Km({runtime:n,rollbackId:o,options:e,global:t,updateSummary:s});if(!km(e.update))throw new p(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${ym}).`,u.USAGE);zm(e.update,n.settings,n.statusRegistry,n.pmRoot);let r=await Ym({options:e,global:t,runtime:n,updateSummary:s});return e.dryRun===!0?Jm(r):Qm({runtime:n,options:e,global:t,plan: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]="dc87393e-61e3-5d43-a756-d5f156faf29e")}catch{}})();var Ry=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Rc=["brief","standard","deep"],Tc="plan-step-",zo="draft",qo=["bug-investigation","feature-implementation","refactoring-sprint"],Ac={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function ep(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(Ac,t)?Ac[t]:void 0;if(!n)throw new p(`Unknown plan template "${e}". Allowed: ${qo.join(", ")}`,u.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${qo[0]}`]});return n.map(o=>({...o}))}function tp(e,t){return t>0?Math.round(e/t*100):0}function Oc(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function ne(e){return Array.isArray(e)?e.flatMap(t=>eo(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?eo(e,{unique:!1}):[]}function K(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function $c(e,t=zo){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Pn.find(s=>s===n);if(!o)throw new p(`Invalid plan mode "${e}". Allowed: ${Pn.join(", ")}`,u.USAGE);return o}function Ho(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Fn.find(s=>s===n);if(!o)throw new p(`Invalid step status "${e}". Allowed: ${Fn.join(", ")}`,u.USAGE);return o}function Pc(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Nn.find(s=>s===n);if(!o)throw new p(`Invalid step link kind "${e}". Allowed: ${Nn.join(", ")}`,u.USAGE);return o}function np(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Ln.find(o=>o===t);if(!n)throw new p(`Invalid plan harness "${e}". Allowed: ${Ln.join(", ")}`,u.USAGE);return n}function op(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Rc.find(o=>o===t);if(!n)throw new p(`Invalid --depth "${e}". Allowed: ${Rc.join(", ")}`,u.USAGE);return n}function sp(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new p("Plan --fields requires a comma-separated list of plan field names",u.USAGE);return t}var Do=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function rp(e,t){let n=e,o={},s=[];for(let r of t){let i=r.startsWith("plan.")?r.slice(5):r;if(i.length!==0){if(!Do.has(i)){s.push(r);continue}Object.prototype.hasOwnProperty.call(n,i)&&(o[i]=n[i])}}if(s.length>0)throw new p(`Unknown Plan --fields value(s): ${s.join(", ")}`,u.USAGE,{nextSteps:[`Use --fields ${[...Do].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...Do].join(",")}`}});return o}function Bo(e,t){let n={};for(let o of e.split(",")){let s=o.trim();if(s.length===0)continue;let r=s.indexOf("=");if(r<=0)throw new p(`Invalid ${t} entry "${s}"; expected key=value`,u.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[s.slice(0,r).trim().toLowerCase()]=s.slice(r+1).trim()}return n}function Vo(e){let t=Bo(e,"--file");if(!t.path)throw new p("--file requires path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Wo(e){let t=Bo(e,"--test");if(!t.command&&!t.path)throw new p("--test requires at least command=<value> or path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function Ko(e){let t=Bo(e,"--doc");if(!t.path)throw new p("--doc requires path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function ip(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=tp(t.completed,t.total),t}function ap(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let o=`${Tc}${String(n).padStart(3,"0")}`;if(!t.has(o))return o}throw new p("Could not allocate step id (limit reached)",u.GENERIC_FAILURE)}function Qe(e,t){let n=t.trim();if(n.length===0)throw new p("Step reference cannot be empty",u.USAGE);let o=e.find(s=>s.id===n);if(o)return o;if(/^\d+$/.test(n)){let s=Number.parseInt(n,10),r=e.find(i=>i.order===s);if(r)return r}throw new p(`Step "${t}" not found in plan`,u.NOT_FOUND)}function Cc(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function cp(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),o=[],s=[];if(n.length>0){if(t.length>n.length)throw new p("pm plan materialize --steps all cannot be combined with other step refs",u.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=Cc(i);if(a){s.push({from_step:i.id,...a});continue}o.push(i)}return{targets:o,skipped:s}}let r=new Set;for(let i of t){let a=Qe(e,i);if(r.has(a.id))continue;r.add(a.id);let c=Cc(a);if(c){s.push({from_step:a.id,...c});continue}o.push(a)}return{targets:o,skipped:s}}function dp(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,o=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||o?.trim()||void 0}function lp(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function mp(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function J(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),o=ip(n),s=lp(n),r={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??zo,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:o,current_step:s?{id:s.id,order:s.order,title:s.title,status:s.status}:void 0,blocked_steps:mp(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(r.steps=n),t==="deep"&&(r.decisions=e.plan_decisions??[],r.discoveries=e.plan_discoveries??[],r.validation=e.plan_validation??[]),r}function X(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!to(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function Fc(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new p(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,u.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function pp(e){let t=x(process.cwd(),e.path);if(!await E(A(t)))throw new p(`Tracker is not initialized at ${t}. Run pm init first.`,u.NOT_FOUND);let n=await R(t);return{pmRoot:t,settings:n}}async function Lc(e,t){let n=F(e.settings,T()),o=await te(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!o)throw new p(`Plan ${t} not found`,u.NOT_FOUND);let s=await H(o,{schema:e.settings.schema});return Fc(s.document.metadata),{document:s.document,itemId:o.id}}function up(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of ne(e.related))t.push(`id=${n},kind=related`);for(let n of ne(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of ne(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function fp(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),o=e.validationExpected?.trim();if(!(!t&&!n&&!o))return{text:t||n||"Validation check",command:n||void 0,expected:o||void 0}}function _p(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||ne(e.dependsOn).length>0||ne(e.link).length>0}function hp(e){let t=e.stepTitle?.trim()||void 0,n=Oc(e.step),o=e.template?.trim()?ep(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...o.map(s=>s.title)],templateSteps:o}}function gp(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new p("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",u.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${qo[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new p("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",u.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function yp(e,t){let n=Ho(e.stepStatus,"pending"),o=Yo(e,"depends_on"),s=K(e.file).map(Vo),r=K(e.test).map(Wo),i=K(e.doc).map(Ko),a=S();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:o.length>0?o:void 0,files:s.length>0?s:void 0,tests:r.length>0?r:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function bp(e){let t=hp(e),n=_p(e);if(gp(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[yp(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let o=S();return{steps:t.stepTitles.map((s,r)=>({id:`${Tc}${String(r+1).padStart(3,"0")}`,order:r+1,title:s,body:t.templateSteps[r]?.body,status:"pending",created_at:o,updated_at:o})),hasPerStepDetailOptions:n}}async function wp(e,t,n){let o=e.title?.trim();if(!o)throw new p("pm plan create requires --title",u.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let s=$c(e.mode,zo),r=np(e.harness),i=e.fromSearch?.trim(),a=fp(e),{steps:c,hasPerStepDetailOptions:d}=bp(e);if(c.length===0&&d)throw new p("pm plan create step options require --step-title (or a single --step)",u.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let l=e.description?.trim()??e.scope?.trim()??o,m=e.claim?O(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:o,description:l,type:"Plan",template:void 0,file:K(e.file),test:K(e.test),doc:K(e.doc),field:K(e.field),assignee:O(e.author,n.settings.author_default),blockedBy:void 0,dep:up(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await yt(f,t),y=await _t({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:O(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let h=["plan_mode"];g.metadata.plan_mode=s,r&&(g.metadata.plan_harness=r,h.push("plan_harness"));let k=e.scope?.trim();k&&(g.metadata.plan_scope=k,h.push("plan_scope"));let I=e.resumeContext?.trim();return I&&(g.metadata.plan_resume_context=I,h.push("plan_resume_context")),g.metadata.plan_steps=c,h.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],h.push("plan_validation")),m&&(g.metadata.assignee=m,h.push("assignee")),{changedFields:h}}}),w=J(y.item,"brief");return{action:"create",plan:w,step:c[0],next_actions:X(_.item.id,w),warnings:[..._.warnings],generated_at:S()}}async function vp(e,t,n){let o=op(t.depth),s=sp(t.fields),{document:r,itemId:i}=await Lc(n,e),a=J(r.metadata,s===null?o:"deep");return{action:"show",plan:s===null?a:rp(a,s),next_actions:X(i,a),warnings:[],generated_at:S()}}function kp(e,t){let n=new Map(Object.entries(t).filter(([o])=>o.startsWith("plan_")).map(([o,s])=>[o,JSON.stringify(s)]));return[...new Set([...e.keys(),...n.keys()])].filter(o=>e.get(o)!==n.get(o))}async function ae(e){let t=O(e.options.author,e.ctx.settings.author_default),n,o=await _t({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(s){Fc(s.metadata);let r=q(e.ctx.settings.schema);if(qe(s.metadata.status,r)||to(s.metadata.plan_mode))throw new p(`Plan ${s.metadata.id} is terminal (status=${s.metadata.status}, plan_mode=${s.metadata.plan_mode??"unset"}) and cannot be mutated.`,u.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let i=(s.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(s.metadata).filter(([m])=>m.startsWith("plan_")).map(([m,f])=>[m,JSON.stringify(f)])),c=e.mutator(i,s);n=c.resultStep;let d=i.slice().sort((m,f)=>m.order-f.order).map((m,f)=>({...m,order:f+1}));s.metadata.plan_steps=d;let l=kp(a,s.metadata);return l.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:l.length>0?l:["plan_steps"]}}});return{document:{metadata:o.item,body:o.body},resultStep:n,itemId:o.item.id}}async function Sp(e,t,n){let o=t.stepTitle?.trim();if(!o)throw new p("pm plan add-step requires --step-title",u.USAGE);let s=Ho(t.stepStatus,"pending"),r=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await ae({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${o}"`,mutator(l){let m=l.length+1;Nc(l,void 0,s,r);let f=Ip(l,t,{order:m,title:o,status:s});return l.push(f),{changedSteps:[f.id],resultStep:f}}}),d=J(i.metadata,"standard");return{action:"add-step",plan:d,step:a,next_actions:X(c,d),warnings:[],generated_at:S()}}function Nc(e,t,n,o){if(n!=="in_progress"||o)return;let s=e.find(r=>r.id!==t&&r.status==="in_progress");if(s)throw new p(`Plan already has step ${s.id} in_progress. Pass --allow-multiple-active or update that step first.`,u.CONFLICT)}function Ip(e,t,n){let o=Yo(t,"depends_on"),s=K(t.file).map(Vo),r=K(t.test).map(Wo),i=K(t.doc).map(Ko),a=S();return{id:ap(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:o.length>0?o:void 0,files:s.length>0?s:void 0,tests:r.length>0?r:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function Yo(e,t){let n=ne(e.dependsOn).map(l=>({id:l,kind:t})),o=ne(e.related).map(l=>({id:l,kind:"related"})),s=ne(e.blocks).map(l=>({id:l,kind:"blocks"})),r=ne(e.blockedBy).map(l=>({id:l,kind:"blocked_by"})),i=ne(e.link),a=Pc(e.linkKind,t),c=e.linkNote?.trim(),d=i.map(l=>{let m={id:l,kind:a};return c&&(m.note=c),m});return[...n,...o,...s,...r,...d]}async function jo(e,t,n,o){let{document:s,resultStep:r,itemId:i}=await ae({id:e,options:t,ctx:n,op:o.op,message:t.message??`${o.op} ${o.stepRef}`,mutator(c,d){let l=Qe(c,o.stepRef),m=S(),f=o.finalStatus??Ho(t.stepStatus,l.status),_=t.allowMultipleActive===!0||o.allowMultipleActive===!0;return Nc(c,l.status==="in_progress"?l.id:void 0,f,_),Ep(l,t,f,m),d.metadata.updated_at=m,{changedSteps:[l.id],resultStep:l}}}),a=J(s.metadata,"standard");return{action:o.op==="plan_complete_step"?"complete-step":o.op==="plan_block_step"?"block-step":"update-step",plan:a,step:r,next_actions:X(i,a),warnings:[],generated_at:S()}}function Ep(e,t,n,o){xp(e,t,n),Rp(e,t),e.status=n,e.updated_at=o,Ap(e,n,o)}function xp(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new p("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",u.USAGE)}function Rp(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=t.stepOwner.trim()||void 0),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let o=K(t.file).map(Vo),s=K(t.test).map(Wo),r=K(t.doc).map(Ko);o.length>0&&(e.files=Uo(e.files,o)),s.length>0&&(e.tests=Uo(e.tests,s)),r.length>0&&(e.docs=Uo(e.docs,r))}function Uo(e,t){let n=[...e??[]],o=new Set(n.map(s=>JSON.stringify(s)));for(let s of t){let r=JSON.stringify(s);o.has(r)||(o.add(r),n.push(s))}return n}function Ap(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function Cp(e,t,n,o,s){let{document:r,itemId:i}=await ae({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${o} -> ${s}`,mutator(c){let d=Qe(c,o),l=c.filter(f=>f.id!==d.id),m=Math.max(1,Math.min(s,l.length+1));return l.splice(m-1,0,d),l.forEach((f,_)=>{f.order=_+1,f.updated_at=S()}),c.length=0,c.push(...l),{changedSteps:[d.id],resultStep:d}}}),a=J(r.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:X(i,a),warnings:[],generated_at:S()}}async function Tp(e,t,n,o){let{document:s,itemId:r}=await ae({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${o}`,mutator(a){let c=Qe(a,o),d=a.filter(l=>l.id!==c.id);return d.forEach((l,m)=>{l.order=m+1}),a.length=0,a.push(...d),{changedSteps:[c.id]}}}),i=J(s.metadata,"standard");return{action:"remove-step",plan:i,next_actions:X(r,i),warnings:[],generated_at:S()}}async function Op(e,t,n,o){let s=Yo(t,Pc(t.linkKind,"related"));if(s.length===0)throw new p("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",u.USAGE);let r=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await ae({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${o}`,mutator(l,m){let f=Qe(l,o),_=f.linked_items??[],y=g=>`${g.kind}:${g.id}`,w=new Set(_.map(y));for(let g of s){let h=y(g);w.has(h)||(_.push(g),w.add(h))}if(f.linked_items=_,f.updated_at=S(),r){let g=m.metadata.dependencies??[],h=I=>`${I.kind}:${I.id}`,k=new Set(g.map(h));for(let I of s){let P=I.kind==="depends_on"?"blocked_by":I.kind,C={id:I.id,kind:P,created_at:S(),author:O(t.author,n.settings.author_default)};k.has(h(C))||(g.push(C),k.add(h(C)))}m.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),d=J(i.metadata,"standard");return{action:"link",plan:d,step:c,next_actions:X(a,d),warnings:[],generated_at:S()}}async function $p(e,t,n,o){let s=ne(t.link);if(s.length===0)throw new p("pm plan unlink requires --link <id> to remove",u.USAGE);let{document:r,itemId:i,resultStep:a}=await ae({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${o}`,mutator(d){let l=Qe(d,o),m=(l.linked_items??[]).filter(f=>!s.includes(f.id));return l.linked_items=m.length>0?m:void 0,l.updated_at=S(),{changedSteps:[l.id],resultStep:l}}}),c=J(r.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:X(i,c),warnings:[],generated_at:S()}}async function Go(e,t,n,o){let s=dp(o,t);if(!s){let d=`--${o}-text`,l=`--${o}`;throw new p(`pm plan ${o} requires ${d}`,u.USAGE,{code:"missing_required_option",examples:[`pm plan ${o} <plan-id> ${d} "..."`,`pm plan ${o} <plan-id> ${l} "..."`],recovery:{suggested_retry:`pm plan ${o} <plan-id> ${d} <value>`}})}let r=O(t.author,n.settings.author_default),{document:i,itemId:a}=await ae({id:e,options:t,ctx:n,op:`plan_append_${o}`,message:t.message??`plan ${o} append`,mutator(d,l){let m=S();if(o==="decision"){let _=l.metadata.plan_decisions??[];return _.push({ts:m,author:r,decision:s,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),l.metadata.plan_decisions=_,{changedSteps:[]}}if(o==="discovery"){let _=l.metadata.plan_discoveries??[];return _.push({ts:m,author:r,text:s}),l.metadata.plan_discoveries=_,{changedSteps:[]}}let f=l.metadata.plan_validation??[];return f.push({text:s,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),l.metadata.plan_validation=f,{changedSteps:[]}}}),c=J(i.metadata,"deep");return{action:o,plan:c,next_actions:X(a,c),warnings:[],generated_at:S()}}async function Pp(e,t,n){let o=t.resumeContext?.trim();if(!o)throw new p("pm plan resume requires --resume-context <text>",u.USAGE);let{document:s,itemId:r}=await ae({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=o;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),i=J(s.metadata,"brief");return{action:"resume",plan:i,next_actions:X(r,i),warnings:[],generated_at:S()}}async function Fp(e,t,n){let o=$c(t.mode??"approved","approved"),{document:s,itemId:r}=await ae({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${o}`,mutator(a,c){c.metadata.plan_mode=o;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),i=J(s.metadata,"brief");return{action:"approve",plan:i,next_actions:X(r,i),warnings:[],generated_at:S()}}function Mc(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function Lp(e,t){let n=J(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:X(e.itemId,n),warnings:Mc(t),generated_at:S()}}function Np(e,t,n){let o=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let s of n.linked_items??[]){let r=s.kind==="blocked_by"||s.kind==="blocks"||s.kind==="related"||s.kind==="discovered_from"?s.kind:"related";o.push(`id=${s.id},kind=${r}`)}return o}async function Mp(e){let t=[],n={},o=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let s of K(e.options.field)){let r=s.indexOf("=");if(r<=0)throw new p(`Invalid --field entry "${s}"; expected name=value`,u.USAGE);let i=s.slice(0,r).trim(),a=s.slice(r+1).trim();if(i.length===0)throw new p(`Invalid --field entry "${s}"; expected name=value`,u.USAGE);let c=i.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new p(`Invalid --field entry "${s}"; expected name=value`,u.USAGE);let[d,...l]=c,m=`${d}${l.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(o.has(m))throw new p(`Invalid --field entry "${s}"; "${m}" is reserved by materialize and cannot be overridden`,u.USAGE);n[m]=a}for(let s of e.targets){let r=await yt({...n,title:s.title,description:s.body?.trim()||s.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${s.id}`,dep:Np(e.parent,e.planItemId,s)},{path:e.pmRoot});t.push({id:r.item.id,title:r.item.title,type:e.resolvedTypeName,parent:r.item.parent,tags:r.item.tags??[],from_step:s.id})}return t}function Dp(e,t,n){for(let o of t){let s=n.find(a=>a.from_step===o.id);if(!s)continue;let r=e.find(a=>a.id===o.id);if(!r)continue;let i=r.linked_items??[];i.push({id:s.id,kind:"implements",note:`materialized as ${s.type}`}),r.linked_items=i,r.updated_at=S()}}async function jp(e,t,n){let o=ne(t.steps);if(o.length===0)throw new p("pm plan materialize requires --steps <ids|orders|all>",u.USAGE);let s=t.materializeType?.trim()||"Task",r=F(n.settings,T()),i=Pt(s,r);if(!i)throw new p(`Invalid --materialize-type "${s}"`,u.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,d=await Lc(n,e),l=(d.document.metadata.plan_steps??[]).slice(),{targets:m,skipped:f}=cp(l,o);if(m.length===0){if(f.length>0)return Lp(d,f);throw new p("No matching plan steps found for --steps",u.NOT_FOUND)}let _=await Mp({targets:m,parent:a,planItemId:d.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:y,itemId:w}=await ae({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${o.join(",")}`,mutator(h){return Dp(h,m,_),{changedSteps:m.map(k=>k.id)}}}),g=J(y.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:X(w,g),warnings:Mc(f),generated_at:S()}}function Up(e){if(e.subcommand==="create")return e;let t=Oc(e.options.step);if(t.length>1)throw new p(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,u.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:{...e.options,stepTitle:t[0]}}:e}function _e(e,t){if(!e.id)throw new p(`pm plan ${t} requires a plan id`,u.USAGE);return e.id}function Ne(e,t){let n=_e(e,t);if(!e.stepRef)throw new p(`pm plan ${t} requires <plan-id> <step>`,u.USAGE);return{id:n,stepRef:e.stepRef}}function Gp(e){let t=Ne(e,"reorder-step");if(e.reorderTo===void 0)throw new p("pm plan reorder-step requires <plan-id> <step> <new-order>",u.USAGE);return{...t,reorderTo:e.reorderTo}}var qp={create:(e,t)=>wp(e.options,e.global,t),show:(e,t)=>vp(_e(e,"show"),e.options,t),"add-step":(e,t)=>Sp(_e(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=Ne(e,"update-step");return jo(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=Ne(e,"complete-step");return jo(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=Ne(e,"block-step");return jo(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=Gp(e);return Cp(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=Ne(e,"remove-step");return Tp(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=Ne(e,"link");return Op(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=Ne(e,"unlink");return $p(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Go(_e(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Go(_e(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Go(_e(e,"validation"),e.options,t,"validation"),resume:(e,t)=>Pp(_e(e,"resume"),e.options,t),approve:(e,t)=>Fp(_e(e,"approve"),e.options,t),materialize:(e,t)=>jp(_e(e,"materialize"),e.options,t)};function zp(e){let t=qp[e];if(!t)throw new p(`Unknown pm plan subcommand "${e}"`,u.USAGE);return t}async function Dc(e){let t=await pp(e.global),n=Up(e);return zp(n.subcommand)(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4eb2056a-4444-514a-a0db-79b8875c3d65")}catch{}})();function Hp(e,t){return[...new Set([...js.filter(o=>e[o]!==void 0),...Object.keys(e).filter(o=>e[o]!==void 0),...t.length>0?["body"]:[]])].sort((o,s)=>o.localeCompare(s))}function Bp(e,t){let n=`copied_from=${e}`;if(!t)return n;let o=t.trim();return o.length>0?`${o} | ${n}`:n}async function Jo(e,t,n){let o=x(process.cwd(),n.path);if(!await E(A(o)))throw new p(`Tracker is not initialized at ${o}. Run pm init first.`,u.NOT_FOUND);let s=await R(o),r=F(s,T()),i=await te(o,e,s.id_prefix,s.item_format,r.type_to_folder);if(!i)throw await Vt(o,e,s.id_prefix,r.type_to_folder);let a=await H(i,{schema:s.schema}),c=a.document.metadata,d=S(),l=O(t.author,s.author_default),m=await Yn(o,s.id_prefix,{tokenLength:s.ids.token_length,typeToFolder:r.type_to_folder,probeExisting:!1}),f=q(s.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new p("Copy --title must not be empty",u.USAGE);let y={...c,id:m,title:_??c.title,status:f.open_status,created_at:d,updated_at:d};delete y.closed_at,delete y.completed_at,delete y.close_reason,delete y.test_runs;let w=Ge(T()),g=Re({metadata:y,body:a.document.body},{schema:s.schema,extensionFieldNames:w}),h=await ao({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:o,mode:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),k=Hp(g.metadata,g.body),I=dt(o,g.metadata.type,m,s.item_format,r.type_to_folder),P=se(o,m),C=await Y(o,m,s.locks.ttl_seconds,l,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),j={metadata:{},body:""},U,Q;try{let de=await zt(o,l,{required:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await ao({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:o,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1});let Ie=await te(o,m,s.id_prefix,s.item_format,r.type_to_folder);if(Ie)throw new p(`Cannot copy to ${m}: an item with that id already exists at ${Ie.itemPath}. Retry the copy to allocate a new id.`,u.CONFLICT,{code:"item_id_collision",why:`Allocated id ${m} already exists at ${Ie.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await V(I,le(g,{format:s.item_format,schema:s.schema,extensionFieldNames:w}));try{let oe=re({nowIso:d,author:l,op:"create",before:j,after:g,message:Bp(i.id,t.message)});await Ae(P,oe)}catch(oe){throw await at(I),oe}Q=await Ht({pmRoot:o,preferredFormat:s.item_format,typeToFolder:r.type_to_folder,schema:s.schema,itemPath:I,document:g})}finally{await de()}U=[...await N({path:I,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:k}),...await N({path:P,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:k})],Lt({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:lt(g.metadata,k),changed_fields:k})}finally{await C()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:k,warnings:[...Vi(h),...Q,...U],...h===void 0?{}:{similarity_advisory:h}}}import hn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="14aa55e1-cb5f-55ea-bf4c-412217d87449")}catch{}})();async function Xo(e,t,n){let o=x(process.cwd(),n.path);if(!await E(A(o)))throw new p(`Tracker is not initialized at ${o}. Run pm init first.`,u.NOT_FOUND);let s=await R(o),r=O(t.author,s.author_default),i=await jr({pmRoot:o,settings:s,id:e,author:r,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?hn.relative(o,i.targetPath).split(hn.sep).join("/"):void 0;return{item:i.item,changed_fields:i.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:i.item.status,...a?{target_path:a}:{},history_retained:hn.relative(o,se(o,i.item.id)).split(hn.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d51ebf7a-d759-5a6b-9a4f-810139a1688c")}catch{}})();async function Vp(e){if(!await E(A(e)))throw new p(`Tracker is not initialized at ${e}. Run pm init first.`,u.NOT_FOUND)}async function Zo(e,t,n){let o=x(process.cwd(),n.path);if(await Vp(o),t.clear===!0){if(e!==void 0)throw new p("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",u.USAGE);return await Qr(o),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let m=await Xr(o);if(m===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await Wp(o,m);return{action:"show",focused_item:m,title:f,message:`Focused on ${m}${f?` (${f})`:""}. New items default --parent to it.`}}let r=await R(o),i=F(r,T()),a=await te(o,e,r.id_prefix,r.item_format,i.type_to_folder);if(!a)throw await Vt(o,e,r.id_prefix,i.type_to_folder);let c=ut(a.id,r.id_prefix),d=await H(a,{schema:r.schema}),l=jc(d.document.metadata.title);return await Zr(o,c),{action:"set",focused_item:c,title:l,message:`Focused on ${c}${l?` (${l})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function Wp(e,t){let n=await R(e),o=F(n,T()),s=await te(e,t,n.id_prefix,n.item_format,o.type_to_folder);if(!s)return null;let r=await H(s,{schema:n.schema});return jc(r.document.metadata.title)}function jc(e){return e.trim().length>0?e:null}import{readFile as su,writeFile as ru}from"node:fs/promises";import iu 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]="f6f04eec-0698-5e5b-a40e-de3a4be89f95")}catch{}})();function Qo(e,t){let n=Nt(e);if(n)throw new p(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,u.GENERIC_FAILURE);let o=[];for(let[s,r]of e.split(/\r?\n/).entries()){let i=r.trim();if(i)try{let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");o.push(a)}catch{throw new p(`History merge input (${t}) contains invalid JSON at line ${s+1}.`,u.GENERIC_FAILURE)}}return o}function ke(e){return D({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Kp(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&ke(e[o])===ke(t[o]);)o+=1;return o}function Uc(e,t,n){Qo(e,"base");let o=Qo(t,"ours"),s=Qo(n,"theirs"),r=Kp(o,s);if(r===o.length&&r===s.length)return{merged:pe(o),strategy:"identical",common_entries:r,entries_from_ours:0,entries_from_theirs:0,entries_total:o.length,reanchored:!1};if(r===s.length)return{merged:pe(o),strategy:"fast_forward_ours",common_entries:r,entries_from_ours:o.length-r,entries_from_theirs:0,entries_total:o.length,reanchored:!1};if(r===o.length)return{merged:pe(s),strategy:"fast_forward_theirs",common_entries:r,entries_from_ours:0,entries_from_theirs:s.length-r,entries_total:s.length,reanchored:!1};let i=o.slice(r),a=new Set(i.map(ke)),c=s.slice(r).filter(m=>!a.has(ke(m))),d=[...i,...c].sort((m,f)=>{let _=At(m.ts,f.ts);if(_!==0)return _;let y=a.has(ke(m)),w=a.has(ke(f));return y!==w?Number(w)-Number(y):ke(m).localeCompare(ke(f))}),l=jt([...o.slice(0,r),...d]);return{merged:pe(l.entries),strategy:"union_reanchor",common_entries:r,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:l.entries.length,reanchored:!0}}function es(e,t){let n=Nt(e);if(n)throw new p(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,u.GENERIC_FAILURE);let o=[];for(let[s,r]of e.split(/\r?\n/).entries()){let i=r.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new p(`Relationship merge input (${t}) contains invalid JSON at line ${s+1}.`,u.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new p(`Relationship merge input (${t}) line ${s+1} is not a relationship event (eventId + sequence required).`,u.GENERIC_FAILURE);o.push(a)}return o}function gn(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
10
+ `,{changedFields:["body"]}}});return{item:d.item,appended:c,changed_fields:d.changedFields}}import Xl from"fast-json-patch";import Lo from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="353be665-9f67-5d0e-99c9-6bbb7e927e0b")}catch{}})();function Zl(e,t){return Di(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Ql(e){let t=so(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Ae(Te(t))}async function em(e,t,n,o){let s=await ee(e,t,n.id_prefix,n.item_format,o);if(s){let c=se(e,s.id),d=await Rr({pmRoot:e,settings:n,itemId:s.id,commandLabel:"restore"});return{id:s.id,historyPath:c,located:s,historyPolicyWarnings:d.warnings}}let r=_t(t,n.id_prefix),i=Jn(t),a=r===i?[r]:[r,i];for(let c of a){let d=se(e,c);if(await x(d))return{id:c,historyPath:d,located:null,historyPolicyWarnings:[]}}throw new p(`Item ${t} not found`,u.NOT_FOUND)}function tm(e,t){let n=Oe(e),o=Oe(t),s=Xl.compare(n,o),r=new Set;for(let i of s){if(i.path==="/body"||i.path.startsWith("/body/")){r.add("body");continue}let a=i.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];r.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(r).sort((i,a)=>i.localeCompare(a))}async function nm(e){if(await G(e.subject.historyPath)!==e.historyRawBeforeLock)throw new p(`History for ${e.resolvedId} changed while waiting for lock; retry restore.`,u.CONFLICT);let n=await ee(e.pmRoot,e.resolvedId,e.settings.id_prefix,e.settings.item_format,e.typeToFolder),o=n?await H(n,{schema:e.settings.schema}):null;if((o?.raw??null)!==e.currentItemRawBeforeLock)throw new p(`Item ${e.resolvedId} changed while waiting for lock; retry restore.`,u.CONFLICT);return{loadedItemUnderLock:o,existingItemPath:n?.itemPath??null}}function om(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Ql(t),originalRaw:null}}function sm(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new p(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,u.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function rm(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await B(e.existingItemPath,e.resolvedOriginalRaw),await Lo.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await B(e.existingItemPath,e.resolvedOriginalRaw);return}await Lo.rm(e.restoredItemPath,{force:!0})}async function im(e){return[...await N({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await N({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Me(e,t,n,o){let s=I(process.cwd(),o.path);if(!await x(A(s)))throw new p(`Tracker is not initialized at ${s}. Run pm init first.`,u.NOT_FOUND);let r=await R(s),i=P(r,O()),a=await em(s,e,r,i.type_to_folder),c=a.id,d=await G(a.historyPath),l=await Ve(a.historyPath,c);if(l.length===0)throw new p(`No history exists for ${c}; restore is unavailable.`,u.NOT_FOUND);let m=Zl(t,l),f=ji(so(l,m.historyIndex),m),_=Er(f,{schema:r.schema});if(_.metadata.id!==c)throw new p(`Restore target resolved to item ${_.metadata.id}, expected ${c}.`,u.GENERIC_FAILURE);let w=(a.located?await H(a.located,{schema:r.schema}):null)?.raw??null,g=C(n.author,r.author_default),h=await K(s,c,r.locks.ttl_seconds,g,!!n.force,r.governance.force_required_for_stale_lock,r.locks.wait_ms);try{let{loadedItemUnderLock:S,existingItemPath:E}=await nm({pmRoot:s,resolvedId:c,subject:a,settings:r,typeToFolder:i.type_to_folder,historyRawBeforeLock:d,currentItemRawBeforeLock:w}),F="toon",T=om(S,l),j=sm({document:T.document,author:g,force:n.force,enforcement:r.governance.ownership_enforcement,resolvedId:c}),U=tm(T.document,_);await or({pm_root:s,operation:"restore",before:T.document,after:_,changed_fields:U,sdk:Br({pmRoot:s,settings:r,typeToFolder:i.type_to_folder})});let Z=me(_,{format:F,schema:r.schema}),de=mt(s,_.metadata.type,c,F,i.type_to_folder),Ee=await Ht(s,g),oe=[];try{await B(de,Z),E&&de!==E&&await Lo.rm(E);let Cl=re({nowIso:k(),author:g,op:"restore",before:T.document,after:_,message:n.message});try{await Ce(a.historyPath,Cl)}catch(Tl){throw await rm({existingItemPath:E,resolvedOriginalRaw:T.originalRaw,restoredItemPath:de}),Tl}oe=await Bt({pmRoot:s,preferredFormat:r.item_format,typeToFolder:i.type_to_folder,schema:r.schema,itemPath:de,previousItemPath:E??void 0,document:_})}finally{await Ee()}let Al=await im({restoredItemPath:de,historyPath:a.historyPath,before:T.document,after:_});Nt({id:_.metadata.id,op:"restore",item_type:_.metadata.type,previous_status:T.document.metadata.status,status:_.metadata.status,previous:pt(T.document.metadata,U),current:pt(_.metadata,U),changed_fields:U});let Ns=l[m.historyIndex];return{item:_.metadata,restored_from:{kind:m.kind,target:m.raw,history_index:m.historyIndex+1,entry_ts:Ns.ts,entry_op:Ns.op},changed_fields:U,warnings:[...a.historyPolicyWarnings,...j,...oe,...Al]}}finally{await h()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4da07a98-855e-59cf-a6a4-2f59a8b3c0bd")}catch{}})();var Rc=1,No="close-many",am=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function cm(e,t){return vt(e,t,{includePagination:!1})}function dm(e,t){return vt(e,t)}function lm(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new p("--ids requires at least one non-empty item ID",u.USAGE)}function mm(e){let t={};if(!e)return t;for(let[n,o]of Object.entries(e))o==null||typeof o=="string"&&!o.split(",").some(s=>s.trim().length>0)||(t[n]=o);return t}function pm(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new p("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",u.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function um(e,t){let n=q(t.schema),o=P(t,O()),s=await $e(e,t.item_format,o.type_to_folder,void 0,t.schema),r=new Map,i=new Map;for(let a of s){if(typeof a.parent!="string"||a.parent.length===0||(i.set(a.id,a.parent),Be(a.status,n)))continue;let c=r.get(a.parent);c?c.push(a.id):r.set(a.parent,[a.id])}for(let a of r.values())a.sort((c,d)=>c.localeCompare(d));return{childrenByParent:r,parentByChild:i}}function xc(e,t,n){let o=n?.get(e);if(o!==void 0)return o;let s=0,r=t.get(e),i=[],a=new Set,c=!1;for(;r!==void 0&&!a.has(r);){let d=n?.get(r);if(d!==void 0){s+=d+1;break}a.add(r),i.push(r),s+=1,r=t.get(r)}if(r!==void 0&&a.has(r)&&(c=!0),!c){n?.set(e,s);for(let[d,l]of i.entries())n?.set(l,s-d-1)}return s}async function fm(e){let t=await $t(e.pmRoot,No,e.rollbackId,Rc),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,o=await Pt(t.items,(s,r)=>Me(s,r,{author:e.options.author,message:n,force:!0},e.global));return{...Le({applied:o.restored_ids.length,skipped:0,failed:o.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:o.restored_ids.length,failed_count:o.failed_count,rows:o.rows,ids:o.restored_ids}}function _m(e,t,n,o,s){return e.map(r=>{let i=(t.get(r.id)??[]).filter(c=>!n.has(c)),a=!Ac(r,o,s);return{id:r.id,title:typeof r.title=="string"?r.title:"",status:r.status,action:a?"skip":"close",...a?{skip_reason:"already_terminal"}:{},...i.length>0?{active_child_ids:i}:{}}})}async function hm(e){let t=await Ot(e.pmRoot,No,e.checkpointId,{schema_version:Rc,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function gm(e){let t=[],n=[];for(let o of e.matched){if(!e.closableIds.has(o.id)){t.push({id:o.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let s=await Ze(o.id,e.reason,e.closeOptions,e.global);t.push({id:o.id,status:"closed",changed_fields:s.changed_fields,...s.warnings&&s.warnings.length>0?{warnings:s.warnings}:{}}),n.push(o.id)}catch(s){t.push({id:o.id,status:"failed",error:ye(s)})}}return{rows:t,closedIds:n}}function ym(e){return typeof e.rollback=="string"?e.rollback:void 0}function bm(e,t){if(t.trim().length===0)throw new p("--rollback requires a checkpoint id",u.USAGE);if(e.dryRun===!0)throw new p("--dry-run cannot be combined with --rollback",u.USAGE);if(dm(e.list,e.status))throw new p("Rollback mode does not accept filter options",u.USAGE)}function wm(e){if(!cm(e.list,e.status))throw new p(`close-many requires at least one filter to scope the close (for example: ${am}). Refusing to match every item.`,u.USAGE)}function vm(e,t){let n=new Map;return[...e].sort((o,s)=>{let r=xc(s.id,t,n)-xc(o.id,t,n);return r!==0?r:o.id.localeCompare(s.id)})}function Ac(e,t,n){return n||!Be(e.status,t)}function km(e,t,n){return new Set(e.filter(o=>Ac(o,t,n)).map(o=>o.id))}async function Sm(e){wm(e.options);let t=q(e.settings.schema),n=pm(e.options.reason,e.settings.governance.require_close_reason),o=e.options.force===!0,s=await we(e.options.status,mm(e.options.list),e.global),{childrenByParent:r,parentByChild:i}=await um(e.pmRoot,e.settings),a=vm(s.items,i),c=[...new Set(String(e.options.list?.ids??"").split(",").map(m=>m.trim()).filter(m=>m.length>0))],d=new Set(a.map(m=>m.id)),l=km(a,t,o);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:o,listed:s,matched:a,unmatchedIds:c.filter(m=>!d.has(m)),planRows:_m(a,r,l,t,o)}}function Im(e){return{outcome:"effect",exit_code:u.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds.length>0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function Em(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return hm({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function Cc(e,t){let n=I(process.cwd(),t.path);if(!await x(A(n)))throw new p(`Tracker is not initialized at ${n}. Run pm init first.`,u.NOT_FOUND);let o=await R(n),s=e.dryRun===!0,r=ym(e);if(lm(e.list),r!==void 0)return bm(e,r),fm({pmRoot:n,rollbackId:r,options:e,global:t});let i=await Sm({pmRoot:n,settings:o,options:e,global:t});if(s)return Im(i);let a=new Set(i.planRows.filter(h=>h.action==="close").map(h=>h.id)),c=k(),d=Tt(No,c),l=await Em({context:i,options:e,closableIds:a,checkpointId:d,nowValue:c}),m={author:e.author,message:e.message??`close-many apply ${d}`,completedAt:e.completedAt,validateClose:i.validateCloseMode,force:i.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:_}=await gm({matched:i.matched,closableIds:a,reason:i.reason,closeOptions:m,global:t}),y=f.filter(h=>h.status==="closed").length,w=f.filter(h=>h.status==="skipped").length,g=f.filter(h=>h.status==="failed").length;return{...Le({applied:y,skipped:w,failed:g,unmatched:i.unmatchedIds.length}),mode:"apply",matched_count:i.matched.length,dry_run:!1,...i.reason!==void 0?{reason:i.reason}:{},filters:i.listed.filters,...i.validateCloseMode?{validate_close:i.validateCloseMode}:{},...l?{checkpoint:l}:{},closed_count:y,skipped_count:w,failed_count:g,rows:f,ids:_,...i.unmatchedIds.length>0?{unmatched_ids:i.unmatchedIds,unmatched_count:i.unmatchedIds.length}:{}}}import{readFile as xm}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="667218ac-866c-59b1-8309-18ad92434fca")}catch{}})();async function Mo(e,t){let n=e.add!==void 0,o=e.stdin===!0,s=typeof e.file=="string",r=Number(n)+Number(o)+Number(s);if(r===0)return;if(r>1)throw new p("Specify comment text using only one input source: --add, --stdin, or --file",u.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add")??"",emptyFlag:"--add"};if(o)return{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let i=e.file.trim();if(!i)throw new p("--file path cannot be empty",u.USAGE);try{return{value:await xm(i,"utf8"),emptyFlag:"--file"}}catch(a){if(La(a)&&a.code==="ENOENT")throw new p(`--file path not found: ${i}`,u.USAGE);let c=a instanceof Error?a.message:String(a);throw new p(`Failed to read --file path "${i}": ${c}`,u.USAGE)}}async function Rm(e,t){let n=e.edit,o=e.delete,s=n!==void 0,r=o!==void 0;if(s&&r)throw new p("Specify only one of --edit or --delete",u.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new p("--edit must be a positive integer",u.USAGE);if(o!==void 0&&(!Number.isInteger(o)||o<1))throw new p("--delete must be a positive integer",u.USAGE);if(r){if(await Mo(e,t)!==void 0)throw new p("--delete does not take comment text",u.USAGE);return{mode:"delete",index:o}}if(s){let c=await Mo(e,t);if(c===void 0)throw new p("--edit requires replacement text via positional [text], --add, --stdin, or --file",u.USAGE);return{mode:"edit",index:n,value:c.value,emptyFlag:c.emptyFlag}}let i=await Mo(e,t);return i===void 0?{mode:"list"}:{mode:i.emptyFlag==="--add"?"add":i.emptyFlag==="--stdin"?"stdin":"file",value:i.value,emptyFlag:i.emptyFlag}}async function Tc(e,t,n){let o=qt(),s=await Rm(t,o),r=s.mode==="add"||s.mode==="edit",i=s.value??"";return Xe(e,t,n,{input:{...s,rawValue:t.add??i,value:r?Je(i,{stripPlainTextPrefix:!0}):i},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:a=>a,createEntry:a=>a,bypassOwnershipConflict:!!(s.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm comments pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="93184f29-f215-5413-9628-fb5b34523995")}catch{}})();async function Oc(e,t,n){return Xe(e,t,n,{input:await dn(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:o=>Je(o),createEntry:o=>o,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm learnings pm-a1b2 --add "review learning" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ebd9f151-593f-5081-97da-d78f83de4914")}catch{}})();function Am(e){if(e===void 0)return;if(e.trim().length===0)throw new p("--add-json must contain a JSON value",u.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new p("--add-json must be valid JSON",u.USAGE,{code:"structured_event_json_invalid"})}return t}function Cm(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Tm(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new p("--since must be a valid ISO timestamp",u.USAGE,{code:"structured_event_since_invalid"});return t}async function $c(e,t,n){let o=Am(t.addJson),s=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(o!==void 0&&s)throw new p("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",u.USAGE,{code:"structured_event_input_conflict"});let r=o===void 0?void 0:D(o),i=[t.since,t.eventType].some(y=>y!==void 0),a=Tm(t.since),c=Lr(t.limit),d=await Xe(e,{...t,...i?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,i].includes(!0)},n,{input:await dn(r===void 0?t:{add:r},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:y=>Je(y),createEntry:y=>o===void 0?y:{...y,format:"json",data:o,event_type:Cm(o)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"For an approved append-only handoff on another owner's item, use the package-provided ownership bypass before considering --force.",examples:['pm notes pm-a1b2 --add "review note" --author "reviewer" --force'],nextSteps:["Use an installed package's narrow append-only ownership bypass when available.","Use --force only when an ownership override is explicitly approved."]}}),l=t.eventType?.trim(),m=d.notes.filter(y=>{let w=[y.format==="json",y.data!==void 0].every(Boolean),g=[a===void 0,Date.parse(y.created_at)>=(a??Number.POSITIVE_INFINITY)].includes(!0),h=[!l,y.event_type===l].includes(!0);return[!i,[w,g,h].every(Boolean)].includes(!0)}),f=i?Fa(m,c):m,_=f.filter(y=>y.format==="json").length;return{...d,notes:f,count:f.length,...i?{total_count:m.length,returned_count:f.length,has_more:f.length<m.length,...c===void 0?{}:{limit:c},structured_event_count:_}:t.includeMeta===!0?{structured_event_count:_}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f91de58-2cbc-52ba-97ea-42482d0c6ce1")}catch{}})();var Fc=1,jo="update-many",Om=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),$m=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),Pm={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},Fm=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],Lm={close_reason:"close_reason","close-reason":"close_reason",deadline:"deadline",estimate:"estimated_minutes",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",ac:"acceptance_criteria",definition_of_ready:"definition_of_ready","definition-of-ready":"definition_of_ready",order:"order",rank:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",why_now:"why_now","why-now":"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blocked_by:"blocked_by","blocked-by":"blocked_by",blocked_reason:"blocked_reason","blocked-reason":"blocked_reason",unblock_note:"unblock_note","unblock-note":"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",repro_steps:"repro_steps","repro-steps":"repro_steps",resolution:"resolution",expected_result:"expected_result","expected-result":"expected_result",actual_result:"actual_result","actual-result":"actual_result",affected_version:"affected_version","affected-version":"affected_version",fixed_version:"fixed_version","fixed-version":"fixed_version",component:"component",regression:"regression",customer_impact:"customer_impact","customer-impact":"customer_impact",type_options:"type_options","type-options":"type_options",tags:"tags"},Lc=e=>{let t={};for(let[n,o]of Object.entries(e))Om.has(n)||o!==void 0&&(t[n]=o);return t},Nm=e=>Object.keys(Lc(e)).length>0,Nc=e=>typeof e=="string"?e.trim():e,Mm=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},Do=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},Dm=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Nc(e)},jm={priority:Mm,estimatedMinutes:Do,order:Do,rank:Do,regression:Dm},Um=(e,t)=>{if(t!==void 0)return(jm[e]??Nc)(t)},Gm=e=>{let t=e.trim().toLowerCase().replaceAll("-","_");return Lm[t]??t},hn=(e,t)=>er(e,t),qm=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],zm=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,Hm=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Pc=(e,t)=>t===void 0?void 0:e[t],et=e=>Array.isArray(e)?e.length:0,Bm=(e,t,n)=>{let o=n[e.addKey],s=Pc(n,e.removeKey),r=et(o),i=et(s),a=n[e.clearKey]===!0,c=Pc(n,e.replaceKey)===!0;if(![a,c,r>0,i>0].includes(!0))return;let d=qm(e.field,t[e.field]);return{field:e.field,before:d,after:{operation:Hm({replace:c,clear:a,removeCount:i}),clear:a,replace:c,add_count:r,remove_count:i,before_count:zm(e.field,d)}}},Vm=(e,t)=>{let n=[];for(let o of Fm){let s=Bm(o,e,t);s!==void 0&&n.push(s)}return n},Wm=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],Km=(e,t)=>{if(![t.tags!==void 0,et(t.addTags)>0,et(t.removeTags)>0].includes(!0))return;let n=Wm(e.tags),o=t.tags===void 0?n:ht(t.tags),s=Tr(o,t.addTags),r=Or(s,t.removeTags).slice().sort((a,c)=>a.localeCompare(c)),i=n.slice().sort((a,c)=>a.localeCompare(c));if(!hn(i,r))return{field:"tags",before:n,after:r}},Ym=(e,t)=>{let n=e.acceptance_criteria,o=Cr(Ar(n),t.addAc,t.removeAc);if(o.unmatchedRemovals.length>0)throw new p(`Acceptance criteria removal did not match: ${o.unmatchedRemovals.join(", ")}`,u.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:o.unmatchedRemovals});let s=o.criteria.join("; ");if(!hn(typeof n=="string"?n:"",s))return{field:"acceptance_criteria",before:n,after:s}},Jm=(e,t,n)=>{for(let[o,s]of Object.entries(Pm)){let r=n[o];if(r===void 0)continue;let i=t[s],a=Um(o,r);hn(i,a)||e.push({field:s,before:i,after:a})}},Xm=(e,t,n,o)=>{let s=pr(n,o,["update_many"]);for(let[r,i]of Object.entries(s)){let a=t[r];hn(a,i)||e.push({field:r,before:a,after:i})}},Zm=(e,t,n)=>{for(let o of n??[]){let s=Gm(o),r=t[s];r!==void 0&&e.push({field:s,before:r,after:null})}},Qm=(e,t,n={})=>{let o=e,s=[],r=Km(o,n);if(r&&s.push(r),Jm(s,o,n),et(n.addAc)>0||et(n.removeAc)>0){let i=Ym(o,n);i!==void 0&&s.push(i)}return s.push(...Vm(o,n)),Xm(s,o,n,t),Zm(s,o,n.unset),{id:e.id,changes:s}},ep=(e,t)=>Fr(e,t,{strict:!0,flagLabel:"--filter-status"}),tp=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new p("--ids requires at least one non-empty item ID",u.USAGE)},np=[({update:e})=>{e.priority!==void 0&&Pr(e.priority)},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let o=P(t,O());if(!Ft(e.type,o))throw new p(Dr(e.type,o.types,lr(n,t.schema)),u.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!ft(e.status,t)){let n=t.definitions.map(o=>o.id);throw new p(`Invalid --status value "${e.status}". Allowed: ${n.join(", ")}`,u.USAGE)}},({update:e})=>{e.deadline!==void 0&&Bs(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&$r(e.estimatedMinutes,"estimated-minutes")}],op=(e,t,n,o)=>{let s={update:e,settings:t,statusRegistry:n,pmRoot:o};for(let r of np)r(s)},sp=async e=>{let t=await $t(e.pmRoot,jo,e.rollbackId,Fc),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,o=await Pt(t.items,(s,r)=>Me(s,r,{author:e.options.update?.author,message:n,force:e.options.update?.force??!0},e.global));return{...Le({applied:o.restored_ids.length,skipped:0,failed:o.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:o.restored_ids.length,failed_count:o.failed_count,rows:o.rows,ids:o.restored_ids}},rp=async e=>{let t={schema_version:Fc,id:e.checkpointId,created_at:e.nowValue,author:C(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Ot(e.pmRoot,jo,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},ip=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(s=>s.trim()).filter(s=>s.length>0))],o=new Set(t.map(s=>s.id));return n.filter(s=>!o.has(s))},Uo=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},ap=async e=>{let t=I(process.cwd(),e.path);if(!await x(A(t)))throw new p(`Tracker is not initialized at ${t}. Run pm init first.`,u.NOT_FOUND);let n=await R(t);return{pmRoot:t,settings:n,statusRegistry:q(n.schema),runtimeFieldRegistry:ut(n.schema)}},cp=e=>{if(e.options.dryRun===!0)throw new p("--dry-run cannot be combined with --rollback",u.USAGE);if(vt(e.options.list,e.options.status))throw new p("Rollback mode does not accept filter options",u.USAGE);if(Object.keys(e.updateSummary).length>0)throw new p("Rollback mode does not accept update mutation flags",u.USAGE);return sp({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},dp=async e=>{ep(e.options.status,e.runtime.statusRegistry);let t=await we(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(s=>{let r=Qm(s,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?r:{...r,warnings:[...e.dependencyWarnings]}}),o=e.options.list?.ids==null?[]:(await we(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(s=>s.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:ip(e.options.list?.ids,o)}},lp=e=>({outcome:"effect",exit_code:u.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...Uo(e)}),mp=e=>({...Le({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...Uo(e)}),pp=async e=>{let t=[],n=[],o=e.options.update.message??`update-many apply ${e.checkpointId}`,s=new Set(e.plans.filter(r=>r.changes.length>0).map(r=>r.id));for(let r of e.items){if(!s.has(r.id)){t.push({id:r.id,status:"skipped"});continue}try{let i=await ve(r.id,{...e.options.update,message:o,runtimeFieldCommands:["update_many"]},e.global);t.push({id:r.id,status:"updated",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(r.id)}catch(i){t.push({id:r.id,status:"failed",error:ye(i)})}}return{rows:t,updatedIds:n}},up=async e=>{if(e.plan.actionable.length===0)return mp(e.plan);let t=k(),n=Tt(jo,t),o=new Set(e.plan.actionable.map(m=>m.id)),s=e.plan.listed.items.filter(m=>o.has(m.id)).map(m=>({id:m.id,target_updated_at:m.updated_at})),r=e.options.checkpoint===!1?void 0:await rp({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:s}),i=await pp({items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),a=m=>i.rows.filter(f=>f.status===m).length,c=a("updated"),d=a("skipped"),l=a("failed");return{...Le({applied:c,skipped:d,failed:l,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...r?{checkpoint:r}:{},updated_count:c,skipped_count:d,failed_count:l,rows:i.rows,ids:i.updatedIds,...Uo(e.plan)}},Mc=async(e,t)=>{let n=await ap(t),o=typeof e.rollback=="string"?e.rollback:void 0,s=Lc(e.update);if(tp(e.list),o!==void 0)return cp({runtime:n,rollbackId:o,options:e,global:t,updateSummary:s});if(!Nm(e.update))throw new p(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${$m}).`,u.USAGE);op(e.update,n.settings,n.statusRegistry,n.pmRoot),Ga(e.update);let r=await Da({pmRoot:n.pmRoot,dependencies:Ua(e.update.dep,n.settings.id_prefix,k(),C(e.update.author,n.settings.author_default)).additions,idPrefix:n.settings.id_prefix,itemFormat:n.settings.item_format,typeToFolder:P(n.settings,O()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),i=await dp({options:e,global:t,runtime:n,updateSummary:s,dependencyWarnings:r});return e.dryRun===!0?lp(i):up({runtime:n,options:e,global:t,plan:i})};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d5ea029-26ef-51bc-bacc-b1d4d807a024")}catch{}})();var fp=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Dc=["brief","standard","deep"],Gc="plan-step-",Vo="draft",Bo=["bug-investigation","feature-implementation","refactoring-sprint"],jc={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function _p(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(jc,t)?jc[t]:void 0;if(!n)throw new p(`Unknown plan template "${e}". Allowed: ${Bo.join(", ")}`,u.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Bo[0]}`]});return n.map(o=>({...o}))}function hp(e,t){return t>0?Math.round(e/t*100):0}function qc(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(n=>n!=null).map(n=>(typeof n=="string"?n:String(n)).trim()).filter(n=>n.length>0)}function ne(e){return Array.isArray(e)?e.flatMap(t=>no(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?no(e,{unique:!1}):[]}function W(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function zc(e,t=Vo){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Fn.find(s=>s===n);if(!o)throw new p(`Invalid plan mode "${e}". Allowed: ${Fn.join(", ")}`,u.USAGE);return o}function Wo(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Ln.find(s=>s===n);if(!o)throw new p(`Invalid step status "${e}". Allowed: ${Ln.join(", ")}`,u.USAGE);return o}function Hc(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),o=Mn.find(s=>s===n);if(!o)throw new p(`Invalid step link kind "${e}". Allowed: ${Mn.join(", ")}`,u.USAGE);return o}function gp(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=Nn.find(o=>o===t);if(!n)throw new p(`Invalid plan harness "${e}". Allowed: ${Nn.join(", ")}`,u.USAGE);return n}function yp(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Dc.find(o=>o===t);if(!n)throw new p(`Invalid --depth "${e}". Allowed: ${Dc.join(", ")}`,u.USAGE);return n}function bp(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new p("Plan --fields requires a comma-separated list of plan field names",u.USAGE);return t}var Go=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function wp(e,t){let n=e,o={},s=[];for(let r of t){let i=r.startsWith("plan.")?r.slice(5):r;if(i.length!==0){if(!Go.has(i)){s.push(r);continue}Object.prototype.hasOwnProperty.call(n,i)&&(o[i]=n[i])}}if(s.length>0)throw new p(`Unknown Plan --fields value(s): ${s.join(", ")}`,u.USAGE,{nextSteps:[`Use --fields ${[...Go].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:s,suggested_retry:`pm plan show <id> --fields ${[...Go].join(",")}`}});return o}function Ko(e,t){let n={};for(let o of e.split(",")){let s=o.trim();if(s.length===0)continue;let r=s.indexOf("=");if(r<=0)throw new p(`Invalid ${t} entry "${s}"; expected key=value`,u.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[s.slice(0,r).trim().toLowerCase()]=s.slice(r+1).trim()}return n}function Yo(e){let t=Ko(e,"--file");if(!t.path)throw new p("--file requires path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function Jo(e){let t=Ko(e,"--test");if(!t.command&&!t.path)throw new p("--test requires at least command=<value> or path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function Xo(e){let t=Ko(e,"--doc");if(!t.path)throw new p("--doc requires path=<value>",u.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function vp(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=hp(t.completed,t.total),t}function kp(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let o=`${Gc}${String(n).padStart(3,"0")}`;if(!t.has(o))return o}throw new p("Could not allocate step id (limit reached)",u.GENERIC_FAILURE)}function tt(e,t){let n=t.trim();if(n.length===0)throw new p("Step reference cannot be empty",u.USAGE);let o=e.find(s=>s.id===n);if(o)return o;if(/^\d+$/.test(n)){let s=Number.parseInt(n,10),r=e.find(i=>i.order===s);if(r)return r}throw new p(`Step "${t}" not found in plan`,u.NOT_FOUND)}function Uc(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function Sp(e,t){let n=t.filter(i=>i.trim().toLowerCase()==="all"),o=[],s=[];if(n.length>0){if(t.length>n.length)throw new p("pm plan materialize --steps all cannot be combined with other step refs",u.USAGE);for(let i of e.slice().sort((a,c)=>a.order-c.order)){let a=Uc(i);if(a){s.push({from_step:i.id,...a});continue}o.push(i)}return{targets:o,skipped:s}}let r=new Set;for(let i of t){let a=tt(e,i);if(r.has(a.id))continue;r.add(a.id);let c=Uc(a);if(c){s.push({from_step:a.id,...c});continue}o.push(a)}return{targets:o,skipped:s}}function Ip(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,o=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||o?.trim()||void 0}function Ep(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function xp(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function Y(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((i,a)=>i.order-a.order),o=vp(n),s=Ep(n),r={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Vo,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:o,current_step:s?{id:s.id,order:s.order,title:s.title,status:s.status}:void 0,blocked_steps:xp(n),linked_items:(e.dependencies??[]).map(i=>({id:i.id,kind:i.kind}))};return(t==="standard"||t==="deep")&&(r.steps=n),t==="deep"&&(r.decisions=e.plan_decisions??[],r.discoveries=e.plan_discoveries??[],r.validation=e.plan_validation??[]),r}function J(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!oo(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function Bc(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new p(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,u.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function Rp(e){let t=I(process.cwd(),e.path);if(!await x(A(t)))throw new p(`Tracker is not initialized at ${t}. Run pm init first.`,u.NOT_FOUND);let n=await R(t);return{pmRoot:t,settings:n}}async function Vc(e,t){let n=P(e.settings,O()),o=await ee(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!o)throw new p(`Plan ${t} not found`,u.NOT_FOUND);let s=await H(o,{schema:e.settings.schema});return Bc(s.document.metadata),{document:s.document,itemId:o.id}}function Ap(e){let t=[];e.parent&&t.push(`id=${e.parent.trim()},kind=parent`);for(let n of ne(e.related))t.push(`id=${n},kind=related`);for(let n of ne(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of ne(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function Cp(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),o=e.validationExpected?.trim();if(!(!t&&!n&&!o))return{text:t||n||"Validation check",command:n||void 0,expected:o||void 0}}function Tp(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||ne(e.dependsOn).length>0||ne(e.link).length>0}function Op(e){let t=e.stepTitle?.trim()||void 0,n=qc(e.step),o=e.template?.trim()?_p(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...o.map(s=>s.title)],templateSteps:o}}function $p(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new p("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",u.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Bo[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new p("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",u.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function Pp(e,t){let n=Wo(e.stepStatus,"pending"),o=Zo(e,"depends_on"),s=W(e.file).map(Yo),r=W(e.test).map(Jo),i=W(e.doc).map(Xo),a=k();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:e.stepOwner?.trim()||void 0,evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:o.length>0?o:void 0,files:s.length>0?s:void 0,tests:r.length>0?r:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n==="completed"?a:void 0}}function Fp(e){let t=Op(e),n=Tp(e);if($p(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[Pp(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let o=k();return{steps:t.stepTitles.map((s,r)=>({id:`${Gc}${String(r+1).padStart(3,"0")}`,order:r+1,title:s,body:t.templateSteps[r]?.body,status:"pending",created_at:o,updated_at:o})),hasPerStepDetailOptions:n}}async function Lp(e,t,n){let o=e.title?.trim();if(!o)throw new p("pm plan create requires --title",u.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let s=zc(e.mode,Vo),r=gp(e.harness),i=e.fromSearch?.trim(),a=Cp(e),{steps:c,hasPerStepDetailOptions:d}=Fp(e);if(c.length===0&&d)throw new p("pm plan create step options require --step-title (or a single --step)",u.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let l=e.description?.trim()??e.scope?.trim()??o,m=e.claim?C(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:o,description:l,type:"Plan",template:void 0,file:W(e.file),test:W(e.test),doc:W(e.doc),field:W(e.field),assignee:C(e.author,n.settings.author_default),blockedBy:void 0,dep:Ap(e),message:e.message??(i?`plan create (search: ${i})`:"plan create")},_=await kt(f,t),y=await gt({pmRoot:n.pmRoot,settings:n.settings,id:_.item.id,op:"plan_create_metadata",author:C(e.author,n.settings.author_default),message:"seed plan metadata",mutate(g){let h=["plan_mode"];g.metadata.plan_mode=s,r&&(g.metadata.plan_harness=r,h.push("plan_harness"));let S=e.scope?.trim();S&&(g.metadata.plan_scope=S,h.push("plan_scope"));let E=e.resumeContext?.trim();return E&&(g.metadata.plan_resume_context=E,h.push("plan_resume_context")),g.metadata.plan_steps=c,h.push("plan_steps"),a&&(g.metadata.plan_validation=[...g.metadata.plan_validation??[],a],h.push("plan_validation")),m&&(g.metadata.assignee=m,h.push("assignee")),{changedFields:h}}}),w=Y(y.item,"brief");return{action:"create",plan:w,step:c[0],next_actions:J(_.item.id,w),warnings:[..._.warnings],generated_at:k()}}async function Np(e,t,n){let o=yp(t.depth),s=bp(t.fields),{document:r,itemId:i}=await Vc(n,e),a=Y(r.metadata,s===null?o:"deep");return{action:"show",plan:s===null?a:wp(a,s),next_actions:J(i,a),warnings:[],generated_at:k()}}function Mp(e,t){let n=new Map(Object.entries(t).filter(([o])=>o.startsWith("plan_")).map(([o,s])=>[o,JSON.stringify(s)]));return[...new Set([...e.keys(),...n.keys()])].filter(o=>e.get(o)!==n.get(o))}async function ae(e){let t=C(e.options.author,e.ctx.settings.author_default),n,o=await gt({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(s){Bc(s.metadata);let r=q(e.ctx.settings.schema);if(Be(s.metadata.status,r)||oo(s.metadata.plan_mode))throw new p(`Plan ${s.metadata.id} is terminal (status=${s.metadata.status}, plan_mode=${s.metadata.plan_mode??"unset"}) and cannot be mutated.`,u.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let i=(s.metadata.plan_steps??[]).slice(),a=new Map(Object.entries(s.metadata).filter(([m])=>m.startsWith("plan_")).map(([m,f])=>[m,JSON.stringify(f)])),c=e.mutator(i,s);n=c.resultStep;let d=i.slice().sort((m,f)=>m.order-f.order).map((m,f)=>({...m,order:f+1}));s.metadata.plan_steps=d;let l=Mp(a,s.metadata);return l.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:l.length>0?l:["plan_steps"]}}});return{document:{metadata:o.item,body:o.body},resultStep:n,itemId:o.item.id}}async function Dp(e,t,n){let o=t.stepTitle?.trim();if(!o)throw new p("pm plan add-step requires --step-title",u.USAGE);let s=Wo(t.stepStatus,"pending"),r=t.allowMultipleActive===!0,{document:i,resultStep:a,itemId:c}=await ae({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${o}"`,mutator(l){let m=l.length+1;Wc(l,void 0,s,r);let f=jp(l,t,{order:m,title:o,status:s});return l.push(f),{changedSteps:[f.id],resultStep:f}}}),d=Y(i.metadata,"standard");return{action:"add-step",plan:d,step:a,next_actions:J(c,d),warnings:[],generated_at:k()}}function Wc(e,t,n,o){if(n!=="in_progress"||o)return;let s=e.find(r=>r.id!==t&&r.status==="in_progress");if(s)throw new p(`Plan already has step ${s.id} in_progress. Pass --allow-multiple-active or update that step first.`,u.CONFLICT)}function jp(e,t,n){let o=Zo(t,"depends_on"),s=W(t.file).map(Yo),r=W(t.test).map(Jo),i=W(t.doc).map(Xo),a=k();return{id:kp(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:t.stepOwner?.trim()||void 0,evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:o.length>0?o:void 0,files:s.length>0?s:void 0,tests:r.length>0?r:void 0,docs:i.length>0?i:void 0,created_at:a,updated_at:a,completed_at:n.status==="completed"?a:void 0}}function Zo(e,t){let n=ne(e.dependsOn).map(l=>({id:l,kind:t})),o=ne(e.related).map(l=>({id:l,kind:"related"})),s=ne(e.blocks).map(l=>({id:l,kind:"blocks"})),r=ne(e.blockedBy).map(l=>({id:l,kind:"blocked_by"})),i=ne(e.link),a=Hc(e.linkKind,t),c=e.linkNote?.trim(),d=i.map(l=>{let m={id:l,kind:a};return c&&(m.note=c),m});return[...n,...o,...s,...r,...d]}async function qo(e,t,n,o){let{document:s,resultStep:r,itemId:i}=await ae({id:e,options:t,ctx:n,op:o.op,message:t.message??`${o.op} ${o.stepRef}`,mutator(c,d){let l=tt(c,o.stepRef),m=k(),f=o.finalStatus??Wo(t.stepStatus,l.status),_=t.allowMultipleActive===!0||o.allowMultipleActive===!0;return Wc(c,l.status==="in_progress"?l.id:void 0,f,_),Up(l,t,f,m),d.metadata.updated_at=m,{changedSteps:[l.id],resultStep:l}}}),a=Y(s.metadata,"standard");return{action:o.op==="plan_complete_step"?"complete-step":o.op==="plan_block_step"?"block-step":"update-step",plan:a,step:r,next_actions:J(i,a),warnings:[],generated_at:k()}}function Up(e,t,n,o){Gp(e,t,n),qp(e,t),e.status=n,e.updated_at=o,zp(e,n,o)}function Gp(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new p("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",u.USAGE)}function qp(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=t.stepOwner.trim()||void 0),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let o=W(t.file).map(Yo),s=W(t.test).map(Jo),r=W(t.doc).map(Xo);o.length>0&&(e.files=zo(e.files,o)),s.length>0&&(e.tests=zo(e.tests,s)),r.length>0&&(e.docs=zo(e.docs,r))}function zo(e,t){let n=[...e??[]],o=new Set(n.map(s=>JSON.stringify(s)));for(let s of t){let r=JSON.stringify(s);o.has(r)||(o.add(r),n.push(s))}return n}function zp(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function Hp(e,t,n,o,s){let{document:r,itemId:i}=await ae({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${o} -> ${s}`,mutator(c){let d=tt(c,o),l=c.filter(f=>f.id!==d.id),m=Math.max(1,Math.min(s,l.length+1));return l.splice(m-1,0,d),l.forEach((f,_)=>{f.order=_+1,f.updated_at=k()}),c.length=0,c.push(...l),{changedSteps:[d.id],resultStep:d}}}),a=Y(r.metadata,"standard");return{action:"reorder-step",plan:a,next_actions:J(i,a),warnings:[],generated_at:k()}}async function Bp(e,t,n,o){let{document:s,itemId:r}=await ae({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${o}`,mutator(a){let c=tt(a,o),d=a.filter(l=>l.id!==c.id);return d.forEach((l,m)=>{l.order=m+1}),a.length=0,a.push(...d),{changedSteps:[c.id]}}}),i=Y(s.metadata,"standard");return{action:"remove-step",plan:i,next_actions:J(r,i),warnings:[],generated_at:k()}}async function Vp(e,t,n,o){let s=Zo(t,Hc(t.linkKind,"related"));if(s.length===0)throw new p("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",u.USAGE);let r=t.promoteToItemDep===!0,{document:i,itemId:a,resultStep:c}=await ae({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${o}`,mutator(l,m){let f=tt(l,o),_=f.linked_items??[],y=g=>`${g.kind}:${g.id}`,w=new Set(_.map(y));for(let g of s){let h=y(g);w.has(h)||(_.push(g),w.add(h))}if(f.linked_items=_,f.updated_at=k(),r){let g=m.metadata.dependencies??[],h=E=>`${E.kind}:${E.id}`,S=new Set(g.map(h));for(let E of s){let F=E.kind==="depends_on"?"blocked_by":E.kind,T={id:E.id,kind:F,created_at:k(),author:C(t.author,n.settings.author_default)};S.has(h(T))||(g.push(T),S.add(h(T)))}m.metadata.dependencies=g}return{changedSteps:[f.id],resultStep:f}}}),d=Y(i.metadata,"standard");return{action:"link",plan:d,step:c,next_actions:J(a,d),warnings:[],generated_at:k()}}async function Wp(e,t,n,o){let s=ne(t.link);if(s.length===0)throw new p("pm plan unlink requires --link <id> to remove",u.USAGE);let{document:r,itemId:i,resultStep:a}=await ae({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${o}`,mutator(d){let l=tt(d,o),m=(l.linked_items??[]).filter(f=>!s.includes(f.id));return l.linked_items=m.length>0?m:void 0,l.updated_at=k(),{changedSteps:[l.id],resultStep:l}}}),c=Y(r.metadata,"standard");return{action:"unlink",plan:c,step:a,next_actions:J(i,c),warnings:[],generated_at:k()}}async function Ho(e,t,n,o){let s=Ip(o,t);if(!s){let d=`--${o}-text`,l=`--${o}`;throw new p(`pm plan ${o} requires ${d}`,u.USAGE,{code:"missing_required_option",examples:[`pm plan ${o} <plan-id> ${d} "..."`,`pm plan ${o} <plan-id> ${l} "..."`],recovery:{suggested_retry:`pm plan ${o} <plan-id> ${d} <value>`}})}let r=C(t.author,n.settings.author_default),{document:i,itemId:a}=await ae({id:e,options:t,ctx:n,op:`plan_append_${o}`,message:t.message??`plan ${o} append`,mutator(d,l){let m=k();if(o==="decision"){let _=l.metadata.plan_decisions??[];return _.push({ts:m,author:r,decision:s,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),l.metadata.plan_decisions=_,{changedSteps:[]}}if(o==="discovery"){let _=l.metadata.plan_discoveries??[];return _.push({ts:m,author:r,text:s}),l.metadata.plan_discoveries=_,{changedSteps:[]}}let f=l.metadata.plan_validation??[];return f.push({text:s,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),l.metadata.plan_validation=f,{changedSteps:[]}}}),c=Y(i.metadata,"deep");return{action:o,plan:c,next_actions:J(a,c),warnings:[],generated_at:k()}}async function Kp(e,t,n){let o=t.resumeContext?.trim();if(!o)throw new p("pm plan resume requires --resume-context <text>",u.USAGE);let{document:s,itemId:r}=await ae({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(a,c){c.metadata.plan_resume_context=o;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),i=Y(s.metadata,"brief");return{action:"resume",plan:i,next_actions:J(r,i),warnings:[],generated_at:k()}}async function Yp(e,t,n){let o=zc(t.mode??"approved","approved"),{document:s,itemId:r}=await ae({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${o}`,mutator(a,c){c.metadata.plan_mode=o;let d=t.scope?.trim();return d&&(c.metadata.plan_scope=d),{changedSteps:[]}}}),i=Y(s.metadata,"brief");return{action:"approve",plan:i,next_actions:J(r,i),warnings:[],generated_at:k()}}function Kc(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function Jp(e,t){let n=Y(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:J(e.itemId,n),warnings:Kc(t),generated_at:k()}}function Xp(e,t,n){let o=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let s of n.linked_items??[]){let r=s.kind==="blocked_by"||s.kind==="blocks"||s.kind==="related"||s.kind==="discovered_from"?s.kind:"related";o.push(`id=${s.id},kind=${r}`)}return o}async function Zp(e){let t=[],n={},o=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let s of W(e.options.field)){let r=s.indexOf("=");if(r<=0)throw new p(`Invalid --field entry "${s}"; expected name=value`,u.USAGE);let i=s.slice(0,r).trim(),a=s.slice(r+1).trim();if(i.length===0)throw new p(`Invalid --field entry "${s}"; expected name=value`,u.USAGE);let c=i.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new p(`Invalid --field entry "${s}"; expected name=value`,u.USAGE);let[d,...l]=c,m=`${d}${l.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(o.has(m))throw new p(`Invalid --field entry "${s}"; "${m}" is reserved by materialize and cannot be overridden`,u.USAGE);n[m]=a}for(let s of e.targets){let r=await kt({...n,title:s.title,description:s.body?.trim()||s.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${s.id}`,dep:Xp(e.parent,e.planItemId,s)},{path:e.pmRoot});t.push({id:r.item.id,title:r.item.title,type:e.resolvedTypeName,parent:r.item.parent,tags:r.item.tags??[],from_step:s.id})}return t}function Qp(e,t,n){for(let o of t){let s=n.find(a=>a.from_step===o.id);if(!s)continue;let r=e.find(a=>a.id===o.id);if(!r)continue;let i=r.linked_items??[];i.push({id:s.id,kind:"implements",note:`materialized as ${s.type}`}),r.linked_items=i,r.updated_at=k()}}async function eu(e,t,n){let o=ne(t.steps);if(o.length===0)throw new p("pm plan materialize requires --steps <ids|orders|all>",u.USAGE);let s=t.materializeType?.trim()||"Task",r=P(n.settings,O()),i=Ft(s,r);if(!i)throw new p(`Invalid --materialize-type "${s}"`,u.USAGE);let a=t.materializeParent?.trim()||e,c=t.materializeTags,d=await Vc(n,e),l=(d.document.metadata.plan_steps??[]).slice(),{targets:m,skipped:f}=Sp(l,o);if(m.length===0){if(f.length>0)return Jp(d,f);throw new p("No matching plan steps found for --steps",u.NOT_FOUND)}let _=await Zp({targets:m,parent:a,planItemId:d.itemId,resolvedTypeName:i,tags:c,options:t,pmRoot:n.pmRoot}),{document:y,itemId:w}=await ae({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${o.join(",")}`,mutator(h){return Qp(h,m,_),{changedSteps:m.map(S=>S.id)}}}),g=Y(y.metadata,"standard");return{action:"materialize",plan:g,materialized:_,...f.length>0?{materialize_skipped:f}:{},next_actions:J(w,g),warnings:Kc(f),generated_at:k()}}function tu(e){if(e.subcommand==="create")return e;let t=qc(e.options.step);if(t.length>1)throw new p(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,u.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:{...e.options,stepTitle:t[0]}}:e}function he(e,t){if(!e.id)throw new p(`pm plan ${t} requires a plan id`,u.USAGE);return e.id}function De(e,t){let n=he(e,t);if(!e.stepRef)throw new p(`pm plan ${t} requires <plan-id> <step>`,u.USAGE);return{id:n,stepRef:e.stepRef}}function nu(e){let t=De(e,"reorder-step");if(e.reorderTo===void 0)throw new p("pm plan reorder-step requires <plan-id> <step> <new-order>",u.USAGE);return{...t,reorderTo:e.reorderTo}}var ou={create:(e,t)=>Lp(e.options,e.global,t),show:(e,t)=>Np(he(e,"show"),e.options,t),"add-step":(e,t)=>Dp(he(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=De(e,"update-step");return qo(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=De(e,"complete-step");return qo(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=De(e,"block-step");return qo(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=nu(e);return Hp(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=De(e,"remove-step");return Bp(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=De(e,"link");return Vp(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=De(e,"unlink");return Wp(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Ho(he(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Ho(he(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Ho(he(e,"validation"),e.options,t,"validation"),resume:(e,t)=>Kp(he(e,"resume"),e.options,t),approve:(e,t)=>Yp(he(e,"approve"),e.options,t),materialize:(e,t)=>eu(he(e,"materialize"),e.options,t)};function su(e){let t=ou[e];if(!t)throw le({command_path:"plan",token:e,allowed:fp});return t}async function Yc(e){let t=await Rp(e.global),n=tu(e);return su(n.subcommand)(n,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4eb2056a-4444-514a-a0db-79b8875c3d65")}catch{}})();function ru(e,t){return[...new Set([...zs.filter(o=>e[o]!==void 0),...Object.keys(e).filter(o=>e[o]!==void 0),...t.length>0?["body"]:[]])].sort((o,s)=>o.localeCompare(s))}function iu(e,t){let n=`copied_from=${e}`;if(!t)return n;let o=t.trim();return o.length>0?`${o} | ${n}`:n}async function Qo(e,t,n){let o=I(process.cwd(),n.path);if(!await x(A(o)))throw new p(`Tracker is not initialized at ${o}. Run pm init first.`,u.NOT_FOUND);let s=await R(o),r=P(s,O()),i=await ee(o,e,s.id_prefix,s.item_format,r.type_to_folder);if(!i)throw await Vt(o,e,s.id_prefix,r.type_to_folder);let a=await H(i,{schema:s.schema}),c=a.document.metadata,d=k(),l=C(t.author,s.author_default),m=await Xn(o,s.id_prefix,{tokenLength:s.ids.token_length,typeToFolder:r.type_to_folder,probeExisting:!1}),f=q(s.schema),_=t.title?.trim();if(_!==void 0&&_.length===0)throw new p("Copy --title must not be empty",u.USAGE);let y={...c,id:m,title:_??c.title,status:f.open_status,created_at:d,updated_at:d};delete y.closed_at,delete y.completed_at,delete y.close_reason,delete y.test_runs;let w=ze(O()),g=Ae({metadata:y,body:a.document.body},{schema:s.schema,extensionFieldNames:w}),h=await bo({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:o,mode:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":s.governance.duplicate_detection_mode,threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),S=ru(g.metadata,g.body),E=mt(o,g.metadata.type,m,s.item_format,r.type_to_folder),F=se(o,m),T=await K(o,m,s.locks.ttl_seconds,l,!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms),j={metadata:{},body:""},U,Z;try{let de=await Ht(o,l,{required:s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{s.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await bo({title:g.metadata.title,description:g.metadata.description,body:g.body,excludeIds:[i.id]},{pmRoot:o,mode:"strict",threshold:s.governance.duplicate_detection_threshold,limit:s.governance.duplicate_detection_limit,allowDuplicate:!1});let Ee=await ee(o,m,s.id_prefix,s.item_format,r.type_to_folder);if(Ee)throw new p(`Cannot copy to ${m}: an item with that id already exists at ${Ee.itemPath}. Retry the copy to allocate a new id.`,u.CONFLICT,{code:"item_id_collision",why:`Allocated id ${m} already exists at ${Ee.itemPath}.`,recovery:{suggested_retry:`pm copy ${i.id}`}});await B(E,me(g,{format:s.item_format,schema:s.schema,extensionFieldNames:w}));try{let oe=re({nowIso:d,author:l,op:"create",before:j,after:g,message:iu(i.id,t.message)});await Ce(F,oe)}catch(oe){throw await dt(E),oe}Z=await Bt({pmRoot:o,preferredFormat:s.item_format,typeToFolder:r.type_to_folder,schema:s.schema,itemPath:E,document:g})}finally{await de()}U=[...await N({path:E,scope:"project",op:"create",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:S}),...await N({path:F,scope:"project",op:"create:history",item_id:g.metadata.id,item_type:g.metadata.type,before:j,after:g,changed_fields:S})],Nt({id:g.metadata.id,op:"create",item_type:g.metadata.type,status:g.metadata.status,current:pt(g.metadata,S),changed_fields:S})}finally{await T()}return{source_id:i.id,item:structuredClone(g.metadata),changed_fields:S,warnings:[...ja(h),...Z,...U],...h===void 0?{}:{similarity_advisory:h}}}import gn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="14aa55e1-cb5f-55ea-bf4c-412217d87449")}catch{}})();async function es(e,t,n){let o=I(process.cwd(),n.path);if(!await x(A(o)))throw new p(`Tracker is not initialized at ${o}. Run pm init first.`,u.NOT_FOUND);let s=await R(o),r=C(t.author,s.author_default),i=await Vr({pmRoot:o,settings:s,id:e,author:r,message:t.message,force:t.force,dryRun:t.dryRun}),a=i.targetPath?gn.relative(o,i.targetPath).split(gn.sep).join("/"):void 0;return{item:i.item,changed_fields:i.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:i.item.status,...a?{target_path:a}:{},history_retained:gn.relative(o,se(o,i.item.id)).split(gn.sep).join("/"),tombstone_retention:"retain_append_only",warnings:i.warnings}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0f43df79-0b27-53b3-b8bd-9f2a35561733")}catch{}})();async function au(e){if(!await x(A(e)))throw new p(`Tracker is not initialized at ${e}. Run pm init first.`,u.NOT_FOUND)}async function ts(e,t,n){let o=I(process.cwd(),n.path);if(await au(o),t.clear===!0){if(e!==void 0)throw new p("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",u.USAGE);let m=await R(o),f=Yn(C(void 0,m.author_default));return await _r(o),await _o({pmRoot:o,settings:m,principal:f}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let m=await ur(o);if(m===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let f=await cu(o,m);return{action:"show",focused_item:m,title:f,message:`Focused on ${m}${f?` (${f})`:""}. New items default --parent to it.`}}let r=await R(o),i=P(r,O()),a=await ee(o,e,r.id_prefix,r.item_format,i.type_to_folder);if(!a)throw await Vt(o,e,r.id_prefix,i.type_to_folder);let c=_t(a.id,r.id_prefix),d=await H(a,{schema:r.schema}),l=Jc(d.document.metadata.title);return await fr(o,c),await _o({pmRoot:o,settings:r,principal:Yn(C(void 0,r.author_default)),itemId:c}),{action:"set",focused_item:c,title:l,message:`Focused on ${c}${l?` (${l})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function cu(e,t){let n=await R(e),o=P(n,O()),s=await ee(e,t,n.id_prefix,n.item_format,o.type_to_folder);if(!s)return null;let r=await H(s,{schema:n.schema});return Jc(r.document.metadata.title)}function Jc(e){return e.trim().length>0?e:null}import{readFile as bu,writeFile as wu}from"node:fs/promises";import vu 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]="f6f04eec-0698-5e5b-a40e-de3a4be89f95")}catch{}})();function ns(e,t){let n=Mt(e);if(n)throw new p(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,u.GENERIC_FAILURE);let o=[];for(let[s,r]of e.split(/\r?\n/).entries()){let i=r.trim();if(i)try{let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");o.push(a)}catch{throw new p(`History merge input (${t}) contains invalid JSON at line ${s+1}.`,u.GENERIC_FAILURE)}}return o}function Se(e){return D({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function du(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&Se(e[o])===Se(t[o]);)o+=1;return o}function Xc(e,t,n){ns(e,"base");let o=ns(t,"ours"),s=ns(n,"theirs"),r=du(o,s);if(r===o.length&&r===s.length)return{merged:ue(o),strategy:"identical",common_entries:r,entries_from_ours:0,entries_from_theirs:0,entries_total:o.length,reanchored:!1};if(r===s.length)return{merged:ue(o),strategy:"fast_forward_ours",common_entries:r,entries_from_ours:o.length-r,entries_from_theirs:0,entries_total:o.length,reanchored:!1};if(r===o.length)return{merged:ue(s),strategy:"fast_forward_theirs",common_entries:r,entries_from_ours:0,entries_from_theirs:s.length-r,entries_total:s.length,reanchored:!1};let i=o.slice(r),a=new Set(i.map(Se)),c=s.slice(r).filter(m=>!a.has(Se(m))),d=[...i,...c].sort((m,f)=>{let _=Ct(m.ts,f.ts);if(_!==0)return _;let y=a.has(Se(m)),w=a.has(Se(f));return y!==w?Number(w)-Number(y):Se(m).localeCompare(Se(f))}),l=Ut([...o.slice(0,r),...d]);return{merged:ue(l.entries),strategy:"union_reanchor",common_entries:r,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:l.entries.length,reanchored:!0}}function os(e,t){let n=Mt(e);if(n)throw new p(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,u.GENERIC_FAILURE);let o=[];for(let[s,r]of e.split(/\r?\n/).entries()){let i=r.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{throw new p(`Relationship merge input (${t}) contains invalid JSON at line ${s+1}.`,u.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new p(`Relationship merge input (${t}) line ${s+1} is not a relationship event (eventId + sequence required).`,u.GENERIC_FAILURE);o.push(a)}return o}function yn(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
11
11
  `)}
12
- `}function Yp(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Gc(e,t,n){es(e,"base");let o=es(t,"ours"),s=es(n,"theirs"),r=Math.min(o.length,s.length),i=0;for(;i<r&&o[i].eventId===s[i].eventId;)i+=1;if(i===o.length&&i===s.length)return{merged:gn(o),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:o.length,reanchored:!1};if(i===s.length)return{merged:gn(o),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:o.length-i,entries_from_theirs:0,entries_total:o.length,reanchored:!1};if(i===o.length)return{merged:gn(s),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:s.length-i,entries_total:s.length,reanchored:!1};let a=o.slice(i),c=new Set(a.map(f=>f.eventId)),d=s.slice(i).filter(f=>!c.has(f.eventId)),l=[...a,...d].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let g=At(f.timestamp,_.timestamp);if(g!==0)return g}else{if(f.timestamp===void 0&&_.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let y=c.has(f.eventId),w=c.has(_.eventId);return y!==w?Number(w)-Number(y):0}),m=Yp([...o.slice(0,i),...l]);return{merged:gn(m),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:d.length,entries_total:m.length,reanchored:!0}}var Jp=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],Xp=["updated_at"];function Me(e,t){return D(e??null)===D(t??null)}function Zp(e,t,n){let o=l=>Array.isArray(l)?l:[],s=new Set(o(e).map(l=>D(l))),r=o(t),i=new Set(r.map(l=>D(l))),a=o(n),c=new Set(a.map(l=>D(l))),d=r.filter(l=>{let m=D(l);return!s.has(m)||c.has(m)});for(let l of a){let m=D(l);!i.has(m)&&!s.has(m)&&d.push(l)}return d}function Qp(e,t){return At(String(e),String(t))>=0?e:t}function qc(e,t,n,o){return Me(t,n)?{value:t,from_theirs:!1,conflict:!1}:Me(e,t)?{value:n,from_theirs:!0,conflict:!1}:Me(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:o==="theirs"?n:t,from_theirs:o==="theirs",conflict:!0}}function zc(e,t,n,o,s){let r=qc(e,t,n,o);if(!r.conflict||s==="preferred_side")return r;let i=D(n).localeCompare(D(t))<0;return{value:i?n:t,from_theirs:i,conflict:!0}}function ts(e){return{...e.metadata}}function ns(e,t,n){try{return Re(Mt(e,n),n)}catch(o){throw new p(`Item merge input (${t}) is not a readable item document: ${String(o)}`,u.GENERIC_FAILURE)}}function eu(e,t,n,o,s){let r=new Set(Jp),i=new Set(Xp),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((d,l)=>d.localeCompare(l)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let d of a){let l=e[d],m=t[d],f=n[d];if(r.has(d)){let y=Zp(l,m,f);c.merged[d]=y,Me(y,m)||c.unionFields.push(d);continue}if(i.has(d)){c.merged[d]=Qp(m,f);continue}let _=zc(l,m,f,o,s);_.value!==void 0&&(c.merged[d]=_.value),_.conflict?(c.conflictFields.push(d),c.conflictDecisions.push({field:d,base:l,ours:m,theirs:f,retained:_.value,discarded:_.from_theirs?m:f})):_.from_theirs&&c.fieldsFromTheirs.push(d)}return c}function Hc(e,t,n,o={}){let s=o.preferred??"ours",r=o.conflictResolution??"preferred_side",i=e.trim().length>0,a=ns(t,"ours",o),c=ns(n,"theirs",o),d=i?ns(e,"base",o):a,l=i?ts(d):{},m=ts(a),f=ts(c),{merged:_,conflictFields:y,fieldsFromTheirs:w,unionFields:g,conflictDecisions:h}=eu(l,m,f,s,r),k=zc(i?d.body:"",a.body,c.body,s,r);return k.conflict?(y.push("body"),h.push({field:"body",base:i?d.body:"",ours:a.body,theirs:c.body,retained:k.value,discarded:k.from_theirs?a.body:c.body})):k.from_theirs&&w.push("body"),{merged:le({metadata:_,body:k.value},o),conflict_fields:y,fields_from_theirs:w,union_fields:g,conflict_decisions:h,preferred:s,conflict_resolution:r}}function os(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ss(e,t){let n=Nt(e);if(n)throw new p(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,u.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new p(`JSON merge input (${t}) is not valid JSON.`,u.GENERIC_FAILURE)}}function tu(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let o=d=>{let l=new Map;for(let m of d){let f=D(m);l.set(f,(l.get(f)??0)+1)}return l},s=o(e),r=o(t),i=o(n);for(let[d,l]of s)if((r.get(d)??0)<l||(i.get(d)??0)<l)return null;let a=new Map(r),c=[];for(let d of n){let l=D(d),m=a.get(l)??0;m>0?a.set(l,m-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function nu(e,t,n,o,s,r,i){if(!os(t)||!os(n))return null;let a=os(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,m)=>l.localeCompare(m));for(let l of d){let m=s.length>0?`${s}.${l}`:l,f=ou(a,t,n,l,o,m,r,i);f!==void 0&&(c[l]=f)}return c}function Bc(e,t,n,o,s,r,i){if(Me(t,n))return t;let a=tu(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(s),a.merged;let c=nu(e,t,n,o,s,r,i);if(c!==null)return c;let d=qc(e,t,n,o);return d.conflict?r.push(s):d.from_theirs&&i.push(s),d.value}function ou(e,t,n,o,s,r,i,a){let c=Object.prototype.hasOwnProperty.call(t,o),d=Object.prototype.hasOwnProperty.call(n,o),l=Object.prototype.hasOwnProperty.call(e,o);if(c&&d)return Bc(e[o],t[o],n[o],s,r,i,a);if(c){if(l&&Me(e[o],t[o])){a.push(r);return}return l?(i.push(r),s==="theirs"?void 0:t[o]):t[o]}if(!(l&&Me(e[o],n[o])))return l?(i.push(r),s==="theirs"?n[o]:void 0):(a.push(r),n[o])}function Vc(e,t,n,o={}){let s=o.preferred??"ours",r=ss(e,"base"),i=ss(t,"ours"),a=ss(n,"theirs"),c=[],d=[],l=Bc(r,i,a,s,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
13
- `,conflict_paths:c,paths_from_theirs:d,preferred:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e739a603-35c5-5df9-8d4b-3bbc0fe3e4fd")}catch{}})();var Wc=["item","history","relationship","json"];function au(e){let t=e.trim().toLowerCase();if(Wc.includes(t))return t;throw new p(`Unknown merge artifact "${e}". Supported values: ${Wc.join(", ")}.`,u.USAGE)}function cu(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new p(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,u.USAGE)}async function rs(e,t){try{return await su(e,"utf8")}catch{throw new p(`Cannot read merge ${t} file at ${e}.`,u.NOT_FOUND)}}async function du(e){let t=x(process.cwd(),e.path);return await E(A(t))?R(t):null}function lu(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Kc(e,t){let n=au(e.artifact),o=cu(e.prefer),s=iu.resolve(e.outputPath??e.oursPath),[r,i,a]=await Promise.all([rs(e.basePath,"base"),rs(e.oursPath,"ours"),rs(e.theirsPath,"theirs")]),c,d,l=[],m={};if(n==="history"){let _=Uc(r,i,a);c=_.merged,m.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=Gc(r,i,a);c=_.merged,m.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await du(t),y=Hc(r,i,a,{format:lu(e.itemPath??s,_),schema:_?.schema,extensionFieldNames:Ge(T()),preferred:o,conflictResolution:"stable_value_order"});c=y.merged,l.push(...y.conflict_fields),m.item={fields_from_theirs:y.fields_from_theirs,union_fields:y.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0&&(d={cwd:process.cwd(),itemPath:e.itemPath,preferred:o,conflictResolution:"stable_value_order",fieldsFromTheirs:y.fields_from_theirs,unionFields:y.union_fields,decisions:y.conflict_decisions})}else{let _=Vc(r,i,a,{preferred:o});c=_.merged,l.push(..._.conflict_paths),m.json={paths_from_theirs:_.paths_from_theirs}}if(await ru(s,c,"utf8"),d!==void 0){let _=await Ia(d);_!==null&&(m.receipt=wt(_))}let f=[];if(l.length>0){let _=m.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${m.receipt.receipt_id} with item ${m.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${l.join(", ")}; the item driver kept the direction-independent stable value. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&m.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:l.length===0,artifact:n,output_path:s,preferred:o,conflicts:l,...m,guidance:f,generated_at:S()}}import Xc from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dd5ab9c3-bc6f-59f1-be89-ad0ab2abe7b5")}catch{}})();function Yc(e,t){return t==="body"?e.body:e.metadata[t]}function is(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=new Set;return e.every(s=>{let r=t.findIndex((i,a)=>!o.has(a)&&is(s,i));return r<0?!1:(o.add(r),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([o,s])=>Object.hasOwn(n,o)&&is(s,n[o]))}function Jc(e,t){let n=new Set(t),o=[];for(let s=e.length-1;s>=0&&n.size>0;s-=1){let r=e[s],i=new Set;for(let c of br(r.patch))i.add(Ut(c.path)),c.from&&i.add(Ut(c.from));let a=[...n].filter(c=>i.has(c));if(a.length!==0){for(let c of a)n.delete(c);o.push({index:s+1,ts:r.ts,author:r.author,op:r.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return o.reverse()}function mu(e,t,n){let o=Xc.compare(t,n);if(o.length===0)return;let s=new Set;for(let y of o)s.add(Ut(y.path));let r=new Set([...s].filter(y=>is(Yc(t,y),Yc(n,y)))),i=new Set([...s].filter(y=>!r.has(y))),a=Jc(e,i),c=Jc(e,r),d=[...s].sort((y,w)=>y.localeCompare(w)),l=[...i].sort((y,w)=>y.localeCompare(w)),m=[...r].sort((y,w)=>y.localeCompare(w)),f=[...new Set(a.map(y=>y.author))].sort((y,w)=>y.localeCompare(w)),_=[...new Set(c.map(y=>y.author))].sort((y,w)=>y.localeCompare(w));return{reconciled_field_count:s.size,reconciled_fields:d,reverted_field_count:i.size,reverted_fields:l,discarded_events:a,discarded_authors:f,preserved_field_count:r.size,preserved_fields:m,preserved_events:c,preserved_authors:_,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function pu(e,t,n){let o=e.located?.itemPath??null,s=e.located?await H(e.located,{schema:t.schema}):null;if(!s)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let r=Te(s.document),i=n[n.length-1]?.after_hash;return{currentItemReplay:r,currentItemPath:o,matchedChainBefore:ee(r)===i,currentItemRawBeforeLock:s.raw,loadedItem:s}}function uu(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function fu(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:S(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Xc.compare(e.finalReplay,e.currentItemReplay):[],before_hash:ee(e.finalReplay),after_hash:ee(n),message:e.message,...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function _u(e,t){let n=[];return e||n.push("history_repair_no_changes"),t>0&&n.push(`history_repair_skipped_unresolvable_ops:${t}`),n}async function hu(e){return Zt({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Xt({historyPath:e.historyPath,nextHistoryRaw:pe(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>N({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function It(e,t,n){let o=x(process.cwd(),n.path);if(!await E(A(o)))throw new p(`Tracker is not initialized at ${o}. Run pm init first.`,u.NOT_FOUND);let s=await R(o),r=F(s,T()),i=await Qt(o,e,s,r.type_to_folder);if(!await E(i.historyPath))throw new p(`No history stream exists for ${i.id}.`,u.NOT_FOUND);let a=await G(i.historyPath),c=await ze(i.historyPath,i.id);if(c.length===0)throw new p(`No history entries exist for ${i.id}; nothing to repair.`,u.USAGE);let d=Be(c),l=jt(c),m=await pu(i,s,c),f=l.finalDocument,_=m.currentItemReplay!==null&&ee(f)!==ee(m.currentItemReplay),y=_&&m.currentItemReplay?mu(l.entries,f,m.currentItemReplay):void 0,w=[l.entriesRehashed>0,l.entriesPatchRepaired>0,_,t.forceAuditEntry===!0].some(Boolean),g=O(t.author,s.author_default),h=!!t.dryRun,k=uu({message:t.message,entriesRehashed:l.entriesRehashed,entriesPatchRepaired:l.entriesPatchRepaired,reconcileNeeded:_}),{rewrittenEntries:I,auditEntryAdded:P}=fu({reanchorEntries:l.entries,changed:w,reconcileNeeded:_,currentItemReplay:m.currentItemReplay,finalReplay:f,author:g,message:k,auditOperation:t.auditOperation??"history_repair",auditContext:t.auditContext}),C=Be(I);if(!C.ok)throw new p(`history-repair produced an invalid rewritten chain (${C.errors.join(", ")}).`,u.GENERIC_FAILURE);let j=_u(w,l.skippedOps);return y&&y.discarded_events.length>0&&(j.push(`history_repair_reconcile_discards_events:${y.discarded_events.length}`),j.push(`history_repair_discarded_authors:${y.discarded_authors.join(",")}`)),w&&!h&&j.push(...await hu({pmRoot:o,subject:i,settings:s,typeRegistry:r,historyRawBeforeLock:a,currentItemRawBeforeLock:m.currentItemRawBeforeLock,author:g,force:t.force,loadedItem:m.loadedItem,historyPath:i.historyPath,rewrittenEntries:I})),{id:i.id,dry_run:h,changed:w,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!d.ok,entries_rehashed:l.entriesRehashed,entries_patch_repaired:l.entriesPatchRepaired,converted_replace_to_add:l.convertedReplaceToAdd,skipped_ops:l.skippedOps,reconciled_with_item:_,audit_entry_added:P,verify_ok:C.ok,verify_errors:C.errors},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},...y?{reconciliation:y}:{},warnings:[...new Set(j)].sort((U,Q)=>U.localeCompare(Q)),generated_at:S()}}function Zc(e,t){if(t&&e!==void 0)throw new p("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",u.USAGE);if(!t&&e===void 0)throw new p("history-repair: provide an item <id> or pass --all to repair every drifted stream.",u.USAGE)}async function yn(e,t){let n=x(process.cwd(),t.path);if(!await E(A(n)))throw new p(`Tracker is not initialized at ${n}. Run pm init first.`,u.NOT_FOUND);let o=await R(n),s=F(o,T()),r=[],i=await Mr(n,o.item_format,s.type_to_folder,r,o.schema,{forceSourceScan:!0}),a=await _a(n,i),c=[],d=[],l={repaired:0,skipped_clean:0,failed:0};for(let m of a.driftedItems)try{let f=await It(m,{...e,auditContext:e.auditContextById?.[m],auditContextById:void 0},t),_=f.changed?"repaired":"skipped_clean";l[_]+=1,d.push(...f.warnings.map(y=>`${m}:${y}`)),c.push({id:m,outcome:_,entries_rehashed:f.history.entries_rehashed,entries_patch_repaired:f.history.entries_patch_repaired,reconciled_with_item:f.history.reconciled_with_item,...f.reconciliation?{reconciliation:f.reconciliation}:{},warnings:f.warnings})}catch(f){l.failed+=1,c.push({id:m,outcome:"failed",error:f instanceof Error?f.message:String(f)})}return e.dryRun||await gr(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:a.driftedItems.length,streams:c,totals:l,warnings:[...new Set([...r,...d])].sort((m,f)=>m.localeCompare(f)),generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c5620467-6c8c-5702-b742-57fba9e302c5")}catch{}})();async function Qc(e,t){let n=e.dryRun===!0,o=await Ea(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=xa(o);if(!n&&e.force!==!0&&s.length>0)throw new p(`Merge reconciliation would accept ${s.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,u.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:s.map(g=>`Review receipt ${g.id} for ${g.item_id}: ${g.decisions.map(h=>h.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let r=o.reduce((g,h)=>((g[h.item_id]??=[]).push(h),g),{}),i=Object.fromEntries(Object.entries(r).map(([g,h])=>[g,{merge:{receipts:h.map(wt)}}])),a=await yn({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:i},t),c=new Set(a.streams.map(g=>g.id)),d=Object.keys(r).filter(g=>!c.has(g));(await Promise.allSettled(d.map(g=>It(g,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:i[g],forceAuditEntry:!0},t)))).forEach((g,h)=>{let k=d[h];if(g.status==="fulfilled"){let I=g.value.changed?"repaired":"skipped_clean";a.streams.push({id:k,outcome:I,entries_rehashed:g.value.history.entries_rehashed,entries_patch_repaired:g.value.history.entries_patch_repaired,reconciled_with_item:g.value.history.reconciled_with_item,warnings:g.value.warnings}),a.totals[I]+=1}else a.streams.push({id:k,outcome:"failed",error:g.reason instanceof Error?g.reason.message:String(g.reason)}),a.totals.failed+=1});let m=0;!n&&a.totals.failed===0&&(await Promise.all(o.map(g=>Ra(process.cwd(),g))),m=o.length);let f=await ln({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),_=f.checks.every(g=>g.status==="ok"),y=a.totals.failed===0&&_,w=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:y?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:y,dry_run:n,repair:a,receipts:{pending_before:o.length,reconciled:m,summaries:o.map(wt)},validation:f,guidance:w,generated_at:f.generated_at}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f8cd69db-ec70-560f-a8c2-2d8d4be75459")}catch{}})();function Et(e){return{...e.args,...e.options}}function he(e,t){let n=b(e,t);if(n!==void 0)return n;throw new p(`Missing required parameter: ${t}`,u.USAGE)}function et(e){return typeof e=="string"?[e]:W(e)}function ed(e){return Na(Et(e),e.global)}function td(e){let t=Et(e);return Ma({cwd:b(t,"cwd"),pmRoot:b(t,"path"),since:b(t,"since"),type:et(t.type),author:et(t.author),item:et(t.item),limit:t.limit===void 0?void 0:B(t.limit,"limit"),full:t.full===!0,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:et(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:et(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:et(t.provenanceFilter)}})}function nd(e){let t=Et(e),n=he(t,"subcommand");if(n==="install")return Wi({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return Qc({dryRun:t.dryRun===!0,author:b(t,"author"),message:b(t,"message"),force:t.force===!0},e.global);if(n==="report")return Aa({includeReconciled:t.includeReconciled===!0,cwd:b(t,"cwd")});if(n==="driver")return Kc({artifact:he(t,"artifact"),basePath:he(t,"basePath"),oursPath:he(t,"oursPath"),theirsPath:he(t,"theirsPath"),outputPath:b(t,"outputPath")??b(t,"output"),itemPath:b(t,"itemPath"),prefer:b(t,"prefer")},e.global);throw new p(`Unknown merge subcommand "${n}".`,u.USAGE,{code:"unknown_subcommand"})}function od(e){let t=Et(e),n=he(t,"subcommand");if(n!=="snapshot")throw new p(`Unknown workspace subcommand "${n}".`,u.USAGE,{code:"unknown_subcommand"});let o=b(t,"snapshotAction")??he(t,"snapshot_action"),s=x(process.cwd(),e.global.path);if(o==="create")return Ga(s,{name:b(t,"name")});if(o==="list")return za(s);let r=he(t,"target");if(o==="inspect")return qa(s,r);if(o==="delete")return Va(s,r);if(o==="restore")return t.dryRun===!0?Ha(s,r):Ba(s,r,{force:t.force===!0,author:b(t,"author"),message:b(t,"message"),lockTtlSeconds:B(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:B(t.lockWaitMs,"lockWaitMs")});throw new p(`Unknown workspace snapshot action "${o}".`,u.USAGE,{code:"unknown_subcommand"})}function bn(e){let t=Et(e),n=he(t,"title");return e.action==="meet"?Da(n,t,e.global):e.action==="event"?ja(n,t,e.global):Ua(n,t,e.global)}import Du 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]="bed1d1d4-0c1d-59e5-8267-fbe800dfd83b")}catch{}})();var tt=["agile","ops","research"],as={agile:{name:"agile",title:"Agile delivery",summary:"Story/Spike delivery with a review stage, story points, and acceptance ownership.",types:rn.agile,statuses:[{id:"review",roles:["active"],aliases:["in-review"],description:"Work is implementation-complete and awaiting peer review."}],fields:[{key:"story_points",type:"number",commands:["create","update","list"],description:"Relative estimation size for a story or spike.",aliases:["points"]},{key:"acceptance_owner",type:"string",commands:["create","update","list"],description:"Stakeholder accountable for accepting the delivered story.",aliases:["acceptor"]}],workflows:[{type:"Story",allowed_transitions:[["open","in_progress"],["in_progress","review"],["review","in_progress"],["review","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search works without an embedding service."},{key:"search_max_results",value:"20",summary:"Sprint-sized result cap for quick triage."}],templates:[{name:"story",options:{type:"Story",priority:"2",tags:"story",acceptanceCriteria:"Story delivers the stated user outcome with tests and docs updated.",body:`## As a
12
+ `}function lu(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Zc(e,t,n){os(e,"base");let o=os(t,"ours"),s=os(n,"theirs"),r=Math.min(o.length,s.length),i=0;for(;i<r&&o[i].eventId===s[i].eventId;)i+=1;if(i===o.length&&i===s.length)return{merged:yn(o),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:o.length,reanchored:!1};if(i===s.length)return{merged:yn(o),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:o.length-i,entries_from_theirs:0,entries_total:o.length,reanchored:!1};if(i===o.length)return{merged:yn(s),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:s.length-i,entries_total:s.length,reanchored:!1};let a=o.slice(i),c=new Set(a.map(f=>f.eventId)),d=s.slice(i).filter(f=>!c.has(f.eventId)),l=[...a,...d].sort((f,_)=>{if(f.timestamp!==void 0&&_.timestamp!==void 0){let g=Ct(f.timestamp,_.timestamp);if(g!==0)return g}else{if(f.timestamp===void 0&&_.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let y=c.has(f.eventId),w=c.has(_.eventId);return y!==w?Number(w)-Number(y):0}),m=lu([...o.slice(0,i),...l]);return{merged:yn(m),strategy:"union_reanchor",common_entries:i,entries_from_ours:a.length,entries_from_theirs:d.length,entries_total:m.length,reanchored:!0}}var mu=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],pu=["updated_at"];function je(e,t){return D(e??null)===D(t??null)}function uu(e,t,n){let o=l=>Array.isArray(l)?l:[],s=new Set(o(e).map(l=>D(l))),r=o(t),i=new Set(r.map(l=>D(l))),a=o(n),c=new Set(a.map(l=>D(l))),d=r.filter(l=>{let m=D(l);return!s.has(m)||c.has(m)});for(let l of a){let m=D(l);!i.has(m)&&!s.has(m)&&d.push(l)}return d}function fu(e,t){return Ct(String(e),String(t))>=0?e:t}function Qc(e,t,n,o){return je(t,n)?{value:t,from_theirs:!1,conflict:!1}:je(e,t)?{value:n,from_theirs:!0,conflict:!1}:je(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:o==="theirs"?n:t,from_theirs:o==="theirs",conflict:!0}}function ed(e,t,n,o,s){let r=Qc(e,t,n,o);if(!r.conflict||s==="preferred_side")return r;let i=D(n).localeCompare(D(t))<0;return{value:i?n:t,from_theirs:i,conflict:!0}}function ss(e){return{...e.metadata}}function rs(e,t,n){try{return Ae(Dt(e,n),n)}catch(o){throw new p(`Item merge input (${t}) is not a readable item document: ${String(o)}`,u.GENERIC_FAILURE)}}function _u(e,t,n,o,s){let r=new Set(mu),i=new Set(pu),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((d,l)=>d.localeCompare(l)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let d of a){let l=e[d],m=t[d],f=n[d];if(r.has(d)){let y=uu(l,m,f);c.merged[d]=y,je(y,m)||c.unionFields.push(d);continue}if(i.has(d)){c.merged[d]=fu(m,f);continue}let _=ed(l,m,f,o,s);_.value!==void 0&&(c.merged[d]=_.value),_.conflict?(c.conflictFields.push(d),c.conflictDecisions.push({field:d,base:l,ours:m,theirs:f,retained:_.value,discarded:_.from_theirs?m:f})):_.from_theirs&&c.fieldsFromTheirs.push(d)}return c}function td(e,t,n,o={}){let s=o.preferred??"ours",r=o.conflictResolution??"preferred_side",i=e.trim().length>0,a=rs(t,"ours",o),c=rs(n,"theirs",o),d=i?rs(e,"base",o):a,l=i?ss(d):{},m=ss(a),f=ss(c),{merged:_,conflictFields:y,fieldsFromTheirs:w,unionFields:g,conflictDecisions:h}=_u(l,m,f,s,r),S=ed(i?d.body:"",a.body,c.body,s,r);return S.conflict?(y.push("body"),h.push({field:"body",base:i?d.body:"",ours:a.body,theirs:c.body,retained:S.value,discarded:S.from_theirs?a.body:c.body})):S.from_theirs&&w.push("body"),{merged:me({metadata:_,body:S.value},o),conflict_fields:y,fields_from_theirs:w,union_fields:g,conflict_decisions:h,preferred:s,conflict_resolution:r}}function is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function as(e,t){let n=Mt(e);if(n)throw new p(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,u.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new p(`JSON merge input (${t}) is not valid JSON.`,u.GENERIC_FAILURE)}}function hu(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let o=d=>{let l=new Map;for(let m of d){let f=D(m);l.set(f,(l.get(f)??0)+1)}return l},s=o(e),r=o(t),i=o(n);for(let[d,l]of s)if((r.get(d)??0)<l||(i.get(d)??0)<l)return null;let a=new Map(r),c=[];for(let d of n){let l=D(d),m=a.get(l)??0;m>0?a.set(l,m-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function gu(e,t,n,o,s,r,i){if(!is(t)||!is(n))return null;let a=is(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,m)=>l.localeCompare(m));for(let l of d){let m=s.length>0?`${s}.${l}`:l,f=yu(a,t,n,l,o,m,r,i);f!==void 0&&(c[l]=f)}return c}function nd(e,t,n,o,s,r,i){if(je(t,n))return t;let a=hu(e,t,n);if(a!==null)return a.acceptedTheirs&&i.push(s),a.merged;let c=gu(e,t,n,o,s,r,i);if(c!==null)return c;let d=Qc(e,t,n,o);return d.conflict?r.push(s):d.from_theirs&&i.push(s),d.value}function yu(e,t,n,o,s,r,i,a){let c=Object.prototype.hasOwnProperty.call(t,o),d=Object.prototype.hasOwnProperty.call(n,o),l=Object.prototype.hasOwnProperty.call(e,o);if(c&&d)return nd(e[o],t[o],n[o],s,r,i,a);if(c){if(l&&je(e[o],t[o])){a.push(r);return}return l?(i.push(r),s==="theirs"?void 0:t[o]):t[o]}if(!(l&&je(e[o],n[o])))return l?(i.push(r),s==="theirs"?n[o]:void 0):(a.push(r),n[o])}function od(e,t,n,o={}){let s=o.preferred??"ours",r=as(e,"base"),i=as(t,"ours"),a=as(n,"theirs"),c=[],d=[],l=nd(r,i,a,s,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
13
+ `,conflict_paths:c,paths_from_theirs:d,preferred:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e739a603-35c5-5df9-8d4b-3bbc0fe3e4fd")}catch{}})();var sd=["item","history","relationship","json"];function ku(e){let t=e.trim().toLowerCase();if(sd.includes(t))return t;throw new p(`Unknown merge artifact "${e}". Supported values: ${sd.join(", ")}.`,u.USAGE)}function Su(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new p(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,u.USAGE)}async function cs(e,t){try{return await bu(e,"utf8")}catch{throw new p(`Cannot read merge ${t} file at ${e}.`,u.NOT_FOUND)}}async function Iu(e){let t=I(process.cwd(),e.path);return await x(A(t))?R(t):null}function Eu(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function rd(e,t){let n=ku(e.artifact),o=Su(e.prefer),s=vu.resolve(e.outputPath??e.oursPath),[r,i,a]=await Promise.all([cs(e.basePath,"base"),cs(e.oursPath,"ours"),cs(e.theirsPath,"theirs")]),c,d,l=[],m={};if(n==="history"){let _=Xc(r,i,a);c=_.merged,m.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=Zc(r,i,a);c=_.merged,m.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await Iu(t),y=td(r,i,a,{format:Eu(e.itemPath??s,_),schema:_?.schema,extensionFieldNames:ze(O()),preferred:o,conflictResolution:"stable_value_order"});c=y.merged,l.push(...y.conflict_fields),m.item={fields_from_theirs:y.fields_from_theirs,union_fields:y.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0&&(d={cwd:process.cwd(),itemPath:e.itemPath,preferred:o,conflictResolution:"stable_value_order",fieldsFromTheirs:y.fields_from_theirs,unionFields:y.union_fields,decisions:y.conflict_decisions})}else{let _=od(r,i,a,{preferred:o});c=_.merged,l.push(..._.conflict_paths),m.json={paths_from_theirs:_.paths_from_theirs}}if(await wu(s,c,"utf8"),d!==void 0){let _=await Sa(d);_!==null&&(m.receipt=wt(_))}let f=[];if(l.length>0){let _=m.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${m.receipt.receipt_id} with item ${m.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${l.join(", ")}; the item driver kept the direction-independent stable value. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&m.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:l.length===0,artifact:n,output_path:s,preferred:o,conflicts:l,...m,guidance:f,generated_at:k()}}import cd from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dd5ab9c3-bc6f-59f1-be89-ad0ab2abe7b5")}catch{}})();function id(e,t){return t==="body"?e.body:e.metadata[t]}function ds(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=new Set;return e.every(s=>{let r=t.findIndex((i,a)=>!o.has(a)&&ds(s,i));return r<0?!1:(o.add(r),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([o,s])=>Object.hasOwn(n,o)&&ds(s,n[o]))}function ad(e,t){let n=new Set(t),o=[];for(let s=e.length-1;s>=0&&n.size>0;s-=1){let r=e[s],i=new Set;for(let c of xr(r.patch))i.add(Gt(c.path)),c.from&&i.add(Gt(c.from));let a=[...n].filter(c=>i.has(c));if(a.length!==0){for(let c of a)n.delete(c);o.push({index:s+1,ts:r.ts,author:r.author,op:r.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return o.reverse()}function xu(e,t,n){let o=cd.compare(t,n);if(o.length===0)return;let s=new Set;for(let y of o)s.add(Gt(y.path));let r=new Set([...s].filter(y=>ds(id(t,y),id(n,y)))),i=new Set([...s].filter(y=>!r.has(y))),a=ad(e,i),c=ad(e,r),d=[...s].sort((y,w)=>y.localeCompare(w)),l=[...i].sort((y,w)=>y.localeCompare(w)),m=[...r].sort((y,w)=>y.localeCompare(w)),f=[...new Set(a.map(y=>y.author))].sort((y,w)=>y.localeCompare(w)),_=[...new Set(c.map(y=>y.author))].sort((y,w)=>y.localeCompare(w));return{reconciled_field_count:s.size,reconciled_fields:d,reverted_field_count:i.size,reverted_fields:l,discarded_events:a,discarded_authors:f,preserved_field_count:r.size,preserved_fields:m,preserved_events:c,preserved_authors:_,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function Ru(e,t,n){let o=e.located?.itemPath??null,s=e.located?await H(e.located,{schema:t.schema}):null;if(!s)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let r=Oe(s.document),i=n[n.length-1]?.after_hash;return{currentItemReplay:r,currentItemPath:o,matchedChainBefore:Q(r)===i,currentItemRawBeforeLock:s.raw,loadedItem:s}}function Au(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function Cu(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:k(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?cd.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Q(e.finalReplay),after_hash:Q(n),message:e.message,...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function Tu(e,t){let n=[];return e||n.push("history_repair_no_changes"),t>0&&n.push(`history_repair_skipped_unresolvable_ops:${t}`),n}async function Ou(e){return Zt({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Xt({historyPath:e.historyPath,nextHistoryRaw:ue(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>N({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function Et(e,t,n){let o=I(process.cwd(),n.path);if(!await x(A(o)))throw new p(`Tracker is not initialized at ${o}. Run pm init first.`,u.NOT_FOUND);let s=await R(o),r=P(s,O()),i=await Qt(o,e,s,r.type_to_folder);if(!await x(i.historyPath))throw new p(`No history stream exists for ${i.id}.`,u.NOT_FOUND);let a=await G(i.historyPath),c=await Ve(i.historyPath,i.id);if(c.length===0)throw new p(`No history entries exist for ${i.id}; nothing to repair.`,u.USAGE);let d=Ke(c),l=Ut(c),m=await Ru(i,s,c),f=l.finalDocument,_=m.currentItemReplay!==null&&Q(f)!==Q(m.currentItemReplay),y=_&&m.currentItemReplay?xu(l.entries,f,m.currentItemReplay):void 0,w=[l.entriesRehashed>0,l.entriesPatchRepaired>0,_,t.forceAuditEntry===!0].some(Boolean),g=C(t.author,s.author_default),h=!!t.dryRun,S=Au({message:t.message,entriesRehashed:l.entriesRehashed,entriesPatchRepaired:l.entriesPatchRepaired,reconcileNeeded:_}),{rewrittenEntries:E,auditEntryAdded:F}=Cu({reanchorEntries:l.entries,changed:w,reconcileNeeded:_,currentItemReplay:m.currentItemReplay,finalReplay:f,author:g,message:S,auditOperation:t.auditOperation??"history_repair",auditContext:t.auditContext}),T=Ke(E);if(!T.ok)throw new p(`history-repair produced an invalid rewritten chain (${T.errors.join(", ")}).`,u.GENERIC_FAILURE);let j=Tu(w,l.skippedOps);return y&&y.discarded_events.length>0&&(j.push(`history_repair_reconcile_discards_events:${y.discarded_events.length}`),j.push(`history_repair_discarded_authors:${y.discarded_authors.join(",")}`)),w&&!h&&j.push(...await Ou({pmRoot:o,subject:i,settings:s,typeRegistry:r,historyRawBeforeLock:a,currentItemRawBeforeLock:m.currentItemRawBeforeLock,author:g,force:t.force,loadedItem:m.loadedItem,historyPath:i.historyPath,rewrittenEntries:E})),{id:i.id,dry_run:h,changed:w,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!d.ok,entries_rehashed:l.entriesRehashed,entries_patch_repaired:l.entriesPatchRepaired,converted_replace_to_add:l.convertedReplaceToAdd,skipped_ops:l.skippedOps,reconciled_with_item:_,audit_entry_added:F,verify_ok:T.ok,verify_errors:T.errors},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},...y?{reconciliation:y}:{},warnings:[...new Set(j)].sort((U,Z)=>U.localeCompare(Z)),generated_at:k()}}function dd(e,t){if(t&&e!==void 0)throw new p("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",u.USAGE);if(!t&&e===void 0)throw new p("history-repair: provide an item <id> or pass --all to repair every drifted stream.",u.USAGE)}async function bn(e,t){let n=I(process.cwd(),t.path);if(!await x(A(n)))throw new p(`Tracker is not initialized at ${n}. Run pm init first.`,u.NOT_FOUND);let o=await R(n),s=P(o,O()),r=[],i=await Hr(n,o.item_format,s.type_to_folder,r,o.schema,{forceSourceScan:!0}),a=await Wi(n,i),c=[],d=[],l={repaired:0,skipped_clean:0,failed:0};for(let m of a.driftedItems)try{let f=await Et(m,{...e,auditContext:e.auditContextById?.[m],auditContextById:void 0},t),_=f.changed?"repaired":"skipped_clean";l[_]+=1,d.push(...f.warnings.map(y=>`${m}:${y}`)),c.push({id:m,outcome:_,entries_rehashed:f.history.entries_rehashed,entries_patch_repaired:f.history.entries_patch_repaired,reconciled_with_item:f.history.reconciled_with_item,...f.reconciliation?{reconciliation:f.reconciliation}:{},warnings:f.warnings})}catch(f){l.failed+=1,c.push({id:m,outcome:"failed",error:f instanceof Error?f.message:String(f)})}return e.dryRun||await Ir(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:a.driftedItems.length,streams:c,totals:l,warnings:[...new Set([...r,...d])].sort((m,f)=>m.localeCompare(f)),generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c5620467-6c8c-5702-b742-57fba9e302c5")}catch{}})();async function ld(e,t){let n=e.dryRun===!0,o=await Ia(process.cwd(),{includeLossless:!0}),{pendingDecisions:s}=Ea(o);if(!n&&e.force!==!0&&s.length>0)throw new p(`Merge reconciliation would accept ${s.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,u.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:s.map(g=>`Review receipt ${g.id} for ${g.item_id}: ${g.decisions.map(h=>h.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let r=o.reduce((g,h)=>((g[h.item_id]??=[]).push(h),g),{}),i=Object.fromEntries(Object.entries(r).map(([g,h])=>[g,{merge:{receipts:h.map(wt)}}])),a=await bn({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:i},t),c=new Set(a.streams.map(g=>g.id)),d=Object.keys(r).filter(g=>!c.has(g));(await Promise.allSettled(d.map(g=>Et(g,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:i[g],forceAuditEntry:!0},t)))).forEach((g,h)=>{let S=d[h];if(g.status==="fulfilled"){let E=g.value.changed?"repaired":"skipped_clean";a.streams.push({id:S,outcome:E,entries_rehashed:g.value.history.entries_rehashed,entries_patch_repaired:g.value.history.entries_patch_repaired,reconciled_with_item:g.value.history.reconciled_with_item,warnings:g.value.warnings}),a.totals[E]+=1}else a.streams.push({id:S,outcome:"failed",error:g.reason instanceof Error?g.reason.message:String(g.reason)}),a.totals.failed+=1});let m=0;!n&&a.totals.failed===0&&(await Promise.all(o.map(g=>xa(process.cwd(),g))),m=o.length);let f=await an({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),_=f.checks.every(g=>g.status==="ok"),y=a.totals.failed===0&&_,w=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:y?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:y,dry_run:n,repair:a,receipts:{pending_before:o.length,reconciled:m,summaries:o.map(wt)},validation:f,guidance:w,generated_at:f.generated_at}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="37ac2a74-f150-5b9d-96d6-d9cc441215be")}catch{}})();function xt(e){return{...e.args,...e.options}}function ge(e,t){let n=b(e,t);if(n!==void 0)return n;throw new p(`Missing required parameter: ${t}`,u.USAGE)}function nt(e){return typeof e=="string"?[e]:V(e)}function md(e){return Ka(xt(e),e.global)}function pd(e){let t=xt(e);return Ya({cwd:b(t,"cwd"),pmRoot:b(t,"path"),since:b(t,"since"),type:nt(t.type),author:nt(t.author),item:nt(t.item),limit:t.limit===void 0?void 0:te(t.limit,"limit"),full:t.full===!0,...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:nt(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:nt(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:nt(t.provenanceFilter)}})}function ud(e){let t=xt(e),n=ge(t,"subcommand");if(n==="install")return na({dryRun:t.dryRun===!0},e.global);if(n==="reconcile")return ld({dryRun:t.dryRun===!0,author:b(t,"author"),message:b(t,"message"),force:t.force===!0},e.global);if(n==="report")return Ra({includeReconciled:t.includeReconciled===!0,cwd:b(t,"cwd")});if(n==="driver")return rd({artifact:ge(t,"artifact"),basePath:ge(t,"basePath"),oursPath:ge(t,"oursPath"),theirsPath:ge(t,"theirsPath"),outputPath:b(t,"outputPath")??b(t,"output"),itemPath:b(t,"itemPath"),prefer:b(t,"prefer")},e.global);throw le({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function fd(e){let t=xt(e),n=ge(t,"subcommand");if(n!=="snapshot")throw le({command_path:"workspace",token:n,allowed:["snapshot"],display_name:"workspace"});let o=b(t,"snapshotAction")??ge(t,"snapshot_action"),s=I(process.cwd(),e.global.path);if(o==="create")return Qa(s,{name:b(t,"name")});if(o==="list")return tc(s);let r=ge(t,"target");if(o==="inspect")return ec(s,r);if(o==="delete")return sc(s,r);if(o==="restore")return t.dryRun===!0?nc(s,r):oc(s,r,{force:t.force===!0,author:b(t,"author"),message:b(t,"message"),lockTtlSeconds:te(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:te(t.lockWaitMs,"lockWaitMs")});throw le({command_path:"workspace snapshot",token:o,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function wn(e){let t=xt(e),n=ge(t,"title");return e.action==="meet"?Ja(n,t,e.global):e.action==="event"?Xa(n,t,e.global):Za(n,t,e.global)}import Qu 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]="bed1d1d4-0c1d-59e5-8267-fbe800dfd83b")}catch{}})();var ot=["agile","ops","research"],ls={agile:{name:"agile",title:"Agile delivery",summary:"Story/Spike delivery with a review stage, story points, and acceptance ownership.",types:sn.agile,statuses:[{id:"review",roles:["active"],aliases:["in-review"],description:"Work is implementation-complete and awaiting peer review."}],fields:[{key:"story_points",type:"number",commands:["create","update","list"],description:"Relative estimation size for a story or spike.",aliases:["points"]},{key:"acceptance_owner",type:"string",commands:["create","update","list"],description:"Stakeholder accountable for accepting the delivered story.",aliases:["acceptor"]}],workflows:[{type:"Story",allowed_transitions:[["open","in_progress"],["in_progress","review"],["review","in_progress"],["review","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search works without an embedding service."},{key:"search_max_results",value:"20",summary:"Sprint-sized result cap for quick triage."}],templates:[{name:"story",options:{type:"Story",priority:"2",tags:"story",acceptanceCriteria:"Story delivers the stated user outcome with tests and docs updated.",body:`## As a
14
14
 
15
15
  ## I want
16
16
 
@@ -18,7 +18,7 @@ import{a as ua,b as Xe,c as mn,d as $a,e as Pa,f as Fa}from"./chunk-5JO6R4BS.js"
18
18
 
19
19
  ## Acceptance
20
20
  - [ ]
21
- `}}],packages:[{spec:"templates",reason:"Reusable create templates for recurring story shapes."},{spec:"calendar",reason:"Sprint and iteration scheduling views."},{spec:"search-advanced",reason:"Richer retrieval as the backlog grows."}]},ops:{name:"ops",title:"Operations",summary:"Incident/Runbook response with mitigation and monitoring stages, severity, and service fields.",types:rn.ops,statuses:[{id:"mitigating",roles:["active"],aliases:["mitigation"],description:"Active mitigation is underway to restore service."},{id:"monitoring",roles:["active"],aliases:["observing"],description:"Mitigation applied; monitoring for recurrence before closure."}],fields:[{key:"severity",type:"string",commands:["create","update","list"],description:"Incident severity classification (e.g. sev1, sev2, sev3).",aliases:["sev"]},{key:"service",type:"string",commands:["create","update","list"],description:"Primary affected service or component."}],workflows:[{type:"Incident",allowed_transitions:[["open","mitigating"],["mitigating","monitoring"],["monitoring","mitigating"],["monitoring","closed"],["mitigating","blocked"],["blocked","mitigating"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search for fast incident lookup."},{key:"search_max_results",value:"25",summary:"Wider result cap to surface related incidents and runbooks."}],templates:[{name:"incident",options:{type:"Incident",priority:"1",tags:"incident",acceptanceCriteria:"Service restored, root cause documented, and follow-ups filed.",body:`## Impact
21
+ `}}],packages:[{spec:"templates",reason:"Reusable create templates for recurring story shapes."},{spec:"calendar",reason:"Sprint and iteration scheduling views."},{spec:"search-advanced",reason:"Richer retrieval as the backlog grows."}]},ops:{name:"ops",title:"Operations",summary:"Incident/Runbook response with mitigation and monitoring stages, severity, and service fields.",types:sn.ops,statuses:[{id:"mitigating",roles:["active"],aliases:["mitigation"],description:"Active mitigation is underway to restore service."},{id:"monitoring",roles:["active"],aliases:["observing"],description:"Mitigation applied; monitoring for recurrence before closure."}],fields:[{key:"severity",type:"string",commands:["create","update","list"],description:"Incident severity classification (e.g. sev1, sev2, sev3).",aliases:["sev"]},{key:"service",type:"string",commands:["create","update","list"],description:"Primary affected service or component."}],workflows:[{type:"Incident",allowed_transitions:[["open","mitigating"],["mitigating","monitoring"],["monitoring","mitigating"],["monitoring","closed"],["mitigating","blocked"],["blocked","mitigating"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search for fast incident lookup."},{key:"search_max_results",value:"25",summary:"Wider result cap to surface related incidents and runbooks."}],templates:[{name:"incident",options:{type:"Incident",priority:"1",tags:"incident",acceptanceCriteria:"Service restored, root cause documented, and follow-ups filed.",body:`## Impact
22
22
 
23
23
  ## Timeline
24
24
 
@@ -27,14 +27,14 @@ import{a as ua,b as Xe,c as mn,d as $a,e as Pa,f as Fa}from"./chunk-5JO6R4BS.js"
27
27
  ## Mitigation
28
28
 
29
29
  ## Follow-ups
30
- `}}],packages:[{spec:"lifecycle-hooks",reason:"Automate transitions and notifications on incident state changes."},{spec:"governance-audit",reason:"Audit incident metadata completeness and closure quality."},{spec:"calendar",reason:"On-call and follow-up scheduling."}]},research:{name:"research",title:"Research",summary:"Experiment/Hypothesis investigation with an analysis stage, hypothesis, and method fields.",types:rn.research,statuses:[{id:"analyzing",roles:["active"],aliases:["analysis"],description:"Data collected; analysis and synthesis in progress."}],fields:[{key:"hypothesis",type:"string",commands:["create","update"],description:"The testable claim the experiment evaluates."},{key:"method",type:"string",commands:["create","update","list"],description:"Experimental method or protocol used to evaluate the hypothesis.",aliases:["protocol"]}],workflows:[{type:"Experiment",allowed_transitions:[["open","in_progress"],["in_progress","analyzing"],["analyzing","in_progress"],["analyzing","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search across the research corpus."},{key:"search_max_results",value:"50",summary:"Broader recall cap for literature and prior-experiment discovery."}],templates:[{name:"experiment",options:{type:"Experiment",priority:"2",tags:"experiment",acceptanceCriteria:"Hypothesis is supported, rejected, or refined with recorded evidence.",body:`## Hypothesis
30
+ `}}],packages:[{spec:"lifecycle-hooks",reason:"Automate transitions and notifications on incident state changes."},{spec:"governance-audit",reason:"Audit incident metadata completeness and closure quality."},{spec:"calendar",reason:"On-call and follow-up scheduling."}]},research:{name:"research",title:"Research",summary:"Experiment/Hypothesis investigation with an analysis stage, hypothesis, and method fields.",types:sn.research,statuses:[{id:"analyzing",roles:["active"],aliases:["analysis"],description:"Data collected; analysis and synthesis in progress."}],fields:[{key:"hypothesis",type:"string",commands:["create","update"],description:"The testable claim the experiment evaluates."},{key:"method",type:"string",commands:["create","update","list"],description:"Experimental method or protocol used to evaluate the hypothesis.",aliases:["protocol"]}],workflows:[{type:"Experiment",allowed_transitions:[["open","in_progress"],["in_progress","analyzing"],["analyzing","in_progress"],["analyzing","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search across the research corpus."},{key:"search_max_results",value:"50",summary:"Broader recall cap for literature and prior-experiment discovery."}],templates:[{name:"experiment",options:{type:"Experiment",priority:"2",tags:"experiment",acceptanceCriteria:"Hypothesis is supported, rejected, or refined with recorded evidence.",body:`## Hypothesis
31
31
 
32
32
  ## Method
33
33
 
34
34
  ## Results
35
35
 
36
36
  ## Conclusion
37
- `}}],packages:[{spec:"search-advanced",reason:"Semantic retrieval over experiments and findings."},{spec:"templates",reason:"Consistent experiment and hypothesis scaffolds."},{spec:"beads",reason:"Import structured prior work into the tracker."}]}};function gu(e){if(e===void 0)return;let t=Se(e);if(t.length===0)throw new Error("Profile name must not be empty.");if(tt.includes(t))return t;throw new Error(`Invalid profile "${e}". Allowed: ${tt.join(", ")}.`)}function Hb(e){let t=gu(e);if(t===void 0)throw new Error(`Profile name is required. Allowed: ${tt.join(", ")}.`);return as[t]}function Bb(){return tt.map(e=>as[e])}function Se(e){return e.trim().toLowerCase().replaceAll("-","_")}function sd(e){return e.map(t=>t.definition.name).join(", ")}function cs(e=[]){let t=tt.map(r=>({definition:as[r],source:"builtin"})),n=new Set(tt.map(r=>Se(r))),o=new Set(n),s=[];for(let r of e){let i=Se(r.profile.name);if(n.has(i)){s.push(`Extension "${r.name}" profile "${r.profile.name}" uses a name reserved by a built-in archetype and was ignored.`);continue}if(o.has(i)){s.push(`Profile "${r.profile.name}" from extension "${r.name}" duplicates an already-registered profile and was ignored.`);continue}o.add(i),t.push({definition:r.profile,source:"extension",package:r.name})}return{profiles:t,warnings:s}}function wn(e,t=[]){let{profiles:n,warnings:o}=cs(t);if(typeof e!="string"||e.trim().length===0)throw new Error(`Profile name is required. Allowed: ${sd(n)}.`);let s=Se(e),r=n.find(i=>Se(i.definition.name)===s);if(r===void 0)throw new Error(`Invalid profile "${e}". Allowed: ${sd(n)}.`);return{resolved:r,warnings: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]="933d8f74-c4aa-58d0-bd3b-8932a35d3702")}catch{}})();function ls(e){return{types:e.types.length,statuses:e.statuses.length,fields:e.fields.length,workflows:e.workflows.length,config:e.config.length,templates:e.templates.length,packages:e.packages.length}}function rd(e){return{name:e.name,title:e.title,summary:e.summary,composition:ls(e),types:e.types.map(t=>ds(()=>ue(t).name,()=>String(t.name??""))),statuses:e.statuses.map(t=>ds(()=>$e(t).id,()=>String(t.id??""))),fields:e.fields.map(t=>ds(()=>Pe(t).key,()=>String(t.key??""))),workflows:e.workflows.map(t=>t.type),config:e.config.map(t=>`${t.key}=${t.value}`),templates:e.templates.map(t=>t.name),packages:e.packages.map(t=>({spec:t.spec,reason:t.reason}))}}function ds(e,t){try{return e()}catch{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]="f9b22df0-7ec2-5d72-bc88-3eb7201a6051")}catch{}})();var aw=["profile","types","statuses","fields","workflows","config","templates","packages"],cw=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],yu=new Set(sr.flatMap(e=>[We(e.id),...(e.aliases??[]).map(t=>We(t))]).filter(e=>e.length>0)),id=new Set(ct.map(e=>e.toLowerCase()));function bu(e,t){e.name.trim().length===0?t.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):e.name!==Se(e.name)&&t.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:e.name,message:`Profile name "${e.name}" is not in canonical form; resolution folds it to "${Se(e.name)}" (lowercase, hyphens as underscores).`}),e.title.trim().length===0&&t.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),e.summary.trim().length===0&&t.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function wu(e,t){let n=new Set,o=new Set;for(let[s,r]of e.types.entries()){let i;try{i=ue(r).name}catch(c){t.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof r.name=="string"?r.name:`#${s}`,message:ge(c)});continue}let a=i.toLowerCase();if(o.has(a)){t.push({severity:"error",code:"type_duplicate",dimension:"types",target:i,message:`Item type "${i}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}o.add(a),n.add(a)}return n}function vu(e,t){let n=new Set,o=new Set;for(let[s,r]of e.statuses.entries()){let i;try{i=$e(r)}catch(a){t.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof r.id=="string"?r.id:`#${s}`,message:ge(a)});continue}if(o.has(i.id)){t.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:i.id,message:`Status "${i.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}o.add(i.id),n.add(i.id);for(let a of i.aliases??[])n.add(We(a))}return n}function ku(e,t){let n=new Set;for(let[o,s]of e.fields.entries()){let r;try{r=Pe(s).key}catch(a){t.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof s.key=="string"?s.key:`#${o}`,message:ge(a)});continue}if(n.has(r)){t.push({severity:"error",code:"field_duplicate",dimension:"fields",target:r,message:`Field "${r}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}n.add(r);let i=Pi(r);i&&t.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:r,message:`Field "${r}" collides with canonical MCP property "${i.property}" owned by ${i.owner}; callers must pass the custom value through ${i.nested_path}.`})}}function Su(e,t,n,o){let s=new Set;for(let[r,i]of e.workflows.entries()){let a=i.type.trim().toLowerCase();if(a.length===0){o.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${r}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}let c=s.has(a);s.add(a),c?o.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:i.type,message:`Workflow type "${i.type}" is declared more than once; the later transition set wins.`}):!id.has(a)&&!t.has(a)&&o.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:i.type,message:`Workflow governs type "${i.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});let d=new Set;for(let l of i.allowed_transitions){let m=We(l[0]),f=We(l[1]);if(m.length===0||f.length===0){o.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:i.type,message:`Workflow "${i.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(let _ of[m,f])yu.has(_)||n.has(_)||d.has(_)||(d.add(_),o.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:_,message:`Workflow "${i.type}" references status "${_}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function Iu(e,t){let n=new Set;for(let o of e.config){let s=Xe(o.key);if(s===void 0){t.push({severity:"error",code:"config_key_unknown",dimension:"config",target:o.key,message:`Config knob "${o.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}n.has(s.key)?t.push({severity:"error",code:"config_duplicate",dimension:"config",target:s.key,message:`Config knob "${s.key}" is set more than once; the later value silently overwrites the earlier one.`}):n.add(s.key);let r=mn(s,o.value);r.ok||t.push({severity:"error",code:"config_value_invalid",dimension:"config",target:o.key,message:r.error.message})}}function Eu(e,t,n){for(let o of e.templates){let s=o.options.type;if(typeof s!="string"||s.trim().length===0)continue;let r=s.trim().toLowerCase();!id.has(r)&&!t.has(r)&&n.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:o.name,message:`Template "${o.name}" creates type "${s}" which is neither a built-in type nor declared by this profile.`})}}function xu(e,t){for(let[n,o]of e.packages.entries())o.spec.trim().length===0&&t.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${n}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function ad(e){let t=[];bu(e,t);let n=wu(e,t),o=vu(e,t);ku(e,t),Su(e,n,o,t),Iu(e,t),Eu(e,n,t),xu(e,t);let s=t.filter(i=>i.severity==="error").length,r=t.length-s;return{profile:e.name,ok:s===0,findings:t,errorCount:s,warningCount: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]="ead1caea-8e8b-5208-9fba-23fb114044b5")}catch{}})();function ms(e,t,n,o,s){let r=e,i=[];for(let a of t){let c=o(r),d=s(r,a),l=o(d.file);r=d.file;let m=c===l?"unchanged":d.replaced?"update":"add";i.push({key:n(a),status:m})}return{file:r,changes:i,changed:i.some(a=>a.status!=="unchanged")}}function cd(e){return JSON.stringify(e.map(t=>t.join("\0")).sort())}function Ru(e,t){let n=e.map(s=>({...s})),o=[];for(let s of t){let r=n.findIndex(a=>a.type===s.type),i={type:s.type,allowed_transitions:s.allowed_transitions};r<0?(n.push(i),o.push({type:s.type,status:"add"})):cd(n[r].allowed_transitions)===cd(s.allowed_transitions)?o.push({type:s.type,status:"unchanged"}):(n[r]=i,o.push({type:s.type,status:"update"}))}return{changes:o,result:n,changed:o.some(s=>s.status!=="unchanged")}}function Au(e,t){let n=[];for(let o of e.config){let s=Xe(o.key);if(s===void 0)throw new Error(`Profile "${e.name}" references unknown config key "${o.key}".`);let r=mn(s,o.value);if(!r.ok)throw new Error(`Profile "${e.name}" config ${o.key}: ${r.error.message}`);let i=$a(t,s),a=i===null?"add":i===r.parsed.value?"unchanged":"update";n.push({key:s.key,path:s.path,value:r.parsed.value,status:a})}return{changes:n,changed:n.some(o=>o.status!=="unchanged")}}function dd(e){let t=Object.entries(e).sort(([n],[o])=>n.localeCompare(o));return JSON.stringify(t)}function Cu(e,t){let n=[];for(let o of e.templates){let s=t.get(o.name),r;s===void 0?r="add":dd(s)===dd(o.options)?r="unchanged":r="update",n.push({name:o.name,options:o.options,status:r})}return{changes:n,changed:n.some(o=>o.status!=="unchanged")}}function ld(e,t){let n=ms(Cr(t.typesRaw),e.types,l=>ue(l).name,qt,(l,m)=>Tr(l,ue(m))),o=ms(Ki(t.statusesRaw),e.statuses,l=>$e(l).id,on,(l,m)=>Yi(l,$e(m))),s=ms(Ji(t.fieldsRaw),e.fields,l=>Pe(l).key,sn,(l,m)=>Xi(l,Pe(m))),r=Ru(t.workflows,e.workflows),i=Au(e,t.settings),a=Cu(e,t.templates),c=e.packages.map(l=>({spec:l.spec,reason:l.reason,status:t.installedPackages.has(l.spec)?"installed":"recommended"})),d=n.changed||o.changed||s.changed||r.changed||i.changed||a.changed;return{profile:{name:e.name,title:e.title,summary:e.summary},types:n,statuses:o,fields:s,workflows:r,config:i,templates:a,packages:c,changed:d}}import pd from"node:fs/promises";import ud from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f232e106-54f4-572e-8f6e-054f52290267")}catch{}})();var Tu="templates",ps=".json",fd=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ou=ni.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),$u=new Set(Ou),md="1970-01-01T00:00:00.000Z",_d={bug:{type:"Issue",priority:"1",tags:"bug",acceptanceCriteria:"Bug no longer reproduces with the steps below and a regression test guards it.",expectedResult:"Describe the correct behavior.",actualResult:"Describe the observed (buggy) behavior.",body:`## Repro steps
37
+ `}}],packages:[{spec:"search-advanced",reason:"Semantic retrieval over experiments and findings."},{spec:"templates",reason:"Consistent experiment and hypothesis scaffolds."},{spec:"beads",reason:"Import structured prior work into the tracker."}]}};function $u(e){if(e===void 0)return;let t=Ie(e);if(t.length===0)throw new Error("Profile name must not be empty.");if(ot.includes(t))return t;throw new Error(`Invalid profile "${e}". Allowed: ${ot.join(", ")}.`)}function fw(e){let t=$u(e);if(t===void 0)throw new Error(`Profile name is required. Allowed: ${ot.join(", ")}.`);return ls[t]}function _w(){return ot.map(e=>ls[e])}function Ie(e){return e.trim().toLowerCase().replaceAll("-","_")}function _d(e){return e.map(t=>t.definition.name).join(", ")}function ms(e=[]){let t=ot.map(r=>({definition:ls[r],source:"builtin"})),n=new Set(ot.map(r=>Ie(r))),o=new Set(n),s=[];for(let r of e){let i=Ie(r.profile.name);if(n.has(i)){s.push(`Extension "${r.name}" profile "${r.profile.name}" uses a name reserved by a built-in archetype and was ignored.`);continue}if(o.has(i)){s.push(`Profile "${r.profile.name}" from extension "${r.name}" duplicates an already-registered profile and was ignored.`);continue}o.add(i),t.push({definition:r.profile,source:"extension",package:r.name})}return{profiles:t,warnings:s}}function vn(e,t=[]){let{profiles:n,warnings:o}=ms(t);if(typeof e!="string"||e.trim().length===0)throw new Error(`Profile name is required. Allowed: ${_d(n)}.`);let s=Ie(e),r=n.find(i=>Ie(i.definition.name)===s);if(r===void 0)throw new Error(`Invalid profile "${e}". Allowed: ${_d(n)}.`);return{resolved:r,warnings: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]="933d8f74-c4aa-58d0-bd3b-8932a35d3702")}catch{}})();function us(e){return{types:e.types.length,statuses:e.statuses.length,fields:e.fields.length,workflows:e.workflows.length,config:e.config.length,templates:e.templates.length,packages:e.packages.length}}function hd(e){return{name:e.name,title:e.title,summary:e.summary,composition:us(e),types:e.types.map(t=>ps(()=>fe(t).name,()=>String(t.name??""))),statuses:e.statuses.map(t=>ps(()=>Pe(t).id,()=>String(t.id??""))),fields:e.fields.map(t=>ps(()=>Fe(t).key,()=>String(t.key??""))),workflows:e.workflows.map(t=>t.type),config:e.config.map(t=>`${t.key}=${t.value}`),templates:e.templates.map(t=>t.name),packages:e.packages.map(t=>({spec:t.spec,reason:t.reason}))}}function ps(e,t){try{return e()}catch{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]="f9b22df0-7ec2-5d72-bc88-3eb7201a6051")}catch{}})();var Ow=["profile","types","statuses","fields","workflows","config","templates","packages"],$w=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],Pu=new Set(cr.flatMap(e=>[He(e.id),...(e.aliases??[]).map(t=>He(t))]).filter(e=>e.length>0)),gd=new Set(lt.map(e=>e.toLowerCase()));function Fu(e,t){e.name.trim().length===0?t.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):e.name!==Ie(e.name)&&t.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:e.name,message:`Profile name "${e.name}" is not in canonical form; resolution folds it to "${Ie(e.name)}" (lowercase, hyphens as underscores).`}),e.title.trim().length===0&&t.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),e.summary.trim().length===0&&t.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function Lu(e,t){let n=new Set,o=new Set;for(let[s,r]of e.types.entries()){let i;try{i=fe(r).name}catch(c){t.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof r.name=="string"?r.name:`#${s}`,message:ye(c)});continue}let a=i.toLowerCase();if(o.has(a)){t.push({severity:"error",code:"type_duplicate",dimension:"types",target:i,message:`Item type "${i}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}o.add(a),n.add(a)}return n}function Nu(e,t){let n=new Set,o=new Set;for(let[s,r]of e.statuses.entries()){let i;try{i=Pe(r)}catch(a){t.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof r.id=="string"?r.id:`#${s}`,message:ye(a)});continue}if(o.has(i.id)){t.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:i.id,message:`Status "${i.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}o.add(i.id),n.add(i.id);for(let a of i.aliases??[])n.add(He(a))}return n}function Mu(e,t){let n=new Set;for(let[o,s]of e.fields.entries()){let r;try{r=Fe(s).key}catch(a){t.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof s.key=="string"?s.key:`#${o}`,message:ye(a)});continue}if(n.has(r)){t.push({severity:"error",code:"field_duplicate",dimension:"fields",target:r,message:`Field "${r}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}n.add(r);let i=Mi(r);i&&t.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:r,message:`Field "${r}" collides with canonical MCP property "${i.property}" owned by ${i.owner}; callers must pass the custom value through ${i.nested_path}.`})}}function Du(e,t,n,o){let s=new Set;for(let[r,i]of e.workflows.entries()){let a=i.type.trim().toLowerCase();if(a.length===0){o.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${r}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}let c=s.has(a);s.add(a),c?o.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:i.type,message:`Workflow type "${i.type}" is declared more than once; the later transition set wins.`}):!gd.has(a)&&!t.has(a)&&o.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:i.type,message:`Workflow governs type "${i.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});let d=new Set;for(let l of i.allowed_transitions){let m=He(l[0]),f=He(l[1]);if(m.length===0||f.length===0){o.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:i.type,message:`Workflow "${i.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(let _ of[m,f])Pu.has(_)||n.has(_)||d.has(_)||(d.add(_),o.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:_,message:`Workflow "${i.type}" references status "${_}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function ju(e,t){let n=new Set;for(let o of e.config){let s=Qe(o.key);if(s===void 0){t.push({severity:"error",code:"config_key_unknown",dimension:"config",target:o.key,message:`Config knob "${o.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}n.has(s.key)?t.push({severity:"error",code:"config_duplicate",dimension:"config",target:s.key,message:`Config knob "${s.key}" is set more than once; the later value silently overwrites the earlier one.`}):n.add(s.key);let r=mn(s,o.value);r.ok||t.push({severity:"error",code:"config_value_invalid",dimension:"config",target:o.key,message:r.error.message})}}function Uu(e,t,n){for(let o of e.templates){let s=o.options.type;if(typeof s!="string"||s.trim().length===0)continue;let r=s.trim().toLowerCase();!gd.has(r)&&!t.has(r)&&n.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:o.name,message:`Template "${o.name}" creates type "${s}" which is neither a built-in type nor declared by this profile.`})}}function Gu(e,t){for(let[n,o]of e.packages.entries())o.spec.trim().length===0&&t.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${n}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function yd(e){let t=[];Fu(e,t);let n=Lu(e,t),o=Nu(e,t);Mu(e,t),Du(e,n,o,t),ju(e,t),Uu(e,n,t),Gu(e,t);let s=t.filter(i=>i.severity==="error").length,r=t.length-s;return{profile:e.name,ok:s===0,findings:t,errorCount:s,warningCount: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]="ead1caea-8e8b-5208-9fba-23fb114044b5")}catch{}})();function fs(e,t,n,o,s){let r=e,i=[];for(let a of t){let c=o(r),d=s(r,a),l=o(d.file);r=d.file;let m=c===l?"unchanged":d.replaced?"update":"add";i.push({key:n(a),status:m})}return{file:r,changes:i,changed:i.some(a=>a.status!=="unchanged")}}function bd(e){return JSON.stringify(e.map(t=>t.join("\0")).sort())}function qu(e,t){let n=e.map(s=>({...s})),o=[];for(let s of t){let r=n.findIndex(a=>a.type===s.type),i={type:s.type,allowed_transitions:s.allowed_transitions};r<0?(n.push(i),o.push({type:s.type,status:"add"})):bd(n[r].allowed_transitions)===bd(s.allowed_transitions)?o.push({type:s.type,status:"unchanged"}):(n[r]=i,o.push({type:s.type,status:"update"}))}return{changes:o,result:n,changed:o.some(s=>s.status!=="unchanged")}}function zu(e,t){let n=[];for(let o of e.config){let s=Qe(o.key);if(s===void 0)throw new Error(`Profile "${e.name}" references unknown config key "${o.key}".`);let r=mn(s,o.value);if(!r.ok)throw new Error(`Profile "${e.name}" config ${o.key}: ${r.error.message}`);let i=Ha(t,s),a=i===null?"add":i===r.parsed.value?"unchanged":"update";n.push({key:s.key,path:s.path,value:r.parsed.value,status:a})}return{changes:n,changed:n.some(o=>o.status!=="unchanged")}}function wd(e){let t=Object.entries(e).sort(([n],[o])=>n.localeCompare(o));return JSON.stringify(t)}function Hu(e,t){let n=[];for(let o of e.templates){let s=t.get(o.name),r;s===void 0?r="add":wd(s)===wd(o.options)?r="unchanged":r="update",n.push({name:o.name,options:o.options,status:r})}return{changes:n,changed:n.some(o=>o.status!=="unchanged")}}function vd(e,t){let n=fs(Nr(t.typesRaw),e.types,l=>fe(l).name,zt,(l,m)=>Mr(l,fe(m))),o=fs(oa(t.statusesRaw),e.statuses,l=>Pe(l).id,nn,(l,m)=>sa(l,Pe(m))),s=fs(ra(t.fieldsRaw),e.fields,l=>Fe(l).key,on,(l,m)=>ia(l,Fe(m))),r=qu(t.workflows,e.workflows),i=zu(e,t.settings),a=Hu(e,t.templates),c=e.packages.map(l=>({spec:l.spec,reason:l.reason,status:t.installedPackages.has(l.spec)?"installed":"recommended"})),d=n.changed||o.changed||s.changed||r.changed||i.changed||a.changed;return{profile:{name:e.name,title:e.title,summary:e.summary},types:n,statuses:o,fields:s,workflows:r,config:i,templates:a,packages:c,changed:d}}import Sd from"node:fs/promises";import Id from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f232e106-54f4-572e-8f6e-054f52290267")}catch{}})();var Bu="templates",_s=".json",Ed=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Vu=ii.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),Wu=new Set(Vu),kd="1970-01-01T00:00:00.000Z",xd={bug:{type:"Issue",priority:"1",tags:"bug",acceptanceCriteria:"Bug no longer reproduces with the steps below and a regression test guards it.",expectedResult:"Describe the correct behavior.",actualResult:"Describe the observed (buggy) behavior.",body:`## Repro steps
38
38
  1.
39
39
  2.
40
40
  3.
@@ -58,26 +58,26 @@ import{a as ua,b as Xe,c as mn,d as $a,e as Pa,f as Fa}from"./chunk-5JO6R4BS.js"
58
58
  `},chore:{type:"Chore",priority:"3",tags:"chore",acceptanceCriteria:"Maintenance task done with no behavior change and green checks.",body:`## What
59
59
 
60
60
  ## Why
61
- `}},xw={normalizeTemplateName:vn,extractTemplateOptions:hd,parseStoredTemplateDocument:hs,builtinTemplateDocument:gd,readStoredTemplateDocument:bd};function vn(e){let t=e.trim();if(!fd.test(t))throw new p(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,u.USAGE);return t}function us(e){return ud.join(e,Tu)}function kn(e,t){return ud.join(us(e),`${t}${ps}`)}async function fs(e){if(!await E(A(e)))throw new p(`Tracker is not initialized at ${e}. Run pm init first.`,u.NOT_FOUND)}function _s(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function hd(e){let t={};for(let[n,o]of Object.entries(e))if(o!==void 0){if($u.has(n)){if(typeof o=="string"){t[n]=[o];continue}if(!Array.isArray(o))continue;let s=o.filter(r=>typeof r=="string");s.length>0&&(t[n]=s);continue}if(typeof o=="string"){t[n]=o;continue}Array.isArray(o)&&o.every(s=>typeof s=="string")&&(t[n]=[...o])}return _s(t)}function Pu(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(`Template "${t}" has invalid options payload.`,u.GENERIC_FAILURE);let n=e,o={};for(let[s,r]of Object.entries(n)){let i=s.trim();if(i.length===0)throw new p(`Template "${t}" contains an empty option key.`,u.GENERIC_FAILURE);if(typeof r=="string"){o[i]=r;continue}if(Array.isArray(r)&&r.every(a=>typeof a=="string")){o[i]=[...r];continue}throw new p(`Template "${t}" contains invalid value for option "${i}".`,u.GENERIC_FAILURE)}return _s(o)}function hs(e,t){let n;try{n=JSON.parse(e)}catch{throw new p(`Template "${t}" contains invalid JSON.`,u.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Template "${t}" has invalid document shape.`,u.GENERIC_FAILURE);let o=n,s=Pu(o.options,t),r=S();return{name:typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():t,created_at:typeof o.created_at=="string"?o.created_at:r,updated_at:typeof o.updated_at=="string"?o.updated_at:r,options:s}}function gd(e){let t=_d[e];return t?{name:e,created_at:md,updated_at:md,options:_s({...t})}:null}async function yd(e,t){let n=await G(kn(e,t));if(n!==null)return{document:hs(n,t),source:"user"};let o=gd(t);if(o)return{document:o,source:"builtin"};throw new p(`Template "${t}" not found`,u.NOT_FOUND)}async function bd(e,t){let n=await G(kn(e,t));if(n===null)throw new p(`Template "${t}" not found`,u.NOT_FOUND);return hs(n,t)}async function Fu(e,t){let n=vn(t),{document:o}=await yd(e,n);return o.options}async function gs(e,t,n){let o=x(process.cwd(),n.path);await fs(o);let s=vn(e),r=hd(t);if(Object.keys(r).length===0)throw new p("templates save requires at least one create option flag",u.USAGE);let i=S(),a=kn(o,s),c=i;await E(a)&&(c=(await bd(o,s)).created_at);let d={name:s,created_at:c,updated_at:i,options:r},l=await R(o);return await pd.mkdir(us(o),{recursive:!0}),await Ve({pmRoot:o,filePath:a,raw:`${JSON.stringify(d,null,2)}
62
- `,op:"templates:save",author:O(void 0,l.author_default),lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms}),{name:d.name,created_at:d.created_at,updated_at:d.updated_at,path:a,options:d.options}}async function Lu(e){let t=us(e);return await E(t)?(await pd.readdir(t)).filter(o=>o.toLowerCase().endsWith(ps)).map(o=>o.slice(0,-ps.length)).filter(o=>fd.test(o)):[]}async function Nu(e){let t=x(process.cwd(),e.path);await fs(t);let n=await Lu(t),o=new Set(n),s=Object.keys(_d).filter(c=>!o.has(c)),r=[...n].sort((c,d)=>c.localeCompare(d)),i=[...s].sort((c,d)=>c.localeCompare(d)),a=[...new Set([...r,...i])].sort((c,d)=>c.localeCompare(d));return{templates:a,count:a.length,builtin_templates:i,user_templates:r}}async function Mu(e,t){let n=x(process.cwd(),t.path);await fs(n);let o=vn(e),{document:s,source:r}=await yd(n,o);return{name:s.name,source:r,created_at:s.created_at,updated_at:s.updated_at,path:r==="builtin"?`builtin:${o}`:kn(n,o),options:s.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1e34cfb-3d4e-5b79-8585-3162e71e574c")}catch{}})();var Jw=["list","show","apply","lint"],ju="schema-types",Uu="schema-statuses",Gu="schema-fields";function Sn(){let e=T();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Sd(){let{profiles:e,warnings:t}=cs(Sn());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:ls(n.definition)})),warnings:t,generated_at:S()}}function Id(e){let t;try{t=wn(e,Sn())}catch(o){throw new p(o instanceof Error?o.message:String(o),u.USAGE)}let{resolved:n}=t;return{action:"show",...rd(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:S()}}function Ed(e){let t;try{t=wn(e,Sn())}catch(s){throw new p(s instanceof Error?s.message:String(s),u.USAGE)}let{resolved:n}=t,o=ad(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:o.ok,error_count:o.errorCount,warning_count:o.warningCount,findings:o.findings,warnings:t.warnings,generated_at:S()}}function qu(e,t){return Du.join(e,"templates",`${t}.json`)}async function zu(e,t){let n=await G(qu(e,t));if(n!==null)try{let o=JSON.parse(n);if(o!==null&&typeof o=="object"&&!Array.isArray(o)){let s=o.options;if(s!==null&&typeof s=="object"&&!Array.isArray(s))return s}}catch{}}async function wd(e,t,n,o){let s=new Map;for(let r of o.templates){let i=await zu(e,r.name);i!==void 0&&s.set(r.name,i)}return{typesRaw:await G(xe(e,t.files.types,Ee.types)),statusesRaw:await G(xe(e,t.files.statuses,Ee.statuses)),fieldsRaw:await G(xe(e,t.files.fields,Ee.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:s,installedPackages:new Set}}function nt(e){let t=[],n=[],o=[];for(let s of e)(s.status==="add"?t:s.status==="update"?n:o).push(s.key);return{added:t,updated:n,unchanged:o}}function vd(e,t,n,o,s){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:o,changed:t.changed,types:nt(t.types.changes),statuses:nt(t.statuses.changes),fields:nt(t.fields.changes),workflows:nt(t.workflows.changes.map(r=>({key:r.type,status:r.status}))),config:nt(t.config.changes),templates:nt(t.templates.changes.map(r=>({key:r.name,status:r.status}))),packages:t.packages,warnings:[...new Set(s)].sort((r,i)=>r.localeCompare(i)),generated_at:S()}}async function Hu(e){if(!await E(A(e)))throw new p(`Tracker is not initialized at ${e}. Run pm init first.`,u.NOT_FOUND)}function Bu(e){try{let t=wn(e,Sn());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new p(t instanceof Error?t.message:String(t),u.USAGE)}}async function xd(e,t,n){let o=x(process.cwd(),n.path);await Hu(o);let s=Bu(e),r=s.profile,i=s.warnings,a=t.dryRun===!0,c=await R(o),d=rr(c.schema);if(a){let h=await wd(o,d,c,r),k=kd(r,h);return vd(r,k,!1,!0,[...i])}let l=O(t.author,c.author_default),m=$r(c),f=!!t.force,_=[...i],y=[],w=async h=>{y.push(await Y(o,h,c.locks.ttl_seconds,l,f,m.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await w(ju),await w(Uu),await w(Gu);let h=await wd(o,d,c,r);if(g=kd(r,h),g.types.changed){let k=xe(o,d.files.types,Ee.types);await Ve({pmRoot:o,filePath:k,raw:qt(g.types.file),op:"profile:apply-types",author:l,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let I=new Set(r.types.map(C=>ue(C).name)),P=g.types.file.definitions.filter(C=>I.has(C.name));await ta(o,P,_,"profile:apply-type-folder"),_.push(...await N({path:k,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let k=xe(o,d.files.statuses,Ee.statuses);await Ve({pmRoot:o,filePath:k,raw:on(g.statuses.file),op:"profile:apply-statuses",author:l,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await N({path:k,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let k=xe(o,d.files.fields,Ee.fields);await Ve({pmRoot:o,filePath:k,raw:sn(g.fields.file),op:"profile:apply-fields",author:l,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await N({path:k,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let k of g.config.changes){if(k.status==="unchanged")continue;let I=Xe(k.key);I!==void 0&&Pa(c,I,k.value)}c.schema.type_workflows=g.workflows.result,await Pr(o,c,"profile:apply-config")}for(let k of g.templates.changes)k.status!=="unchanged"&&await gs(k.name,{...k.options},n)}finally{for(let h of y.reverse())try{await h()}catch{}}return vd(r,g,g.changed,!1,_)}function kd(e,t){try{return ld(e,t)}catch(n){throw new p(n instanceof Error?n.message:String(n),u.USAGE)}}function Vu(e,t){let n=[];if(t.added.length>0&&n.push(`+${t.added.join(", ")}`),t.updated.length>0&&n.push(`~${t.updated.join(", ")}`),n.length!==0)return` ${e}: ${n.join(" ")}`}function Xw(e){let t=["Project profiles:"];for(let n of e.profiles){let o=n.source==="extension"?` [${n.package??"extension"}]`:"";t.push(` ${n.name} \u2014 ${n.title}: ${n.summary}${o}`)}for(let n of e.warnings)t.push(` warning: ${n}`);return t.join(`
63
- `)}function Zw(e){let t=e.source==="extension"?` [${e.package??"extension"}]`:"",n=[`${e.name} \u2014 ${e.title}${t}`,e.summary,""];n.push(`types: ${e.types.join(", ")||"(none)"}`),n.push(`statuses: ${e.statuses.join(", ")||"(none)"}`),n.push(`fields: ${e.fields.join(", ")||"(none)"}`),n.push(`workflows: ${e.workflows.join(", ")||"(none)"}`),n.push(`config: ${e.config.join(", ")||"(none)"}`),n.push(`templates: ${e.templates.join(", ")||"(none)"}`),n.push(`packages: ${e.packages.map(o=>o.spec).join(", ")||"(none)"}`);for(let o of e.warnings)n.push(`warning: ${o}`);return n.join(`
64
- `)}function Qw(e){let t=e.source==="extension"?` [${e.package??"extension"}]`:"",n=e.warning_count+e.warnings.length,s=[e.ok?`Profile ${e.name}${t}: ok (${n} warning${n===1?"":"s"})`:`Profile ${e.name}${t}: ${e.error_count} error${e.error_count===1?"":"s"}, ${n} warning${n===1?"":"s"}`];for(let r of e.findings){let i=r.target!==void 0?` (${r.target})`:"";s.push(` ${r.severity} [${r.code}] ${r.dimension}${i}: ${r.message}`)}for(let r of e.warnings)s.push(` warning: ${r}`);return s.join(`
65
- `)}function ev(e){let t=e.dry_run?"dry-run":e.applied?"applied":"no changes",n=[`Profile ${e.name} (${t})`];if(!e.changed)n.push(" already up to date");else for(let[s,r]of[["types",e.types],["statuses",e.statuses],["fields",e.fields],["workflows",e.workflows],["config",e.config],["templates",e.templates]]){let i=Vu(s,r);i!==void 0&&n.push(i)}let o=e.packages.filter(s=>s.status==="recommended");o.length>0&&n.push(` recommended packages: ${o.map(s=>s.spec).join(", ")}`);for(let s of e.warnings)n.push(` warning: ${s}`);return n.join(`
66
- `)}import Ad from"node:fs/promises";import Cd from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7e0f84f6-9528-55c5-8976-6f85cd920486")}catch{}})();function Wu(e,t,n){let o=new Set,s=[];for(let r of e){let i=r.trim();if(i.length===0||o.has(i))continue;o.add(i);let a=t.get(i);if(a===void 0){s.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){s.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}s.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return s}function Ku(e,t){let n=[...e].sort((s,r)=>r.entries-s.entries||s.id.localeCompare(r.id)),o=[];for(let s of n){if(t.scope==="closed"&&s.bucket!=="closed"){o.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(s.entries<=t.minEntries){o.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&s.entries<=t.allOver){o.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"below_threshold"});continue}o.push({id:s.id,entries:s.entries,selected:!0,skip_reason:null})}return o}function Rd(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(o=>[o.id,o]));return Wu(t.ids,n,t.minEntries)}return Ku(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6609492-75a9-5111-b9b3-1b81908f3084")}catch{}})();function Yu(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new p("history-compact --before requires a non-empty value.",u.USAGE);if(/^\d+$/.test(n)){let r=Number.parseInt(n,10);if(!Number.isSafeInteger(r)||r<1||r>t.length+1)throw new p(`history-compact --before version must be between 1 and ${t.length+1}.`,u.USAGE);let i=Math.max(0,Math.min(t.length,r-1));return{kind:"version",raw:n,compactCount:i,retainedCount:t.length-i}}let o=Date.parse(n);if(!Number.isFinite(o))throw new p(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,u.USAGE);let s=0;for(let[r,i]of t.entries()){let a=Date.parse(i.ts);if(!Number.isFinite(a))throw new p(`History for this item contains invalid timestamp at entry ${r+1}.`,u.GENERIC_FAILURE);if(a>=o)break;s+=1}return{kind:"timestamp",raw:n,compactCount:s,retainedCount:t.length-s}}function Ju(e,t){let n=Dt(),o=Dt();for(let s=0;s<e.length;s+=1){let r=e[s];if(ee(n)!==r.before_hash)throw new p(`history-compact detected before-hash drift at entry ${s+1}; run pm history-repair first.`,u.CONFLICT);if(n=Jt(n,r.patch,s+1,r.op),ee(n)!==r.after_hash)throw new p(`history-compact detected after-hash drift at entry ${s+1}; run pm history-repair first.`,u.CONFLICT);s+1===t&&(o=structuredClone(n))}return{checkpoint:o,finalReplay:n}}function Xu(e,t,n){let o=structuredClone(t),s=[];for(let[r,i]of e.entries()){let a=ee(o);o=Jt(o,i.patch,n+r+1,i.op),s.push({...i,before_hash:a,after_hash:ee(o)})}return{entries:s,finalReplay:o}}async function Zu(e,t,n){let o=e.located?await H(e.located,{schema:t.schema}):null;return o?{loadedItem:o,currentItemRawBeforeLock:o.raw,matchedChainBefore:ee(Te(o.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function Qu(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function ef(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function tf(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=Ju(e.historyEntries,e.boundary.compactCount),o=e.historyEntries.slice(e.boundary.compactCount),s=Xu(o,t,e.boundary.compactCount),i=[re({nowIso:S(),author:e.author,op:"history_compact_baseline",before:Ce(Dt()),after:Ce(t),message:ef(e.boundary)}),...s.entries];return e.dryRun||i.push(re({nowIso:S(),author:e.author,op:"history_compact",before:Ce(n),after:Ce(n),message:Qu(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function nf(e){return Zt({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-compact",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Xt({historyPath:e.historyPath,nextHistoryRaw:pe(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>N({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function ys(e,t,n){let o=x(process.cwd(),n.path);if(!await E(A(o)))throw new p(`Tracker is not initialized at ${o}. Run pm init first.`,u.NOT_FOUND);let s=await R(o),r=F(s,T()),i=await Qt(o,e,s,r.type_to_folder),a=i.historyPath,c=await G(a);if(c===null)throw new p(`No history stream exists for ${i.id}.`,u.NOT_FOUND);let d=await ze(a,i.id);if(d.length===0)throw new p(`No history entries exist for ${i.id}; nothing to compact.`,u.USAGE);let l=Be(d);if(!l.ok)throw new p(`history-compact requires a valid history chain (${l.errors.join(", ")}). Run pm history-repair ${i.id} first.`,u.CONFLICT);let m=Yu(t.before,d),f=m.compactCount>0,_=!!t.dryRun,y=O(t.author,s.author_default),w=[];f||w.push("history_compact_noop_before_boundary");let g=await Zu(i,s,d);g.matchedChainBefore===!1&&w.push("history_compact_item_chain_mismatch");let{rewrittenEntries:h,baselineEntryAdded:k,auditEntryAdded:I}=tf({historyEntries:d,boundary:m,changed:f,dryRun:_,author:y,options:t}),P=Be(h);if(!P.ok)throw new p(`history-compact produced an invalid rewritten chain (${P.errors.join(", ")}).`,u.GENERIC_FAILURE);f&&!_&&w.push(...await nf({pmRoot:o,subject:i,settings:s,typeRegistry:r,historyRawBeforeLock:c,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:y,force:t.force,loadedItem:g.loadedItem,historyPath:a,rewrittenEntries:h}));let C=m.retainedCount>0?m.compactCount+1:null;return{id:i.id,dry_run:_,changed:f,compact_boundary:{kind:m.kind,before:m.raw,entries_compacted:m.compactCount,entries_retained:m.retainedCount,first_retained_entry:C},history:{path:a,entries_scanned:d.length,entries_after:h.length,baseline_entry_added:k,audit_entry_added:I,verify_ok:P.ok,verify_errors:P.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:g.matchedChainBefore},warnings:[...new Set(w)].sort((j,U)=>j.localeCompare(U)),generated_at:S()}}var of=3;function Td(e,t){let n=t.ids!==void 0&&t.ids.length>0,o=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(o?1:0)===0)throw new p("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",u.USAGE);if(e!==void 0&&(n||o))throw new p("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",u.USAGE);if(n&&o)throw new p("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",u.USAGE)}function sf(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function rf(e){let t=q(e.settings.schema),n=Gi(t),o=await Bt(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),s=new Map(o.map(d=>[d.id,n.classify(d.status)])),r=Cd.join(e.pmRoot,"history"),i=[],a=[];if(!await E(r))return{candidates:i,preselectionErrors:a};let c=(await Ad.readdir(r)).filter(d=>d.endsWith(".jsonl")).sort((d,l)=>d.localeCompare(l));for(let d of c){let l=Cd.join(r,d),m=d.slice(0,-6);try{let f=await Ad.readFile(l,"utf8");await Wn({path:l,scope:"project"}),i.push({id:m,entries:sf(f),bucket:s.get(m)??null})}catch(f){a.push({id:m,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:a}}async function af(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await ys(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function Od(e,t){let n=x(process.cwd(),t.path);if(!await E(A(n)))throw new p(`Tracker is not initialized at ${n}. Run pm init first.`,u.NOT_FOUND);let o=await R(n),s=F(o,T()),{candidates:r,preselectionErrors:i}=await rf({pmRoot:n,settings:o,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??of,d=o.history.compact_policy,l=a==="scan"&&e.allOver===void 0&&d.enabled,m=e.allOver??(l?d.max_entries:void 0),f=Rd(r,{ids:e.ids,scope:e.scope,minEntries:c,allOver:m}),_=!!e.dryRun,y=[...i],w={streams_considered:r.length+i.length,selected:0,items_compacted:0,items_skipped:0,items_errored:i.length};for(let g of f){let h=await af({row:g,options:e,dryRun:_,global:t});if(y.push(h.result),!h.selected){w.items_skipped+=1;continue}w.selected+=1,h.compacted&&(w.items_compacted+=1),h.errored&&(w.items_errored+=1)}return{bulk:!0,dry_run:_,mode:a,scope:e.scope??null,criteria:{min_entries:c,all_over:m??null,policy_threshold_applied:l},totals:w,results:y,generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f762b5e6-8224-531f-9dd1-f71dc18c3ddf")}catch{}})();function $d(e){let t=e.options.all===!0,n=e.id??b(e.options,"id");return Zc(n,t),t?yn(e.options,e.global):It(n,e.options,e.global)}function Pd(e){let t=e.options.ids,n=Array.isArray(t)?t.map(String).filter(d=>d.trim().length>0):typeof t=="string"?t.split(",").map(d=>d.trim()).filter(Boolean):void 0,o=B(e.options.allOver??e.options.all_over,"history-compact allOver"),s=B(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),r=b(e.options,"scope"),i=[];e.options.closed===!0&&i.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&i.push("all-streams"),(r==="closed"||r==="all-streams")&&i.push(r);let a=[...new Set(i)];if(a.length>1)throw new p("history-compact: closed and all-streams scopes are mutually exclusive.",u.USAGE);let c=a[0];return Td(e.id,{ids:n,allOver:o,scope:c}),e.id!==void 0?ys(e.id,{before:b(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global):Od({ids:n,scope:c,allOver:o,minEntries:s,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dbabff08-1bb7-539b-b1c1-c10584aa0a67")}catch{}})();function Fd(e){return{storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:b(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:W(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:b(e,"measurementSource"),measurementItem:b(e,"measurementItem"),measurementRevision:b(e,"measurementRevision"),author:b(e,"author"),message:b(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:b(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2643d11d-befc-5a87-8bec-760951eec4d0")}catch{}})();var cf=new Set(["true","1","yes","on"]),df=new Set(["false","0","no","off"]);function lf(e,t,n=[]){let o=[t,...n];for(let s of o){let r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}function mf(e,t,n=[]){let o=[t,...n];for(let s of o){let r=e[s];if(r!==void 0){if(typeof r=="boolean")return r;if(typeof r=="string"){let i=r.trim().toLowerCase();if(cf.has(i))return!0;if(df.has(i))return!1}}}}function pf(e,t,n=[]){for(let o of[t,...n]){let s=e[o],i=(typeof s=="string"?s.split(","):Array.isArray(s)?s.flatMap(a=>typeof a=="string"?a.split(","):[]):[]).map(a=>a.trim()).filter(a=>a.length>0);if(i.length>0)return i}return[]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2567f6a-cd1c-56b5-a93d-41e92ed574bf")}catch{}})();function z(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function uf(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);if(Number.isFinite(t)&&t>=0)return t}}function ff(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=4)return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);if(Number.isInteger(t)&&t>=0&&t<=4)return t}return 2}function _f(e){if(Array.isArray(e)){let t=e.filter(n=>typeof n=="string").map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);return Array.from(new Set(t)).sort((n,o)=>n.localeCompare(o))}return typeof e=="string"?ft(e):[]}function hf(e){let t=z(e);if(t){let n=pt(t);if(n)return n}return"open"}function ws(e){if(typeof e=="number"&&Number.isInteger(e))return e;if(typeof e!="string"||e.trim().length===0)return;let t=Number(e);return Number.isInteger(t)?t:void 0}function Ld(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e===1?!0:e===0?!1:void 0;if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:void 0}function ot(e){if(!Array.isArray(e))return;let t=e.map(n=>z(n)).filter(n=>n!==void 0);return t.length>0?t:void 0}function bs(e){return Dd(e,z)}function Nd(e){return Dd(e,Ud)}function gf(e,t){if(typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=100)return e;let n=z(e)?.toLowerCase();if(!n)return;let o=n==="med"?"medium":n;if(t.some(r=>r===o))return o;let s=Number(o);return Number.isInteger(s)&&s>=0&&s<=100?s:void 0}function Md(e,t){let n=z(e)?.toLowerCase();if(!n)return;let o=n==="med"?"medium":n;return t.includes(o)?o:void 0}function vs(e){return z(e)?.toLowerCase()==="global"?"global":"project"}function yf(e,t){let n=ks(e,t.allowScalar===!0);if(!n)return;let o=n.map(s=>Sf(s,t)).filter(s=>s!==void 0);return o.length>0?o:void 0}function bf(e,t={}){return jd(e,t,(n,o)=>({path:n,scope:vs(o?.scope),note:z(o?.note)}))}function wf(e,t={}){return jd(e,t,(n,o)=>({path:n,scope:vs(o?.scope),note:z(o?.note)}))}function vf(e,t={}){let n=ks(e,t.allowScalar===!0);if(!n)return;let o=n.map(s=>xf(s,t)).filter(s=>s!==void 0);return o.length>0?o:void 0}function kf(e,t){return O(e,t)}function En(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ks(e,t){return Array.isArray(e)?e:t?[e]:void 0}function In(e,t){for(let n of t){let o=z(e[n]);if(o)return o}}function Dd(e,t){if(!En(e))return;let n=Object.entries(e).map(([o,s])=>[o.trim(),t(s)]).filter(o=>o[0].length>0&&o[1]!==void 0);return n.length>0?Object.fromEntries(n):void 0}function Sf(e,t){if(typeof e=="string")return If(e,t);if(!En(e))return;let n=In(e,t.textKeys??["text"]);if(!n)return;let o=t.createdAtKey??"created_at",s=t.authorKey??"author";return{created_at:(t.toIsoString?t.toIsoString(e[o]):z(e[o]))??t.fallbackCreatedAt,author:z(e[s])??t.fallbackAuthor,text:n}}function If(e,t){let n=z(e);return n?{created_at:t.fallbackCreatedAt,author:t.fallbackAuthor,text:n}:void 0}function jd(e,t,n){let o=ks(e,t.allowScalar===!0);if(!o)return;let s=t.pathKeys??["path"],r=o.map(i=>Ef(i,s,n)).filter(i=>i!==void 0);return r.length>0?r:void 0}function Ef(e,t,n){if(typeof e=="string"){let s=z(e);return s?n(s):void 0}if(!En(e))return;let o=In(e,t);return o?n(o,e):void 0}function xf(e,t){if(typeof e=="string"){let s=z(e);return s?{command:s,scope:"project"}:void 0}if(!En(e))return;let n=In(e,t.commandKeys??["command"]),o=In(e,t.pathKeys??["path"]);if(!(!n&&(t.requireCommand===!0||!o)))return{...n?{command:n}:{},...o?{path:o}:{},scope:vs(e.scope),timeout_seconds:Rf(e.timeout_seconds,t),note:z(e.note),...t.includeExtendedAssertions===!0?Af(e):{}}}function Rf(e,t){let n=t.integerTimeout===!0?ws(e):Ud(e);if(n===void 0)return;let o=t.timeoutMinimum??0;return t.timeoutExclusiveMinimum===!0?n>o?n:void 0:n>=o?n:void 0}function Ud(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string"||e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Af(e){return{pm_context_mode:Md(e.pm_context_mode,["schema","tracker","auto"]),env_set:bs(e.env_set),env_clear:ot(e.env_clear),shared_host_safe:Ld(e.shared_host_safe),assert_stdout_contains:ot(e.assert_stdout_contains),assert_stdout_regex:ot(e.assert_stdout_regex),assert_stderr_contains:ot(e.assert_stderr_contains),assert_stderr_regex:ot(e.assert_stderr_regex),assert_stdout_min_lines:ws(e.assert_stdout_min_lines),assert_json_field_equals:bs(e.assert_json_field_equals),assert_json_field_gte:Nd(e.assert_json_field_gte)}}async function Cf(e){if(!await E(A(e)))throw new p(`Tracker is not initialized at ${e}. Run pm init first.`,u.NOT_FOUND)}function Gd(){return{metadata:{},body:""}}async function Tf(e){let{pmRoot:t,id:n,itemPath:o,document:s,author:r,message:i,settings:a,conflictWarningPrefix:c}=e,d=se(t,n),l=Gd();try{let m=await Y(t,n,a.locks.ttl_seconds,r,!1,a.governance.force_required_for_stale_lock,a.locks.wait_ms);try{await V(o,le(s,{format:"toon"}));try{let f=re({nowIso:S(),author:r,op:"import",before:l,after:s,message:i});return await Ae(d,f),{committed:!0,writeWarnings:[...await N({path:o,scope:"project",op:"import",item_id:s.metadata.id,item_type:s.metadata.type,before:l,after:s,changed_fields:["imported"]}),...await N({path:d,scope:"project",op:"import:history",item_id:s.metadata.id,item_type:s.metadata.type,before:l,after:s,changed_fields:["imported"]})]}}catch(f){throw await at(o),f}}finally{await m()}}catch(m){if(m instanceof p&&m.exitCode===u.CONFLICT)return{committed:!1,conflictWarning:`${c}:${n}`};throw m}}import{readFile as $f}from"node:fs/promises";import Pf 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]="3911e4fb-a9b3-5732-8b45-c484a121dffb")}catch{}})();function Of(e){return e.trim().toLowerCase().replaceAll("_","-")}var Is=[{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm init","pm context --limit 10","pm list-open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list-open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm install <target> --project","pm upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]}],Ss=new Map;for(let e of Is){Ss.set(e.id,e);for(let t of e.aliases)Ss.set(t,e)}function qd(){return Is.map(e=>({...e,aliases:[...e.aliases],commands:[...e.commands],workflows:e.workflows.map(t=>({...t,commands:[...t.commands]})),docs:e.docs.map(t=>({...t})),related:[...e.related]}))}function xn(){return Is.map(e=>e.id)}function zd(e){if(!e)return null;let t=Of(e);return t?Ss.get(t)??null: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]="9376fbdf-c942-5fa6-9252-92125ae44e73")}catch{}})();var Ff=["markdown","toon","json"],Lf=["brief","standard","deep"];function Nf(e){if(!e)return;let t=e.trim().toLowerCase();if(!Ff.includes(t))throw new p("Guide format must be one of markdown|toon|json",u.USAGE);return t}function Mf(e,t){let n=Nf(e.format);if(t.json&&n&&n!=="json")throw new p("Cannot combine --json with --format markdown|toon",u.USAGE);return t.json?"json":n??"toon"}function Df(e){if(!e)return"brief";let t=e.trim().toLowerCase();if(!Lf.includes(t))throw new p("Guide depth must be one of brief|standard|deep",u.USAGE);return t}function jf(){return qs(process.env,"PM_CLI_PACKAGE_ROOT",import.meta.url,["..","..",".."])}function Hd(e){return e.replaceAll(`\r
61
+ `}},Jw={normalizeTemplateName:kn,extractTemplateOptions:Rd,parseStoredTemplateDocument:bs,builtinTemplateDocument:Ad,readStoredTemplateDocument:Td};function kn(e){let t=e.trim();if(!Ed.test(t))throw new p(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,u.USAGE);return t}function hs(e){return Id.join(e,Bu)}function Sn(e,t){return Id.join(hs(e),`${t}${_s}`)}async function gs(e){if(!await x(A(e)))throw new p(`Tracker is not initialized at ${e}. Run pm init first.`,u.NOT_FOUND)}function ys(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function Rd(e){let t={};for(let[n,o]of Object.entries(e))if(o!==void 0){if(Wu.has(n)){if(typeof o=="string"){t[n]=[o];continue}if(!Array.isArray(o))continue;let s=o.filter(r=>typeof r=="string");s.length>0&&(t[n]=s);continue}if(typeof o=="string"){t[n]=o;continue}Array.isArray(o)&&o.every(s=>typeof s=="string")&&(t[n]=[...o])}return ys(t)}function Ku(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(`Template "${t}" has invalid options payload.`,u.GENERIC_FAILURE);let n=e,o={};for(let[s,r]of Object.entries(n)){let i=s.trim();if(i.length===0)throw new p(`Template "${t}" contains an empty option key.`,u.GENERIC_FAILURE);if(typeof r=="string"){o[i]=r;continue}if(Array.isArray(r)&&r.every(a=>typeof a=="string")){o[i]=[...r];continue}throw new p(`Template "${t}" contains invalid value for option "${i}".`,u.GENERIC_FAILURE)}return ys(o)}function bs(e,t){let n;try{n=JSON.parse(e)}catch{throw new p(`Template "${t}" contains invalid JSON.`,u.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new p(`Template "${t}" has invalid document shape.`,u.GENERIC_FAILURE);let o=n,s=Ku(o.options,t),r=k();return{name:typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():t,created_at:typeof o.created_at=="string"?o.created_at:r,updated_at:typeof o.updated_at=="string"?o.updated_at:r,options:s}}function Ad(e){let t=xd[e];return t?{name:e,created_at:kd,updated_at:kd,options:ys({...t})}:null}async function Cd(e,t){let n=await G(Sn(e,t));if(n!==null)return{document:bs(n,t),source:"user"};let o=Ad(t);if(o)return{document:o,source:"builtin"};throw new p(`Template "${t}" not found`,u.NOT_FOUND)}async function Td(e,t){let n=await G(Sn(e,t));if(n===null)throw new p(`Template "${t}" not found`,u.NOT_FOUND);return bs(n,t)}async function Yu(e,t){let n=kn(t),{document:o}=await Cd(e,n);return o.options}async function ws(e,t,n){let o=I(process.cwd(),n.path);await gs(o);let s=kn(e),r=Rd(t);if(Object.keys(r).length===0)throw new p("templates save requires at least one create option flag",u.USAGE);let i=k(),a=Sn(o,s),c=i;await x(a)&&(c=(await Td(o,s)).created_at);let d={name:s,created_at:c,updated_at:i,options:r},l=await R(o);return await Sd.mkdir(hs(o),{recursive:!0}),await Ye({pmRoot:o,filePath:a,raw:`${JSON.stringify(d,null,2)}
62
+ `,op:"templates:save",author:C(void 0,l.author_default),lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms}),{name:d.name,created_at:d.created_at,updated_at:d.updated_at,path:a,options:d.options}}async function Ju(e){let t=hs(e);return await x(t)?(await Sd.readdir(t)).filter(o=>o.toLowerCase().endsWith(_s)).map(o=>o.slice(0,-_s.length)).filter(o=>Ed.test(o)):[]}async function Xu(e){let t=I(process.cwd(),e.path);await gs(t);let n=await Ju(t),o=new Set(n),s=Object.keys(xd).filter(c=>!o.has(c)),r=[...n].sort((c,d)=>c.localeCompare(d)),i=[...s].sort((c,d)=>c.localeCompare(d)),a=[...new Set([...r,...i])].sort((c,d)=>c.localeCompare(d));return{templates:a,count:a.length,builtin_templates:i,user_templates:r}}async function Zu(e,t){let n=I(process.cwd(),t.path);await gs(n);let o=kn(e),{document:s,source:r}=await Cd(n,o);return{name:s.name,source:r,created_at:s.created_at,updated_at:s.updated_at,path:r==="builtin"?`builtin:${o}`:Sn(n,o),options:s.options}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1e34cfb-3d4e-5b79-8585-3162e71e574c")}catch{}})();var Fd=["list","show","apply","lint"],ef="schema-types",tf="schema-statuses",nf="schema-fields";function In(){let e=O();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Ld(){let{profiles:e,warnings:t}=ms(In());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:us(n.definition)})),warnings:t,generated_at:k()}}function Nd(e){let t;try{t=vn(e,In())}catch(o){throw new p(o instanceof Error?o.message:String(o),u.USAGE)}let{resolved:n}=t;return{action:"show",...hd(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:k()}}function Md(e){let t;try{t=vn(e,In())}catch(s){throw new p(s instanceof Error?s.message:String(s),u.USAGE)}let{resolved:n}=t,o=yd(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:o.ok,error_count:o.errorCount,warning_count:o.warningCount,findings:o.findings,warnings:t.warnings,generated_at:k()}}function of(e,t){return Qu.join(e,"templates",`${t}.json`)}async function sf(e,t){let n=await G(of(e,t));if(n!==null)try{let o=JSON.parse(n);if(o!==null&&typeof o=="object"&&!Array.isArray(o)){let s=o.options;if(s!==null&&typeof s=="object"&&!Array.isArray(s))return s}}catch{}}async function Od(e,t,n,o){let s=new Map;for(let r of o.templates){let i=await sf(e,r.name);i!==void 0&&s.set(r.name,i)}return{typesRaw:await G(Re(e,t.files.types,xe.types)),statusesRaw:await G(Re(e,t.files.statuses,xe.statuses)),fieldsRaw:await G(Re(e,t.files.fields,xe.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:s,installedPackages:new Set}}function st(e){let t=[],n=[],o=[];for(let s of e)(s.status==="add"?t:s.status==="update"?n:o).push(s.key);return{added:t,updated:n,unchanged:o}}function $d(e,t,n,o,s){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:o,changed:t.changed,types:st(t.types.changes),statuses:st(t.statuses.changes),fields:st(t.fields.changes),workflows:st(t.workflows.changes.map(r=>({key:r.type,status:r.status}))),config:st(t.config.changes),templates:st(t.templates.changes.map(r=>({key:r.name,status:r.status}))),packages:t.packages,warnings:[...new Set(s)].sort((r,i)=>r.localeCompare(i)),generated_at:k()}}async function rf(e){if(!await x(A(e)))throw new p(`Tracker is not initialized at ${e}. Run pm init first.`,u.NOT_FOUND)}function af(e){try{let t=vn(e,In());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new p(t instanceof Error?t.message:String(t),u.USAGE)}}async function Dd(e,t,n){let o=I(process.cwd(),n.path);await rf(o);let s=af(e),r=s.profile,i=s.warnings,a=t.dryRun===!0,c=await R(o),d=dr(c.schema);if(a){let h=await Od(o,d,c,r),S=Pd(r,h);return $d(r,S,!1,!0,[...i])}let l=C(t.author,c.author_default),m=jr(c),f=!!t.force,_=[...i],y=[],w=async h=>{y.push(await K(o,h,c.locks.ttl_seconds,l,f,m.force_required_for_stale_lock,c.locks.wait_ms))},g;try{await w(ef),await w(tf),await w(nf);let h=await Od(o,d,c,r);if(g=Pd(r,h),g.types.changed){let S=Re(o,d.files.types,xe.types);await Ye({pmRoot:o,filePath:S,raw:zt(g.types.file),op:"profile:apply-types",author:l,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let E=new Set(r.types.map(T=>fe(T).name)),F=g.types.file.definitions.filter(T=>E.has(T.name));await ma(o,F,_,"profile:apply-type-folder"),_.push(...await N({path:S,scope:"project",op:"profile:apply-types"}))}if(g.statuses.changed){let S=Re(o,d.files.statuses,xe.statuses);await Ye({pmRoot:o,filePath:S,raw:nn(g.statuses.file),op:"profile:apply-statuses",author:l,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await N({path:S,scope:"project",op:"profile:apply-statuses"}))}if(g.fields.changed){let S=Re(o,d.files.fields,xe.fields);await Ye({pmRoot:o,filePath:S,raw:on(g.fields.file),op:"profile:apply-fields",author:l,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),_.push(...await N({path:S,scope:"project",op:"profile:apply-fields"}))}if(g.config.changed||g.workflows.changed){for(let S of g.config.changes){if(S.status==="unchanged")continue;let E=Qe(S.key);E!==void 0&&Ba(c,E,S.value)}c.schema.type_workflows=g.workflows.result,await Ur(o,c,"profile:apply-config")}for(let S of g.templates.changes)S.status!=="unchanged"&&await ws(S.name,{...S.options},n)}finally{for(let h of y.reverse())try{await h()}catch{}}return $d(r,g,g.changed,!1,_)}function Pd(e,t){try{return vd(e,t)}catch(n){throw new p(n instanceof Error?n.message:String(n),u.USAGE)}}function cf(e,t){let n=[];if(t.added.length>0&&n.push(`+${t.added.join(", ")}`),t.updated.length>0&&n.push(`~${t.updated.join(", ")}`),n.length!==0)return` ${e}: ${n.join(" ")}`}function wv(e){let t=["Project profiles:"];for(let n of e.profiles){let o=n.source==="extension"?` [${n.package??"extension"}]`:"";t.push(` ${n.name} \u2014 ${n.title}: ${n.summary}${o}`)}for(let n of e.warnings)t.push(` warning: ${n}`);return t.join(`
63
+ `)}function vv(e){let t=e.source==="extension"?` [${e.package??"extension"}]`:"",n=[`${e.name} \u2014 ${e.title}${t}`,e.summary,""];n.push(`types: ${e.types.join(", ")||"(none)"}`),n.push(`statuses: ${e.statuses.join(", ")||"(none)"}`),n.push(`fields: ${e.fields.join(", ")||"(none)"}`),n.push(`workflows: ${e.workflows.join(", ")||"(none)"}`),n.push(`config: ${e.config.join(", ")||"(none)"}`),n.push(`templates: ${e.templates.join(", ")||"(none)"}`),n.push(`packages: ${e.packages.map(o=>o.spec).join(", ")||"(none)"}`);for(let o of e.warnings)n.push(`warning: ${o}`);return n.join(`
64
+ `)}function kv(e){let t=e.source==="extension"?` [${e.package??"extension"}]`:"",n=e.warning_count+e.warnings.length,s=[e.ok?`Profile ${e.name}${t}: ok (${n} warning${n===1?"":"s"})`:`Profile ${e.name}${t}: ${e.error_count} error${e.error_count===1?"":"s"}, ${n} warning${n===1?"":"s"}`];for(let r of e.findings){let i=r.target!==void 0?` (${r.target})`:"";s.push(` ${r.severity} [${r.code}] ${r.dimension}${i}: ${r.message}`)}for(let r of e.warnings)s.push(` warning: ${r}`);return s.join(`
65
+ `)}function Sv(e){let t=e.dry_run?"dry-run":e.applied?"applied":"no changes",n=[`Profile ${e.name} (${t})`];if(!e.changed)n.push(" already up to date");else for(let[s,r]of[["types",e.types],["statuses",e.statuses],["fields",e.fields],["workflows",e.workflows],["config",e.config],["templates",e.templates]]){let i=cf(s,r);i!==void 0&&n.push(i)}let o=e.packages.filter(s=>s.status==="recommended");o.length>0&&n.push(` recommended packages: ${o.map(s=>s.spec).join(", ")}`);for(let s of e.warnings)n.push(` warning: ${s}`);return n.join(`
66
+ `)}import Ud from"node:fs/promises";import Gd from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7e0f84f6-9528-55c5-8976-6f85cd920486")}catch{}})();function df(e,t,n){let o=new Set,s=[];for(let r of e){let i=r.trim();if(i.length===0||o.has(i))continue;o.add(i);let a=t.get(i);if(a===void 0){s.push({id:i,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=n){s.push({id:i,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}s.push({id:i,entries:a.entries,selected:!0,skip_reason:null})}return s}function lf(e,t){let n=[...e].sort((s,r)=>r.entries-s.entries||s.id.localeCompare(r.id)),o=[];for(let s of n){if(t.scope==="closed"&&s.bucket!=="closed"){o.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(s.entries<=t.minEntries){o.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&s.entries<=t.allOver){o.push({id:s.id,entries:s.entries,selected:!1,skip_reason:"below_threshold"});continue}o.push({id:s.id,entries:s.entries,selected:!0,skip_reason:null})}return o}function jd(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(o=>[o.id,o]));return df(t.ids,n,t.minEntries)}return lf(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6609492-75a9-5111-b9b3-1b81908f3084")}catch{}})();function mf(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new p("history-compact --before requires a non-empty value.",u.USAGE);if(/^\d+$/.test(n)){let r=Number.parseInt(n,10);if(!Number.isSafeInteger(r)||r<1||r>t.length+1)throw new p(`history-compact --before version must be between 1 and ${t.length+1}.`,u.USAGE);let i=Math.max(0,Math.min(t.length,r-1));return{kind:"version",raw:n,compactCount:i,retainedCount:t.length-i}}let o=Date.parse(n);if(!Number.isFinite(o))throw new p(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,u.USAGE);let s=0;for(let[r,i]of t.entries()){let a=Date.parse(i.ts);if(!Number.isFinite(a))throw new p(`History for this item contains invalid timestamp at entry ${r+1}.`,u.GENERIC_FAILURE);if(a>=o)break;s+=1}return{kind:"timestamp",raw:n,compactCount:s,retainedCount:t.length-s}}function pf(e,t){let n=jt(),o=jt();for(let s=0;s<e.length;s+=1){let r=e[s];if(Q(n)!==r.before_hash)throw new p(`history-compact detected before-hash drift at entry ${s+1}; run pm history-repair first.`,u.CONFLICT);if(n=Jt(n,r.patch,s+1,r.op),Q(n)!==r.after_hash)throw new p(`history-compact detected after-hash drift at entry ${s+1}; run pm history-repair first.`,u.CONFLICT);s+1===t&&(o=structuredClone(n))}return{checkpoint:o,finalReplay:n}}function uf(e,t,n){let o=structuredClone(t),s=[];for(let[r,i]of e.entries()){let a=Q(o);o=Jt(o,i.patch,n+r+1,i.op),s.push({...i,before_hash:a,after_hash:Q(o)})}return{entries:s,finalReplay:o}}async function ff(e,t,n){let o=e.located?await H(e.located,{schema:t.schema}):null;return o?{loadedItem:o,currentItemRawBeforeLock:o.raw,matchedChainBefore:Q(Oe(o.document))===n[n.length-1]?.after_hash}:{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null}}function _f(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function hf(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function gf(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=pf(e.historyEntries,e.boundary.compactCount),o=e.historyEntries.slice(e.boundary.compactCount),s=uf(o,t,e.boundary.compactCount),i=[re({nowIso:k(),author:e.author,op:"history_compact_baseline",before:Te(jt()),after:Te(t),message:hf(e.boundary)}),...s.entries];return e.dryRun||i.push(re({nowIso:k(),author:e.author,op:"history_compact",before:Te(n),after:Te(n),message:_f(e.options,e.boundary)})),{rewrittenEntries:i,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function yf(e){return Zt({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-compact",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Xt({historyPath:e.historyPath,nextHistoryRaw:ue(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>N({path:e.historyPath,scope:"project",op:"history_compact:history"})})}async function vs(e,t,n){let o=I(process.cwd(),n.path);if(!await x(A(o)))throw new p(`Tracker is not initialized at ${o}. Run pm init first.`,u.NOT_FOUND);let s=await R(o),r=P(s,O()),i=await Qt(o,e,s,r.type_to_folder),a=i.historyPath,c=await G(a);if(c===null)throw new p(`No history stream exists for ${i.id}.`,u.NOT_FOUND);let d=await Ve(a,i.id);if(d.length===0)throw new p(`No history entries exist for ${i.id}; nothing to compact.`,u.USAGE);let l=Ke(d);if(!l.ok)throw new p(`history-compact requires a valid history chain (${l.errors.join(", ")}). Run pm history-repair ${i.id} first.`,u.CONFLICT);let m=mf(t.before,d),f=m.compactCount>0,_=!!t.dryRun,y=C(t.author,s.author_default),w=[];f||w.push("history_compact_noop_before_boundary");let g=await ff(i,s,d);g.matchedChainBefore===!1&&w.push("history_compact_item_chain_mismatch");let{rewrittenEntries:h,baselineEntryAdded:S,auditEntryAdded:E}=gf({historyEntries:d,boundary:m,changed:f,dryRun:_,author:y,options:t}),F=Ke(h);if(!F.ok)throw new p(`history-compact produced an invalid rewritten chain (${F.errors.join(", ")}).`,u.GENERIC_FAILURE);f&&!_&&w.push(...await yf({pmRoot:o,subject:i,settings:s,typeRegistry:r,historyRawBeforeLock:c,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:y,force:t.force,loadedItem:g.loadedItem,historyPath:a,rewrittenEntries:h}));let T=m.retainedCount>0?m.compactCount+1:null;return{id:i.id,dry_run:_,changed:f,compact_boundary:{kind:m.kind,before:m.raw,entries_compacted:m.compactCount,entries_retained:m.retainedCount,first_retained_entry:T},history:{path:a,entries_scanned:d.length,entries_after:h.length,baseline_entry_added:S,audit_entry_added:E,verify_ok:F.ok,verify_errors:F.errors},item:{exists:i.located!==null,path:i.located?.itemPath??null,matched_chain_before:g.matchedChainBefore},warnings:[...new Set(w)].sort((j,U)=>j.localeCompare(U)),generated_at:k()}}var bf=3;function qd(e,t){let n=t.ids!==void 0&&t.ids.length>0,o=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(o?1:0)===0)throw new p("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",u.USAGE);if(e!==void 0&&(n||o))throw new p("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",u.USAGE);if(n&&o)throw new p("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",u.USAGE)}function wf(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function vf(e){let t=q(e.settings.schema),n=Pa(t),o=await $e(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),s=new Map(o.map(d=>[d.id,n.classify(d.status)])),r=Gd.join(e.pmRoot,"history"),i=[],a=[];if(!await x(r))return{candidates:i,preselectionErrors:a};let c=(await Ud.readdir(r)).filter(d=>d.endsWith(".jsonl")).sort((d,l)=>d.localeCompare(l));for(let d of c){let l=Gd.join(r,d),m=d.slice(0,-6);try{let f=await Ud.readFile(l,"utf8");await Kn({path:l,scope:"project"}),i.push({id:m,entries:wf(f),bucket:s.get(m)??null})}catch(f){a.push({id:m,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:i,preselectionErrors:a}}async function kf(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await vs(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function zd(e,t){let n=I(process.cwd(),t.path);if(!await x(A(n)))throw new p(`Tracker is not initialized at ${n}. Run pm init first.`,u.NOT_FOUND);let o=await R(n),s=P(o,O()),{candidates:r,preselectionErrors:i}=await vf({pmRoot:n,settings:o,typeToFolder:s.type_to_folder}),a=e.ids!==void 0&&e.ids.length>0?"ids":"scan",c=e.minEntries??bf,d=o.history.compact_policy,l=a==="scan"&&e.allOver===void 0&&d.enabled,m=e.allOver??(l?d.max_entries:void 0),f=jd(r,{ids:e.ids,scope:e.scope,minEntries:c,allOver:m}),_=!!e.dryRun,y=[...i],w={streams_considered:r.length+i.length,selected:0,items_compacted:0,items_skipped:0,items_errored:i.length};for(let g of f){let h=await kf({row:g,options:e,dryRun:_,global:t});if(y.push(h.result),!h.selected){w.items_skipped+=1;continue}w.selected+=1,h.compacted&&(w.items_compacted+=1),h.errored&&(w.items_errored+=1)}return{bulk:!0,dry_run:_,mode:a,scope:e.scope??null,criteria:{min_entries:c,all_over:m??null,policy_threshold_applied:l},totals:w,results:y,generated_at:k()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f762b5e6-8224-531f-9dd1-f71dc18c3ddf")}catch{}})();function Hd(e){let t=e.options.all===!0,n=e.id??b(e.options,"id");return dd(n,t),t?bn(e.options,e.global):Et(n,e.options,e.global)}function Bd(e){let t=e.options.ids,n=Array.isArray(t)?t.map(String).filter(d=>d.trim().length>0):typeof t=="string"?t.split(",").map(d=>d.trim()).filter(Boolean):void 0,o=te(e.options.allOver??e.options.all_over,"history-compact allOver"),s=te(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),r=b(e.options,"scope"),i=[];e.options.closed===!0&&i.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&i.push("all-streams"),(r==="closed"||r==="all-streams")&&i.push(r);let a=[...new Set(i)];if(a.length>1)throw new p("history-compact: closed and all-streams scopes are mutually exclusive.",u.USAGE);let c=a[0];return qd(e.id,{ids:n,allOver:o,scope:c}),e.id!==void 0?vs(e.id,{before:b(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global):zd({ids:n,scope:c,allOver:o,minEntries:s,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2ef0de1-bc44-5550-862c-f3929334fbef")}catch{}})();function Vd(e,t,n){let o;if(typeof e.lines=="string")o=po(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");o=po(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:o,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dbabff08-1bb7-539b-b1c1-c10584aa0a67")}catch{}})();function Wd(e){return{storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:b(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:V(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:b(e,"measurementSource"),measurementItem:b(e,"measurementItem"),measurementRevision:b(e,"measurementRevision"),author:b(e,"author"),message:b(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:b(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2643d11d-befc-5a87-8bec-760951eec4d0")}catch{}})();var Sf=new Set(["true","1","yes","on"]),If=new Set(["false","0","no","off"]);function Ef(e,t,n=[]){let o=[t,...n];for(let s of o){let r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}function xf(e,t,n=[]){let o=[t,...n];for(let s of o){let r=e[s];if(r!==void 0){if(typeof r=="boolean")return r;if(typeof r=="string"){let i=r.trim().toLowerCase();if(Sf.has(i))return!0;if(If.has(i))return!1}}}}function Rf(e,t,n=[]){for(let o of[t,...n]){let s=e[o],i=(typeof s=="string"?s.split(","):Array.isArray(s)?s.flatMap(a=>typeof a=="string"?a.split(","):[]):[]).map(a=>a.trim()).filter(a=>a.length>0);if(i.length>0)return i}return[]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2567f6a-cd1c-56b5-a93d-41e92ed574bf")}catch{}})();function z(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Af(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);if(Number.isFinite(t)&&t>=0)return t}}function Cf(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=4)return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);if(Number.isInteger(t)&&t>=0&&t<=4)return t}return 2}function Tf(e){if(Array.isArray(e)){let t=e.filter(n=>typeof n=="string").map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);return Array.from(new Set(t)).sort((n,o)=>n.localeCompare(o))}return typeof e=="string"?ht(e):[]}function Of(e){let t=z(e);if(t){let n=ft(t);if(n)return n}return"open"}function Ss(e){if(typeof e=="number"&&Number.isInteger(e))return e;if(typeof e!="string"||e.trim().length===0)return;let t=Number(e);return Number.isInteger(t)?t:void 0}function Kd(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e===1?!0:e===0?!1:void 0;if(typeof e!="string")return;let t=e.trim().toLowerCase();return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:void 0}function rt(e){if(!Array.isArray(e))return;let t=e.map(n=>z(n)).filter(n=>n!==void 0);return t.length>0?t:void 0}function ks(e){return Xd(e,z)}function Yd(e){return Xd(e,Qd)}function $f(e,t){if(typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=100)return e;let n=z(e)?.toLowerCase();if(!n)return;let o=n==="med"?"medium":n;if(t.some(r=>r===o))return o;let s=Number(o);return Number.isInteger(s)&&s>=0&&s<=100?s:void 0}function Jd(e,t){let n=z(e)?.toLowerCase();if(!n)return;let o=n==="med"?"medium":n;return t.includes(o)?o:void 0}function Is(e){return z(e)?.toLowerCase()==="global"?"global":"project"}function Pf(e,t){let n=Es(e,t.allowScalar===!0);if(!n)return;let o=n.map(s=>Df(s,t)).filter(s=>s!==void 0);return o.length>0?o:void 0}function Ff(e,t={}){return Zd(e,t,(n,o)=>({path:n,scope:Is(o?.scope),note:z(o?.note)}))}function Lf(e,t={}){return Zd(e,t,(n,o)=>({path:n,scope:Is(o?.scope),note:z(o?.note)}))}function Nf(e,t={}){let n=Es(e,t.allowScalar===!0);if(!n)return;let o=n.map(s=>Gf(s,t)).filter(s=>s!==void 0);return o.length>0?o:void 0}function Mf(e,t){return C(e,t)}function xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Es(e,t){return Array.isArray(e)?e:t?[e]:void 0}function En(e,t){for(let n of t){let o=z(e[n]);if(o)return o}}function Xd(e,t){if(!xn(e))return;let n=Object.entries(e).map(([o,s])=>[o.trim(),t(s)]).filter(o=>o[0].length>0&&o[1]!==void 0);return n.length>0?Object.fromEntries(n):void 0}function Df(e,t){if(typeof e=="string")return jf(e,t);if(!xn(e))return;let n=En(e,t.textKeys??["text"]);if(!n)return;let o=t.createdAtKey??"created_at",s=t.authorKey??"author";return{created_at:(t.toIsoString?t.toIsoString(e[o]):z(e[o]))??t.fallbackCreatedAt,author:z(e[s])??t.fallbackAuthor,text:n}}function jf(e,t){let n=z(e);return n?{created_at:t.fallbackCreatedAt,author:t.fallbackAuthor,text:n}:void 0}function Zd(e,t,n){let o=Es(e,t.allowScalar===!0);if(!o)return;let s=t.pathKeys??["path"],r=o.map(i=>Uf(i,s,n)).filter(i=>i!==void 0);return r.length>0?r:void 0}function Uf(e,t,n){if(typeof e=="string"){let s=z(e);return s?n(s):void 0}if(!xn(e))return;let o=En(e,t);return o?n(o,e):void 0}function Gf(e,t){if(typeof e=="string"){let s=z(e);return s?{command:s,scope:"project"}:void 0}if(!xn(e))return;let n=En(e,t.commandKeys??["command"]),o=En(e,t.pathKeys??["path"]);if(!(!n&&(t.requireCommand===!0||!o)))return{...n?{command:n}:{},...o?{path:o}:{},scope:Is(e.scope),timeout_seconds:qf(e.timeout_seconds,t),note:z(e.note),...t.includeExtendedAssertions===!0?zf(e):{}}}function qf(e,t){let n=t.integerTimeout===!0?Ss(e):Qd(e);if(n===void 0)return;let o=t.timeoutMinimum??0;return t.timeoutExclusiveMinimum===!0?n>o?n:void 0:n>=o?n:void 0}function Qd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string"||e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function zf(e){return{pm_context_mode:Jd(e.pm_context_mode,["schema","tracker","auto"]),env_set:ks(e.env_set),env_clear:rt(e.env_clear),shared_host_safe:Kd(e.shared_host_safe),assert_stdout_contains:rt(e.assert_stdout_contains),assert_stdout_regex:rt(e.assert_stdout_regex),assert_stderr_contains:rt(e.assert_stderr_contains),assert_stderr_regex:rt(e.assert_stderr_regex),assert_stdout_min_lines:Ss(e.assert_stdout_min_lines),assert_json_field_equals:ks(e.assert_json_field_equals),assert_json_field_gte:Yd(e.assert_json_field_gte)}}async function Hf(e){if(!await x(A(e)))throw new p(`Tracker is not initialized at ${e}. Run pm init first.`,u.NOT_FOUND)}function el(){return{metadata:{},body:""}}async function Bf(e){let{pmRoot:t,id:n,itemPath:o,document:s,author:r,message:i,settings:a,conflictWarningPrefix:c}=e,d=se(t,n),l=el();try{let m=await K(t,n,a.locks.ttl_seconds,r,!1,a.governance.force_required_for_stale_lock,a.locks.wait_ms);try{await B(o,me(s,{format:"toon"}));try{let f=re({nowIso:k(),author:r,op:"import",before:l,after:s,message:i});return await Ce(d,f),{committed:!0,writeWarnings:[...await N({path:o,scope:"project",op:"import",item_id:s.metadata.id,item_type:s.metadata.type,before:l,after:s,changed_fields:["imported"]}),...await N({path:d,scope:"project",op:"import:history",item_id:s.metadata.id,item_type:s.metadata.type,before:l,after:s,changed_fields:["imported"]})]}}catch(f){throw await dt(o),f}}finally{await m()}}catch(m){if(m instanceof p&&m.exitCode===u.CONFLICT)return{committed:!1,conflictWarning:`${c}:${n}`};throw m}}import{readFile as Wf}from"node:fs/promises";import Kf 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]="3911e4fb-a9b3-5732-8b45-c484a121dffb")}catch{}})();function Vf(e){return e.trim().toLowerCase().replaceAll("_","-")}var Rs=[{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm init","pm context --limit 10","pm list-open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list-open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm install <target> --project","pm upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]}],xs=new Map;for(let e of Rs){xs.set(e.id,e);for(let t of e.aliases)xs.set(t,e)}function tl(){return Rs.map(e=>({...e,aliases:[...e.aliases],commands:[...e.commands],workflows:e.workflows.map(t=>({...t,commands:[...t.commands]})),docs:e.docs.map(t=>({...t})),related:[...e.related]}))}function Rn(){return Rs.map(e=>e.id)}function nl(e){if(!e)return null;let t=Vf(e);return t?xs.get(t)??null: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]="9376fbdf-c942-5fa6-9252-92125ae44e73")}catch{}})();var Yf=["markdown","toon","json"],Jf=["brief","standard","deep"];function Xf(e){if(!e)return;let t=e.trim().toLowerCase();if(!Yf.includes(t))throw new p("Guide format must be one of markdown|toon|json",u.USAGE);return t}function Zf(e,t){let n=Xf(e.format);if(t.json&&n&&n!=="json")throw new p("Cannot combine --json with --format markdown|toon",u.USAGE);return t.json?"json":n??"toon"}function Qf(e){if(!e)return"brief";let t=e.trim().toLowerCase();if(!Jf.includes(t))throw new p("Guide depth must be one of brief|standard|deep",u.USAGE);return t}function e_(){return Vs(process.env,"PM_CLI_PACKAGE_ROOT",import.meta.url,["..","..",".."])}function ol(e){return e.replaceAll(`\r
67
67
  `,`
68
- `)}function Uf(e,t,n){let s=Hd(e).split(`
68
+ `)}function t_(e,t,n){let s=ol(e).split(`
69
69
  `),i=s.slice(0,t).join(`
70
- `),a=s.length>t;return i.length>n&&(i=i.slice(0,n),a=!0),{excerpt:i.trimEnd(),truncated:a,lineCount:s.length}}async function Gf(e,t,n){let o=t!=="brief",s=o?t==="deep"?"full":"excerpt":"none",r=[];for(let i of e.docs){let a=Pf.resolve(n,i.path);if(!o){r.push({path:i.path,purpose:i.purpose,optional:i.optional===!0,exists:!0,line_count:null,content_mode:"none",content:null,truncated:!1});continue}try{let c=await $f(a,"utf8");if(t==="deep"){let d=Hd(c).trimEnd();r.push({path:i.path,purpose:i.purpose,optional:i.optional===!0,exists:!0,line_count:d.length===0?0:d.split(`
71
- `).length,content_mode:"full",content:d,truncated:!1})}else{let d=Uf(c,120,12e3);r.push({path:i.path,purpose:i.purpose,optional:i.optional===!0,exists:!0,line_count:d.lineCount,content_mode:s,content:d.excerpt,truncated:d.truncated})}}catch(c){let l=c?.code==="ENOENT";if(r.push({path:i.path,purpose:i.purpose,optional:i.optional===!0,exists:!1,line_count:null,content_mode:"none",content:null,truncated:!1}),!l)throw new p(`Failed to read guide document "${i.path}".`,u.GENERIC_FAILURE)}}return r}function qf(e){let t=qd().map(n=>({id:n.id,aliases:n.aliases,title:n.title,summary:n.summary,intent:n.intent,quick_commands:e==="brief"?n.commands.slice(0,3):n.commands.slice(0,6),docs:n.docs.map(o=>({path:o.path,purpose:o.purpose})),related:n.related}));return{output_default:"toon",mode:"index",depth:e,topics:t,suggested_next_steps:["pm guide <topic>","pm guide <topic> --depth standard","pm guide <topic> --depth deep --format markdown","pm guide <topic> --json"]}}function zf(e){let t=zd(e);if(t)return t;let n=xn().join(", ");throw new p(`Unknown guide topic "${e}". Available topics: ${n}. Use "pm guide --list" to browse.`,u.USAGE)}async function Hf(e,t){let n=Df(typeof e.depth=="string"?e.depth:void 0),o=e.list===!0,s=typeof e.topic=="string"?e.topic:void 0;if(o||!s)return qf(n);let r=zf(s),i=jf(),a=await Gf(r,n,i),c=a.filter(d=>!d.exists&&!d.optional).map(d=>`Missing required guide document: ${d.path}`);return{output_default:"toon",mode:"topic",depth:n,requested_topic:s,topic:r,docs:a,warnings:c}}function Bf(e){return e.replaceAll("```","``\\`")}function Vf(e){if(e.mode==="index"){let n=["# pm guide","","Token-efficient local documentation index for agent and maintainer workflows.","","## Topics"];for(let o of e.topics)n.push(`- \`${o.id}\` - ${o.summary}`),e.depth!=="brief"&&(n.push(` - intent: ${o.intent}`),n.push(` - docs: ${o.docs.map(s=>`\`${s.path}\``).join(", ")}`));n.push("","## Next steps");for(let o of e.suggested_next_steps)n.push(`- \`${o}\``);return n.join(`
72
- `)}let t=[`# pm guide ${e.topic.id}`,"",e.topic.summary,"","## Intent",e.topic.intent,"","## Key commands",...e.topic.commands.map(n=>`- \`${n}\``),"","## Workflow prompts"];for(let n of e.topic.workflows)t.push(`### ${n.name}`),t.push(`goal: ${n.goal}`),t.push(`prompt: ${n.prompt}`),t.push("commands:"),t.push(...n.commands.map(o=>`- \`${o}\``)),t.push("");t.push("## Documents");for(let n of e.docs){let o=n.exists?"available":n.optional?"missing (optional)":"missing (required)";t.push(`- \`${n.path}\` - ${n.purpose} (${o})`),n.exists&&n.content_mode!=="none"&&n.content&&(t.push(""),t.push(`### Excerpt: \`${n.path}\``),n.truncated&&t.push("_truncated for context efficiency_"),t.push("```markdown"),t.push(Bf(n.content)),t.push("```"))}return e.topic.related.length>0&&(t.push("","## Related topics"),t.push(...e.topic.related.map(n=>`- \`${n}\``))),e.warnings.length>0&&(t.push("","## Warnings"),t.push(...e.warnings.map(n=>`- ${n}`))),t.join(`
73
- `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c9648d7-ab14-5e0d-8793-86ae13643fa6")}catch{}})();var Bd=["bash","zsh","fish"],Wf=[...ct],Kf=[...$n],Es=Ya("full"),Yf=$(Kt),Jf=$(ri),Xf=$(pi),Zf=$(yi),Qf=$(bi),e_=$(ui),t_=$(fi),n_=$(gi),o_=$(xi),s_=$(wi),r_=$(vi),i_=$(mi),a_=$(Si),c_=$(ii),d_=$(Ii),l_=$(ki),m_=$(Ei),p_=$(Ti),u_=$(Ai),f_=$(_i),__=$(Ci),h_=$(Ri),g_=$(Yt),y_=$(hi),b_=$(ci),w_=$(Oi),v_=$(ai),k_="create show add-step update-step complete-step block-step reorder-step remove-step link unlink decision discovery validation resume approve materialize",S_=$($i),I_=`${S_} bash zsh fish`,xs=st(xn()),Rn="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate",E_=$(di),x_=$(li),R_="--author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",A_="--dry-run --author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",C_="--author --message --validate-close --duplicate-of --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",T_="--author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",Zd=[["init","Initialize pm storage for the current workspace"],["config","Read or update pm settings"],["extension","Manage extension lifecycle operations"],["package","Manage package lifecycle operations"],["packages","Alias for package"],["create","Create a new project management item"],["copy","Copy an existing item to a new ID"],["focus","Set/clear/show the session focused parent for new items"],["list","List active items with optional filters"],["list-all","List all items with optional filters"],["list-draft","List draft items with optional filters"],["list-open","List open items with optional filters"],["list-in-progress","List in-progress items with optional filters"],["list-blocked","List blocked items with optional filters"],["list-closed","List closed items with optional filters"],["list-canceled","List canceled items with optional filters"],["aggregate","Aggregate grouped item counts and numeric stats for governance queries"],["duplicates","Find bounded duplicate clusters across lifecycle statuses"],["guide","Browse local progressive-disclosure guides"],["calendar","Show calendar views for deadlines and reminders"],["cal","Alias for calendar"],["context","Show a token-efficient project context snapshot"],["ctx","Alias for context"],["get","Show item details by ID"],["next","Recommend the next actionable (unblocked, ready) work item"],["search","Search items with keyword, semantic, or hybrid modes"],["reindex","Rebuild search artifacts"],["history","Show item history entries"],["history-compact","Compact history streams into a synthetic baseline + retained tail"],["history-redact","Redact sensitive literals/patterns and recompute history hashes"],["history-repair","Re-anchor a drifted history chain so pm health/validate report ok"],["schema","Manage custom item types and statuses in .agents/pm/schema/*.json"],["profile","List, show, apply, and lint project profiles (archetype schema/config/template/package bundles)"],["plan","Agent-optimized Plan item workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["activity","Show recent activity across items"],["restore","Restore an item to an earlier state"],["update","Update item fields and metadata"],["update-many","Bulk-update matched items with dry-run and rollback checkpoints"],["close","Close an item (reason requirement follows governance settings)"],["close-many","Bulk-close matched items with an optional shared reason and rollback checkpoint"],["delete","Delete an item and record the change"],["append","Append text to an item body"],["comments","List or add comments for an item"],["notes","List or add notes for an item"],["learnings","List or add learnings for an item"],["files","Manage linked files"],["docs","Manage linked docs"],["deps","Show dependency relationships for an item"],["graph","Bounded graph traversal, analytics, and governance-audit queries"],["test","Manage linked tests and optionally run them"],["test-all","Run linked tests across matching items"],["test-runs","Manage background linked-test runs"],["stats","Show project tracker statistics"],["health","Show project tracker health checks"],["validate","Run standalone validation checks"],["gc","Clean optional cache artifacts"],["contracts","Show machine-readable command and schema contracts"],["claim","Claim an item for active work"],["release","Release the active claim for an item"],["start-task","Lifecycle alias to claim and set in_progress"],["pause-task","Lifecycle alias to reopen and release claim"],["close-task","Lifecycle alias to close and release claim"],["meet","Shortcut to create a Meeting with scheduling defaults"],["event","Shortcut to create an Event with scheduling defaults"],["remind","Shortcut to create a Reminder from a point in time"],["templates","Manage reusable create templates"],["completion","Generate shell completion"],["help","Display help for a command"]],O_=new Map([["calendar","Show deadline/reminder calendar views"],["schema","Inspect and manage runtime schema"],["profile","List, show, apply, and lint project profiles (archetype bundles)"],["plan","Agent-optimized Plan workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["start-task","Lifecycle alias to claim and set in-progress"]]),$_=si.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function st(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}function P_(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].join(" ")}function Qd(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll("$","\\$").replaceAll("`","\\`")}function Rs(e,t){return P_(e.length>0?e:t.item_types??Wf)}function As(e){return st(e.statuses??Kf)}function De(e,t){let n=[...e.split(/\s+/u).filter(o=>o.length>0),...t??[]];return st(n)}function el(e){let t=(e??[]).map(n=>n.trim()).filter(n=>n.startsWith("--")&&n.length>2).map(n=>`--${n.slice(2).replaceAll("_","-")}`);return[...new Set(t)].sort((n,o)=>n.localeCompare(o))}function xt(e){let t=el(e);return t.length===0?"":`${t.map(n=>` '${n}[Runtime schema field flag]:value' \\`).join(`
70
+ `),a=s.length>t;return i.length>n&&(i=i.slice(0,n),a=!0),{excerpt:i.trimEnd(),truncated:a,lineCount:s.length}}async function n_(e,t,n){let o=t!=="brief",s=o?t==="deep"?"full":"excerpt":"none",r=[];for(let i of e.docs){let a=Kf.resolve(n,i.path);if(!o){r.push({path:i.path,purpose:i.purpose,optional:i.optional===!0,exists:!0,line_count:null,content_mode:"none",content:null,truncated:!1});continue}try{let c=await Wf(a,"utf8");if(t==="deep"){let d=ol(c).trimEnd();r.push({path:i.path,purpose:i.purpose,optional:i.optional===!0,exists:!0,line_count:d.length===0?0:d.split(`
71
+ `).length,content_mode:"full",content:d,truncated:!1})}else{let d=t_(c,120,12e3);r.push({path:i.path,purpose:i.purpose,optional:i.optional===!0,exists:!0,line_count:d.lineCount,content_mode:s,content:d.excerpt,truncated:d.truncated})}}catch(c){let l=c?.code==="ENOENT";if(r.push({path:i.path,purpose:i.purpose,optional:i.optional===!0,exists:!1,line_count:null,content_mode:"none",content:null,truncated:!1}),!l)throw new p(`Failed to read guide document "${i.path}".`,u.GENERIC_FAILURE)}}return r}function o_(e){let t=tl().map(n=>({id:n.id,aliases:n.aliases,title:n.title,summary:n.summary,intent:n.intent,quick_commands:e==="brief"?n.commands.slice(0,3):n.commands.slice(0,6),docs:n.docs.map(o=>({path:o.path,purpose:o.purpose})),related:n.related}));return{output_default:"toon",mode:"index",depth:e,topics:t,suggested_next_steps:["pm guide <topic>","pm guide <topic> --depth standard","pm guide <topic> --depth deep --format markdown","pm guide <topic> --json"]}}function s_(e){let t=nl(e);if(t)return t;let n=Rn().join(", ");throw new p(`Unknown guide topic "${e}". Available topics: ${n}. Use "pm guide --list" to browse.`,u.USAGE)}async function r_(e,t){let n=Qf(typeof e.depth=="string"?e.depth:void 0),o=e.list===!0,s=typeof e.topic=="string"?e.topic:void 0;if(o||!s)return o_(n);let r=s_(s),i=e_(),a=await n_(r,n,i),c=a.filter(d=>!d.exists&&!d.optional).map(d=>`Missing required guide document: ${d.path}`);return{output_default:"toon",mode:"topic",depth:n,requested_topic:s,topic:r,docs:a,warnings:c}}function i_(e){return e.replaceAll("```","``\\`")}function a_(e){if(e.mode==="index"){let n=["# pm guide","","Token-efficient local documentation index for agent and maintainer workflows.","","## Topics"];for(let o of e.topics)n.push(`- \`${o.id}\` - ${o.summary}`),e.depth!=="brief"&&(n.push(` - intent: ${o.intent}`),n.push(` - docs: ${o.docs.map(s=>`\`${s.path}\``).join(", ")}`));n.push("","## Next steps");for(let o of e.suggested_next_steps)n.push(`- \`${o}\``);return n.join(`
72
+ `)}let t=[`# pm guide ${e.topic.id}`,"",e.topic.summary,"","## Intent",e.topic.intent,"","## Key commands",...e.topic.commands.map(n=>`- \`${n}\``),"","## Workflow prompts"];for(let n of e.topic.workflows)t.push(`### ${n.name}`),t.push(`goal: ${n.goal}`),t.push(`prompt: ${n.prompt}`),t.push("commands:"),t.push(...n.commands.map(o=>`- \`${o}\``)),t.push("");t.push("## Documents");for(let n of e.docs){let o=n.exists?"available":n.optional?"missing (optional)":"missing (required)";t.push(`- \`${n.path}\` - ${n.purpose} (${o})`),n.exists&&n.content_mode!=="none"&&n.content&&(t.push(""),t.push(`### Excerpt: \`${n.path}\``),n.truncated&&t.push("_truncated for context efficiency_"),t.push("```markdown"),t.push(i_(n.content)),t.push("```"))}return e.topic.related.length>0&&(t.push("","## Related topics"),t.push(...e.topic.related.map(n=>`- \`${n}\``))),e.warnings.length>0&&(t.push("","## Warnings"),t.push(...e.warnings.map(n=>`- ${n}`))),t.join(`
73
+ `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="381bfd99-bd9b-5f8f-9783-65c2bf2cd810")}catch{}})();var sl=["bash","zsh","fish"],c_=[...lt],d_=[...Pn],As=rc("full"),l_=$(Kt),m_=$(di),p_=$(hi),u_=$(ki),f_=$(Si),__=$(gi),h_=$(yi),g_=$(vi),y_=$(Ti),b_=$(Ii),w_=$(Ei),v_=$(_i),k_=$(Ri),S_=$(li),I_=$(Ai),E_=$(xi),x_=$(Ci),R_=$(Fi),A_=$($i),C_=$(bi),T_=$(Pi),O_=$(Oi),$_=$(Yt),P_=$(wi),F_=$(pi),L_=$(Li),N_=$(mi),M_="create show add-step update-step complete-step block-step reorder-step remove-step link unlink decision discovery validation resume approve materialize",D_=$(Ni),j_=`${D_} bash zsh fish`,Cs=it(Rn()),An="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate",U_=$(ui),G_=$(fi),q_="--author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",z_="--dry-run --author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",H_="--author --message --validate-close --duplicate-of --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",B_="--author --message --force --json --quiet --no-changed-fields --id-only --pm-path --path --no-extensions --no-pager --profile --help",ml=[["init","Initialize pm storage for the current workspace"],["config","Read or update pm settings"],["extension","Manage extension lifecycle operations"],["package","Manage package lifecycle operations"],["packages","Alias for package"],["create","Create a new project management item"],["copy","Copy an existing item to a new ID"],["focus","Set/clear/show the session focused parent for new items"],["list","List active items with optional filters"],["list-all","List all items with optional filters"],["list-draft","List draft items with optional filters"],["list-open","List open items with optional filters"],["list-in-progress","List in-progress items with optional filters"],["list-blocked","List blocked items with optional filters"],["list-closed","List closed items with optional filters"],["list-canceled","List canceled items with optional filters"],["aggregate","Aggregate grouped item counts and numeric stats for governance queries"],["duplicates","Find bounded duplicate clusters across lifecycle statuses"],["guide","Browse local progressive-disclosure guides"],["calendar","Show calendar views for deadlines and reminders"],["cal","Alias for calendar"],["context","Show a token-efficient project context snapshot"],["ctx","Alias for context"],["get","Show item details by ID"],["next","Recommend the next actionable (unblocked, ready) work item"],["search","Search items with keyword, semantic, or hybrid modes"],["reindex","Rebuild search artifacts"],["history","Show item history entries"],["history-compact","Compact history streams into a synthetic baseline + retained tail"],["history-redact","Redact sensitive literals/patterns and recompute history hashes"],["history-repair","Re-anchor a drifted history chain so pm health/validate report ok"],["schema","Manage custom item types and statuses in .agents/pm/schema/*.json"],["profile","List, show, apply, and lint project profiles (archetype schema/config/template/package bundles)"],["plan","Agent-optimized Plan item workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["activity","Show recent activity across items"],["restore","Restore an item to an earlier state"],["update","Update item fields and metadata"],["update-many","Bulk-update matched items with dry-run and rollback checkpoints"],["close","Close an item (reason requirement follows governance settings)"],["close-many","Bulk-close matched items with an optional shared reason and rollback checkpoint"],["delete","Delete an item and record the change"],["append","Append text to an item body"],["comments","List or add comments for an item"],["notes","List or add notes for an item"],["learnings","List or add learnings for an item"],["files","Manage linked files"],["docs","Manage linked docs"],["deps","Show dependency relationships for an item"],["graph","Bounded graph traversal, analytics, and governance-audit queries"],["test","Manage linked tests and optionally run them"],["test-all","Run linked tests across matching items"],["test-runs","Manage background linked-test runs"],["stats","Show project tracker statistics"],["health","Show project tracker health checks"],["validate","Run standalone validation checks"],["gc","Clean optional cache artifacts"],["contracts","Show machine-readable command and schema contracts"],["claim","Claim an item for active work"],["release","Release the active claim for an item"],["start-task","Lifecycle alias to claim and set in_progress"],["pause-task","Lifecycle alias to reopen and release claim"],["close-task","Lifecycle alias to close and release claim"],["meet","Shortcut to create a Meeting with scheduling defaults"],["event","Shortcut to create an Event with scheduling defaults"],["remind","Shortcut to create a Reminder from a point in time"],["templates","Manage reusable create templates"],["completion","Generate shell completion"],["help","Display help for a command"]],V_=new Map([["calendar","Show deadline/reminder calendar views"],["schema","Inspect and manage runtime schema"],["profile","List, show, apply, and lint project profiles (archetype bundles)"],["plan","Agent-optimized Plan workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["start-task","Lifecycle alias to claim and set in-progress"]]),W_=ci.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" ");function it(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}function K_(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].join(" ")}function pl(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll("$","\\$").replaceAll("`","\\`")}function Ts(e,t){return K_(e.length>0?e:t.item_types??c_)}function Os(e){return it(e.statuses??d_)}function Ue(e,t){let n=[...e.split(/\s+/u).filter(o=>o.length>0),...t??[]];return it(n)}function ul(e){let t=(e??[]).map(n=>n.trim()).filter(n=>n.startsWith("--")&&n.length>2).map(n=>`--${n.slice(2).replaceAll("_","-")}`);return[...new Set(t)].sort((n,o)=>n.localeCompare(o))}function Rt(e){let t=ul(e);return t.length===0?"":`${t.map(n=>` '${n}[Runtime schema field flag]:value' \\`).join(`
74
74
  `)}
75
- `}function An(e,t={}){let n=t.trailingContinuation??!0,o=e.length-1;return e.map((s,r)=>` ${s}${n||r!==o?" \\":""}`).join(`
76
- `)}function F_(){return Zd.map(([e,t])=>` '${e}:${t}'`).join(`
77
- `)}function L_(){return Zd.filter(([e])=>e!=="help").map(([e,t])=>{let n=O_.get(e)??t;return`complete -c pm -n __pm_no_subcommand -a ${e.padEnd(16)} -d '${n}'`}).join(`
78
- `)}function Vd(e){let t=["reviewer-missing[Select only items missing reviewer]","risk-missing[Select only items missing risk]","confidence-missing[Select only items missing confidence]","sprint-missing[Select only items missing sprint]","release-missing[Select only items missing release]"],n=e.includeContentMissingAliases===!0?["files-missing[Alias for --no-files]","docs-missing[Alias for --no-docs]"]:[],o=[["has-notes[Select only items that have notes]","no-notes[Select only items with no notes]"],["has-learnings[Select only items that have learnings]","no-learnings[Select only items with no learnings]"],["has-files[Select only items that have linked files]","no-files[Select only items with no linked files]"],["has-docs[Select only items that have linked docs]","no-docs[Select only items with no linked docs]"],["has-tests[Select only items that have linked tests]","no-tests[Select only items with no linked tests]"],["has-comments[Select only items that have comments]","no-comments[Select only items with no comments]"],["has-deps[Select only items that have dependencies]","no-deps[Select only items with no dependencies]"],["has-body[Select only items with non-empty body]","empty-body[Select only items with empty body]"],["has-linked-command[Select only items that have a linked command]","no-linked-command[Select only items with no linked command]"]];return An([...[...t,...n].map(s=>`'--${e.missingPrefix}${s}'`),...o.flatMap(([s,r])=>[`'--${e.pairedPrefix}${s}'`,`'--${e.pairedPrefix}${r}'`])])}var N_=["'--comment[Comment seed author=<value>,created_at=<iso|now>,text=<value>]:comment'","'--note[Note seed author=<value>,created_at=<iso|now>,text=<value>]:note'","'--learning[Learning seed author=<value>,created_at=<iso|now>,text=<value>]:learning'","'--file[Linked file path=<value>,scope=<project|global>,note=<text>]:file'","'--test[Linked test command=<value>,path=<value>,scope=<project|global>]:test'","'--doc[Linked doc path=<value>,scope=<project|global>,note=<text>]:doc'","'--reminder[Reminder entry at=<iso|relative>|date=<iso|relative>,text=<text>|title=<text>]:reminder'","'--event[Event entry start=<iso|relative>,end=<iso|relative>,recur_*]:event'","'--type-option[Type option key=value or key=<name>,value=<value>]:type_option'","'--unset[Clear scalar metadata field by name]:field'","'--replace-files[Atomically replace linked files with provided --file values]'","'--replace-docs[Atomically replace linked docs with provided --doc values]'","'--clear-deps[Clear dependency entries]'","'--clear-comments[Clear comments]'","'--clear-notes[Clear notes]'","'--clear-learnings[Clear learnings]'","'--clear-files[Clear linked files]'","'--clear-tests[Clear linked tests]'","'--clear-docs[Clear linked docs]'","'--clear-reminders[Clear reminders]'","'--clear-events[Clear events]'","'--clear-type-options[Clear type options]'"];function Wd(e){return An([...e==="reminder"?["'--at[Reminder time (default +1d)]:at'","'--text[Reminder text (defaults to title)]:text'"]:["'--start[Start time (ISO, now, or relative)]:start'","'--duration[Duration from start (default 1h)]:duration'","'--end[End time (overrides --duration)]:end'","'--location[Location]:location'","'--timezone[IANA timezone]:timezone'","'--all-day[Mark as an all-day event]'"],"'--parent[Parent item id]:parent'","'--allow-missing-parent[Permit a parent id that does not exist yet]'","'--tags[Comma-separated tags]:tags'","'(-p --priority)'{-p,--priority}'[Priority (0-4)]:(0 1 2 3 4)'","'(-b --body)'{-b,--body}'[Item body]:body'","'(-d --description)'{-d,--description}'[Short description]:description'","'--author[Mutation author]:author'","'--message[History message]:message'","'--json[Output JSON]'","'--quiet[Suppress stdout]'"],{trailingContinuation:!1})}function Kd(e,t,n,o){return An([`'--filter-status[Filter by status before ${e}]:(${t})'`,`'--filter-type[Filter by type before ${e}]:(${n})'`,`'--filter-tag[Filter by tag before ${e}]:(${o})'`,`'--filter-priority[Filter by priority before ${e}]:(0 1 2 3 4)'`,"'--filter-deadline-before[Filter by deadline upper bound]:deadline'","'--filter-deadline-after[Filter by deadline lower bound]:deadline'","'--filter-updated-after[Filter by updated_at lower bound (ISO/relative)]:timestamp'","'--filter-updated-before[Filter by updated_at upper bound (ISO/relative)]:timestamp'","'--filter-created-after[Filter by created_at lower bound (ISO/relative)]:timestamp'","'--filter-created-before[Filter by created_at upper bound (ISO/relative)]:timestamp'",`'--filter-assignee[Filter by assignee before ${e}]:assignee'`,"'--filter-assignee-filter[Filter assignee presence]:(assigned unassigned)'","'--filter-parent[Filter by parent item ID]:parent'","'--filter-sprint[Filter by sprint]:sprint'","'--filter-release[Filter by release]:release'"])}function je(e,t){let n=el(t).map(s=>s.slice(2));if(e.length===0||n.length===0)return"";let o=[];for(let s of e)for(let r of n)o.push(`complete -c pm -n '__fish_seen_subcommand_from ${s}' -l ${r} -d 'Runtime schema field flag' -r`);return`${o.join(`
75
+ `}function Cn(e,t={}){let n=t.trailingContinuation??!0,o=e.length-1;return e.map((s,r)=>` ${s}${n||r!==o?" \\":""}`).join(`
76
+ `)}function Y_(){return ml.map(([e,t])=>` '${e}:${t}'`).join(`
77
+ `)}function J_(){return ml.filter(([e])=>e!=="help").map(([e,t])=>{let n=V_.get(e)??t;return`complete -c pm -n __pm_no_subcommand -a ${e.padEnd(16)} -d '${n}'`}).join(`
78
+ `)}function rl(e){let t=["reviewer-missing[Select only items missing reviewer]","risk-missing[Select only items missing risk]","confidence-missing[Select only items missing confidence]","sprint-missing[Select only items missing sprint]","release-missing[Select only items missing release]"],n=e.includeContentMissingAliases===!0?["files-missing[Alias for --no-files]","docs-missing[Alias for --no-docs]"]:[],o=[["has-notes[Select only items that have notes]","no-notes[Select only items with no notes]"],["has-learnings[Select only items that have learnings]","no-learnings[Select only items with no learnings]"],["has-files[Select only items that have linked files]","no-files[Select only items with no linked files]"],["has-docs[Select only items that have linked docs]","no-docs[Select only items with no linked docs]"],["has-tests[Select only items that have linked tests]","no-tests[Select only items with no linked tests]"],["has-comments[Select only items that have comments]","no-comments[Select only items with no comments]"],["has-deps[Select only items that have dependencies]","no-deps[Select only items with no dependencies]"],["has-body[Select only items with non-empty body]","empty-body[Select only items with empty body]"],["has-linked-command[Select only items that have a linked command]","no-linked-command[Select only items with no linked command]"]];return Cn([...[...t,...n].map(s=>`'--${e.missingPrefix}${s}'`),...o.flatMap(([s,r])=>[`'--${e.pairedPrefix}${s}'`,`'--${e.pairedPrefix}${r}'`])])}var X_=["'--comment[Comment seed author=<value>,created_at=<iso|now>,text=<value>]:comment'","'--note[Note seed author=<value>,created_at=<iso|now>,text=<value>]:note'","'--learning[Learning seed author=<value>,created_at=<iso|now>,text=<value>]:learning'","'--file[Linked file path=<value>,scope=<project|global>,note=<text>]:file'","'--test[Linked test command=<value>,path=<value>,scope=<project|global>]:test'","'--doc[Linked doc path=<value>,scope=<project|global>,note=<text>]:doc'","'--reminder[Reminder entry at=<iso|relative>|date=<iso|relative>,text=<text>|title=<text>]:reminder'","'--event[Event entry start=<iso|relative>,end=<iso|relative>,recur_*]:event'","'--type-option[Type option key=value or key=<name>,value=<value>]:type_option'","'--unset[Clear scalar metadata field by name]:field'","'--replace-files[Atomically replace linked files with provided --file values]'","'--replace-docs[Atomically replace linked docs with provided --doc values]'","'--clear-deps[Clear dependency entries]'","'--clear-comments[Clear comments]'","'--clear-notes[Clear notes]'","'--clear-learnings[Clear learnings]'","'--clear-files[Clear linked files]'","'--clear-tests[Clear linked tests]'","'--clear-docs[Clear linked docs]'","'--clear-reminders[Clear reminders]'","'--clear-events[Clear events]'","'--clear-type-options[Clear type options]'"];function il(e){return Cn([...e==="reminder"?["'--at[Reminder time (default +1d)]:at'","'--text[Reminder text (defaults to title)]:text'"]:["'--start[Start time (ISO, now, or relative)]:start'","'--duration[Duration from start (default 1h)]:duration'","'--end[End time (overrides --duration)]:end'","'--location[Location]:location'","'--timezone[IANA timezone]:timezone'","'--all-day[Mark as an all-day event]'"],"'--parent[Parent item id]:parent'","'--allow-missing-parent[Permit a parent id that does not exist yet]'","'--tags[Comma-separated tags]:tags'","'(-p --priority)'{-p,--priority}'[Priority (0-4)]:(0 1 2 3 4)'","'(-b --body)'{-b,--body}'[Item body]:body'","'(-d --description)'{-d,--description}'[Short description]:description'","'--author[Mutation author]:author'","'--message[History message]:message'","'--json[Output JSON]'","'--quiet[Suppress stdout]'"],{trailingContinuation:!1})}function al(e,t,n,o){return Cn([`'--filter-status[Filter by status before ${e}]:(${t})'`,`'--filter-type[Filter by type before ${e}]:(${n})'`,`'--filter-tag[Filter by tag before ${e}]:(${o})'`,`'--filter-priority[Filter by priority before ${e}]:(0 1 2 3 4)'`,"'--filter-deadline-before[Filter by deadline upper bound]:deadline'","'--filter-deadline-after[Filter by deadline lower bound]:deadline'","'--filter-updated-after[Filter by updated_at lower bound (ISO/relative)]:timestamp'","'--filter-updated-before[Filter by updated_at upper bound (ISO/relative)]:timestamp'","'--filter-created-after[Filter by created_at lower bound (ISO/relative)]:timestamp'","'--filter-created-before[Filter by created_at upper bound (ISO/relative)]:timestamp'",`'--filter-assignee[Filter by assignee before ${e}]:assignee'`,"'--filter-assignee-filter[Filter assignee presence]:(assigned unassigned)'","'--filter-parent[Filter by parent item ID]:parent'","'--filter-sprint[Filter by sprint]:sprint'","'--filter-release[Filter by release]:release'"])}function Ge(e,t){let n=ul(t).map(s=>s.slice(2));if(e.length===0||n.length===0)return"";let o=[];for(let s of e)for(let r of n)o.push(`complete -c pm -n '__fish_seen_subcommand_from ${s}' -l ${r} -d 'Runtime schema field flag' -r`);return`${o.join(`
79
79
  `)}
80
- `}function Yd(e,t,n){let o=e.toUpperCase(),s=`PM_COMPLETION_${o}_CACHE`,r=`PM_COMPLETION_${o}_CACHE_TS`,i=`PM_COMPLETION_${o}_TTL`,a=Qd(n);return[`_pm_completion_${e}_choices() {`," local now ttl cache_ts resolved",' now="$(date +%s 2>/dev/null || echo 0)"',` ttl="\${${i}:-120}"`,` cache_ts="\${${r}:-0}"`,` if [[ -n "\${${s}:-}" && "$now" -ne 0 && $((now - cache_ts)) -lt "$ttl" ]]; then`,` printf '%s\\n' "$${s}"`," return 0"," fi",` resolved="$(pm ${t} 2>/dev/null)"`,' if [[ -z "$resolved" ]]; then',` resolved="${a}"`," fi",` ${s}="$resolved"`,` ${r}="$now"`,` printf '%s\\n' "$${s}"`,"}"]}function Jd(e,t,n){let o=e.toUpperCase(),s=`PM_COMPLETION_${o}_CACHE`,r=`PM_COMPLETION_${o}_CACHE_TS`,i=`PM_COMPLETION_${o}_TTL`,a=Qd(n);return`
80
+ `}function cl(e,t,n){let o=e.toUpperCase(),s=`PM_COMPLETION_${o}_CACHE`,r=`PM_COMPLETION_${o}_CACHE_TS`,i=`PM_COMPLETION_${o}_TTL`,a=pl(n);return[`_pm_completion_${e}_choices() {`," local now ttl cache_ts resolved",' now="$(date +%s 2>/dev/null || echo 0)"',` ttl="\${${i}:-120}"`,` cache_ts="\${${r}:-0}"`,` if [[ -n "\${${s}:-}" && "$now" -ne 0 && $((now - cache_ts)) -lt "$ttl" ]]; then`,` printf '%s\\n' "$${s}"`," return 0"," fi",` resolved="$(pm ${t} 2>/dev/null)"`,' if [[ -z "$resolved" ]]; then',` resolved="${a}"`," fi",` ${s}="$resolved"`,` ${r}="$now"`,` printf '%s\\n' "$${s}"`,"}"]}function dl(e,t,n){let o=e.toUpperCase(),s=`PM_COMPLETION_${o}_CACHE`,r=`PM_COMPLETION_${o}_CACHE_TS`,i=`PM_COMPLETION_${o}_TTL`,a=pl(n);return`
81
81
  _pm_${e}_choices() {
82
82
  local now ttl cache_ts resolved
83
83
  now=\${EPOCHSECONDS:-0}
@@ -95,7 +95,7 @@ _pm_${e}_choices() {
95
95
  ${r}="$now"
96
96
  print -r -- "$${s}"
97
97
  }
98
- `}function Xd(e,t,n){let o=e.toUpperCase(),s=n.replaceAll("'","\\'");return`
98
+ `}function ll(e,t,n){let o=e.toUpperCase(),s=n.replaceAll("'","\\'");return`
99
99
  function __pm_${e}_choices
100
100
  set -l now (date +%s ^/dev/null)
101
101
  if test -z "$now"
@@ -120,8 +120,8 @@ function __pm_${e}_choices
120
120
  set -gx PM_COMPLETION_${o}_CACHE_TS $now
121
121
  printf '%s\\n' $resolved
122
122
  end
123
- `}function M_(e=[],t=[],n=!1,o={}){let s=Es.join(" "),r=e.length===0,i=Rs(e,o),a=As(o),c=st(t),d=De(Yf,o.command_flags?.list),l=De(n_,o.command_flags?.create),m=De(s_,o.command_flags?.update),f=De(r_,o.command_flags?.["update-many"]),_=De(g_,o.command_flags?.search),y=De(l_,o.command_flags?.calendar),w=De(m_,o.command_flags?.context),g=n||t.length>0,h=k=>`$(compgen -W "${k}" -- "$cur")`;return["# bash completion for pm",`# Source this file or add 'eval "$(pm completion bash)"' to ~/.bashrc`,"",...r?[...Yd("type","completion-types",i),""]:[],...Yd("status","completion-statuses",a),"","_pm_completion() {"," local cur prev words cword"," _init_completion 2>/dev/null || {",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"'," cword=$COMP_CWORD"," }",""," if [[ $cword -eq 1 ]]; then",` COMPREPLY=(${h(s)})`," return 0"," fi","",' if [[ "$prev" == "--type" ]]; then',r?' COMPREPLY=($(compgen -W "$(_pm_completion_type_choices)" -- "$cur"))':` COMPREPLY=(${h(i)})`," return 0"," fi","",' if [[ "$prev" == "--status" ]]; then',' COMPREPLY=($(compgen -W "$(_pm_completion_status_choices)" -- "$cur"))'," return 0"," fi","",...g?[' if [[ "$prev" == "--tag" || "$prev" == "--tags" ]]; then',` COMPREPLY=(${h(c)})`," return 0"," fi"]:[' if [[ "$prev" == "--tag" || "$prev" == "--tags" ]]; then'," local now ttl cache_ts tag_values",' now="$(date +%s 2>/dev/null || echo 0)"',' ttl="${PM_COMPLETION_TAG_TTL:-120}"',' cache_ts="${PM_COMPLETION_TAG_CACHE_TS:-0}"',' tag_values="${PM_COMPLETION_TAG_CACHE:-}"',' if [[ -z "$tag_values" || "$now" -eq 0 || $((now - cache_ts)) -ge "$ttl" ]]; then',' tag_values="$(pm completion-tags 2>/dev/null)"',' PM_COMPLETION_TAG_CACHE="$tag_values"',' PM_COMPLETION_TAG_CACHE_TS="$now"'," fi",' COMPREPLY=($(compgen -W "$tag_values" -- "$cur"))'," return 0"," fi"],"",' local cmd="${COMP_WORDS[1]}"',"",' case "$cmd" in'," list|list-all|list-draft|list-open|list-in-progress|list-blocked|list-closed|list-canceled)",` COMPREPLY=(${h(d)})`," ;;"," aggregate)",` COMPREPLY=(${h(Jf)})`," ;;"," duplicates)",` COMPREPLY=(${h(f_)})`," ;;"," create)",` COMPREPLY=(${h(l)})`," ;;"," copy)",` COMPREPLY=(${h(Zf)})`," ;;"," focus)",` COMPREPLY=(${h(Qf)})`," ;;"," update)",` COMPREPLY=(${h(m)})`," ;;"," update-many)",` COMPREPLY=(${h(f)})`," ;;"," calendar|cal)",` COMPREPLY=(${h(y)})`," ;;"," context|ctx)",` COMPREPLY=(${h(w)})`," ;;"," next)",` COMPREPLY=(${h(p_)})`," ;;"," guide)",` COMPREPLY=(${h(`${h_} ${xs}`)})`," ;;"," search)",` COMPREPLY=(${h(_)})`," ;;"," reindex)",` COMPREPLY=(${h("--mode --progress --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," init)",` COMPREPLY=(${h(`${b_} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)})`," ;;"," config)",` COMPREPLY=(${h("--criterion --clear-criteria --format --policy --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," extension)",` COMPREPLY=(${h(`${Rn} ${E_}`)})`," ;;"," package|packages)",` COMPREPLY=(${h(`${Rn} ${x_}`)})`," ;;"," comments)",` COMPREPLY=(${h("--add --body --stdin --file --edit --delete --limit --full-history --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," notes)",` COMPREPLY=(${h("--add --add-json --stdin --file --edit --delete --limit --since --event-type --include-meta --full-history --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," learnings)",` COMPREPLY=(${h("--add --stdin --file --edit --delete --limit --full-history --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," files)",` COMPREPLY=(${h("discover lookup --add --add-glob --remove --migrate --list --apply --note --append-stable --validate-paths --scope --limit --offset --no-truncate --strict-read --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," docs)",` COMPREPLY=(${h("--add --add-glob --remove --migrate --note --validate-paths --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," append)",` COMPREPLY=(${h(Xf)})`," ;;"," deps)",` COMPREPLY=(${h(u_)})`," ;;"," graph)",` COMPREPLY=(${h(`ancestors descendants predecessors successors paths impact analyze audit communities redundancy dominators slack centrality articulation plan index ${__}`)})`," ;;"," test)",` COMPREPLY=(${h("--add --add-json --remove --list --run --match --only-index --only-last --background --timeout --progress --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 --auto-pm-context --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," test-all)",` COMPREPLY=(${h("--status --limit --offset --background --timeout --progress --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 --auto-pm-context --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," test-runs)",` COMPREPLY=(${h("list status logs stop resume --status --limit --stream --tail --force --author --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," validate)",` COMPREPLY=(${h("--check-metadata --metadata-profile --check-resolution --check-lifecycle --check-stale-blockers --dependency-cycle-severity --parent-cycle-severity --check-files --scan-mode --include-pm-internals --verbose-file-lists --verbose-diagnostics --all-affected-ids --strict-exit --fail-on-warn --fix-hints --auto-fix --dry-run --fix-scope --prune-missing --check-history-drift --check-command-references --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," health)",` COMPREPLY=(${h(y_)})`," ;;"," history)",` COMPREPLY=(${h(c_)})`," ;;"," events)",` COMPREPLY=(${h(d_)})`," ;;"," history-compact)",` COMPREPLY=(${h("--before --ids --all-over --closed --all-streams --min-entries --dry-run --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," history-author-acknowledge)",` COMPREPLY=(${h("--event --all-actionable --attributed-author --reviewer --reason --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," get)",` COMPREPLY=(${h(o_)})`," ;;"," history-redact)",` COMPREPLY=(${h("--literal --regex --replacement --dry-run --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," history-repair)",` COMPREPLY=(${h("--all --dry-run --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," schema)",` COMPREPLY=(${h("list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status --description --default-status --folder --alias --role --order --type --commands --cli-flag --required --required-on-create --no-allow-unset --required-types --infer --min-count --apply --to --migration-id --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," profile)",` COMPREPLY=(${h("list show apply lint agile ops research --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," plan)",` COMPREPLY=(${h(`${k_} ${v_}`)})`," ;;"," activity)",` COMPREPLY=(${h(a_)})`," ;;"," contracts)",` COMPREPLY=(${h(w_)})`," ;;"," gc)",` COMPREPLY=(${h("--dry-run --scope --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," stats)",` COMPREPLY=(${h("--storage --metadata-coverage --field-utilization --by-assignee --by-tag --by-priority --tag-prefix --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," close|close-task)",` COMPREPLY=(${h(C_)})`," ;;"," close-many)",` COMPREPLY=(${h(i_)})`," ;;"," release)",` COMPREPLY=(${h(T_)})`," ;;"," delete)",` COMPREPLY=(${h(A_)})`," ;;"," claim|restore|start-task|pause-task)",` COMPREPLY=(${h(R_)})`," ;;"," meet|event)",` COMPREPLY=(${h(e_)})`," ;;"," remind)",` COMPREPLY=(${h(t_)})`," ;;"," completion)",` COMPREPLY=(${h(I_)})`," ;;"," templates)",` COMPREPLY=(${h("save list show")})`," ;;"," *)",` COMPREPLY=(${h($_)})`," ;;"," esac"," return 0","}","","complete -F _pm_completion pm"].join(`
124
- `)}function D_(e=[],t=[],n=!1,o={}){let s=e.length===0,r=Rs(e,o),i=As(o),a=s?'${(f)"$(_pm_type_choices)"}':r,c='${(f)"$(_pm_status_choices)"}',d=xs,l=st(t),m=n||t.length>0,f=m?l:'${(f)"$(_pm_tag_choices)"}',_=xt(o.command_flags?.list),y=xt(o.command_flags?.create),w=xt(o.command_flags?.search),g=xt(o.command_flags?.calendar),h=xt(o.command_flags?.context),k=Vd({missingPrefix:"filter-",pairedPrefix:"",includeContentMissingAliases:!0}),I=Vd({missingPrefix:"filter-",pairedPrefix:"filter-"}),P=An(N_),C=m?"":`
123
+ `}function Z_(e=[],t=[],n=!1,o={}){let s=As.join(" "),r=e.length===0,i=Ts(e,o),a=Os(o),c=it(t),d=Ue(l_,o.command_flags?.list),l=Ue(g_,o.command_flags?.create),m=Ue(b_,o.command_flags?.update),f=Ue(w_,o.command_flags?.["update-many"]),_=Ue($_,o.command_flags?.search),y=Ue(E_,o.command_flags?.calendar),w=Ue(x_,o.command_flags?.context),g=n||t.length>0,h=S=>`$(compgen -W "${S}" -- "$cur")`;return["# bash completion for pm",`# Source this file or add 'eval "$(pm completion bash)"' to ~/.bashrc`,"",...r?[...cl("type","completion-types",i),""]:[],...cl("status","completion-statuses",a),"","_pm_completion() {"," local cur prev words cword"," _init_completion 2>/dev/null || {",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"'," cword=$COMP_CWORD"," }",""," if [[ $cword -eq 1 ]]; then",` COMPREPLY=(${h(s)})`," return 0"," fi","",' if [[ "$prev" == "--type" ]]; then',r?' COMPREPLY=($(compgen -W "$(_pm_completion_type_choices)" -- "$cur"))':` COMPREPLY=(${h(i)})`," return 0"," fi","",' if [[ "$prev" == "--status" ]]; then',' COMPREPLY=($(compgen -W "$(_pm_completion_status_choices)" -- "$cur"))'," return 0"," fi","",...g?[' if [[ "$prev" == "--tag" || "$prev" == "--tags" ]]; then',` COMPREPLY=(${h(c)})`," return 0"," fi"]:[' if [[ "$prev" == "--tag" || "$prev" == "--tags" ]]; then'," local now ttl cache_ts tag_values",' now="$(date +%s 2>/dev/null || echo 0)"',' ttl="${PM_COMPLETION_TAG_TTL:-120}"',' cache_ts="${PM_COMPLETION_TAG_CACHE_TS:-0}"',' tag_values="${PM_COMPLETION_TAG_CACHE:-}"',' if [[ -z "$tag_values" || "$now" -eq 0 || $((now - cache_ts)) -ge "$ttl" ]]; then',' tag_values="$(pm completion-tags 2>/dev/null)"',' PM_COMPLETION_TAG_CACHE="$tag_values"',' PM_COMPLETION_TAG_CACHE_TS="$now"'," fi",' COMPREPLY=($(compgen -W "$tag_values" -- "$cur"))'," return 0"," fi"],"",' local cmd="${COMP_WORDS[1]}"',"",' case "$cmd" in'," list|list-all|list-draft|list-open|list-in-progress|list-blocked|list-closed|list-canceled)",` COMPREPLY=(${h(d)})`," ;;"," aggregate)",` COMPREPLY=(${h(m_)})`," ;;"," duplicates)",` COMPREPLY=(${h(C_)})`," ;;"," create)",` COMPREPLY=(${h(l)})`," ;;"," copy)",` COMPREPLY=(${h(u_)})`," ;;"," focus)",` COMPREPLY=(${h(f_)})`," ;;"," update)",` COMPREPLY=(${h(m)})`," ;;"," update-many)",` COMPREPLY=(${h(f)})`," ;;"," calendar|cal)",` COMPREPLY=(${h(y)})`," ;;"," context|ctx)",` COMPREPLY=(${h(w)})`," ;;"," next)",` COMPREPLY=(${h(R_)})`," ;;"," guide)",` COMPREPLY=(${h(`${O_} ${Cs}`)})`," ;;"," search)",` COMPREPLY=(${h(_)})`," ;;"," reindex)",` COMPREPLY=(${h("--mode --progress --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," init)",` COMPREPLY=(${h(`${F_} --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help`)})`," ;;"," config)",` COMPREPLY=(${h("--criterion --clear-criteria --format --policy --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," extension)",` COMPREPLY=(${h(`${An} ${U_}`)})`," ;;"," package|packages)",` COMPREPLY=(${h(`${An} ${G_}`)})`," ;;"," comments)",` COMPREPLY=(${h("--add --body --stdin --file --edit --delete --limit --full-history --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," notes)",` COMPREPLY=(${h("--add --add-json --stdin --file --edit --delete --limit --since --event-type --include-meta --full-history --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," learnings)",` COMPREPLY=(${h("--add --stdin --file --edit --delete --limit --full-history --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," files)",` COMPREPLY=(${h("discover lookup --add --add-glob --remove --migrate --list --apply --note --append-stable --validate-paths --scope --limit --offset --no-truncate --strict-read --explain --lines --decision-depth --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," docs)",` COMPREPLY=(${h("--add --add-glob --remove --migrate --note --validate-paths --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," append)",` COMPREPLY=(${h(p_)})`," ;;"," deps)",` COMPREPLY=(${h(A_)})`," ;;"," graph)",` COMPREPLY=(${h(`ancestors descendants predecessors successors paths impact analyze audit communities redundancy dominators slack centrality articulation plan index ${T_}`)})`," ;;"," test)",` COMPREPLY=(${h("--add --add-json --remove --list --run --match --only-index --only-last --background --timeout --progress --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 --auto-pm-context --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," test-all)",` COMPREPLY=(${h("--status --limit --offset --background --timeout --progress --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 --auto-pm-context --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," test-runs)",` COMPREPLY=(${h("list status logs stop resume --status --limit --stream --tail --force --author --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," validate)",` COMPREPLY=(${h("--check-metadata --metadata-profile --check-resolution --check-lifecycle --check-stale-blockers --dependency-cycle-severity --parent-cycle-severity --check-files --scan-mode --include-pm-internals --verbose-file-lists --verbose-diagnostics --all-affected-ids --strict-exit --fail-on-warn --fix-hints --auto-fix --dry-run --fix-scope --prune-missing --check-history-drift --check-command-references --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," health)",` COMPREPLY=(${h(P_)})`," ;;"," history)",` COMPREPLY=(${h(S_)})`," ;;"," events)",` COMPREPLY=(${h(I_)})`," ;;"," history-compact)",` COMPREPLY=(${h("--before --ids --all-over --closed --all-streams --min-entries --dry-run --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," history-author-acknowledge)",` COMPREPLY=(${h("--event --all-actionable --attributed-author --reviewer --reason --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," get)",` COMPREPLY=(${h(y_)})`," ;;"," history-redact)",` COMPREPLY=(${h("--literal --regex --replacement --dry-run --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," history-repair)",` COMPREPLY=(${h("--all --dry-run --author --message --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," schema)",` COMPREPLY=(${h("list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status --description --default-status --folder --alias --role --order --type --commands --cli-flag --required --required-on-create --no-allow-unset --required-types --infer --min-count --apply --to --migration-id --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," profile)",` COMPREPLY=(${h("list show apply lint agile ops research --dry-run --author --force --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," plan)",` COMPREPLY=(${h(`${M_} ${N_}`)})`," ;;"," activity)",` COMPREPLY=(${h(k_)})`," ;;"," contracts)",` COMPREPLY=(${h(L_)})`," ;;"," gc)",` COMPREPLY=(${h("--dry-run --scope --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," stats)",` COMPREPLY=(${h("--storage --metadata-coverage --field-utilization --by-assignee --by-tag --by-priority --tag-prefix --json --quiet --no-changed-fields --pm-path --path --no-extensions --no-pager --profile --help")})`," ;;"," close|close-task)",` COMPREPLY=(${h(H_)})`," ;;"," close-many)",` COMPREPLY=(${h(v_)})`," ;;"," release)",` COMPREPLY=(${h(B_)})`," ;;"," delete)",` COMPREPLY=(${h(z_)})`," ;;"," claim|restore|start-task|pause-task)",` COMPREPLY=(${h(q_)})`," ;;"," meet|event)",` COMPREPLY=(${h(__)})`," ;;"," remind)",` COMPREPLY=(${h(h_)})`," ;;"," completion)",` COMPREPLY=(${h(j_)})`," ;;"," templates)",` COMPREPLY=(${h("save list show")})`," ;;"," *)",` COMPREPLY=(${h(W_)})`," ;;"," esac"," return 0","}","","complete -F _pm_completion pm"].join(`
124
+ `)}function Q_(e=[],t=[],n=!1,o={}){let s=e.length===0,r=Ts(e,o),i=Os(o),a=s?'${(f)"$(_pm_type_choices)"}':r,c='${(f)"$(_pm_status_choices)"}',d=Cs,l=it(t),m=n||t.length>0,f=m?l:'${(f)"$(_pm_tag_choices)"}',_=Rt(o.command_flags?.list),y=Rt(o.command_flags?.create),w=Rt(o.command_flags?.search),g=Rt(o.command_flags?.calendar),h=Rt(o.command_flags?.context),S=rl({missingPrefix:"filter-",pairedPrefix:"",includeContentMissingAliases:!0}),E=rl({missingPrefix:"filter-",pairedPrefix:"filter-"}),F=Cn(X_),T=m?"":`
125
125
  _pm_tag_choices() {
126
126
  local now ttl cache_ts
127
127
  now=\${EPOCHSECONDS:-0}
@@ -142,13 +142,13 @@ _pm_tag_choices() {
142
142
  _pm_commands() {
143
143
  local -a commands
144
144
  commands=(
145
- ${F_()}
145
+ ${Y_()}
146
146
  )
147
147
  _describe 'command' commands
148
148
  }
149
- ${C}
150
- ${s?Jd("type","completion-types",r):""}
151
- ${Jd("status","completion-statuses",i)}
149
+ ${T}
150
+ ${s?dl("type","completion-types",r):""}
151
+ ${dl("status","completion-statuses",i)}
152
152
 
153
153
  _pm() {
154
154
  local context state line
@@ -192,7 +192,7 @@ _pm() {
192
192
  '--assignee-filter[Filter assignee presence]:(assigned unassigned)' \\
193
193
  '--sprint[Filter by sprint]:sprint' \\
194
194
  '--release[Filter by release]:release' \\
195
- ${k}
195
+ ${S}
196
196
  '--limit[Limit returned item count]:number' \\
197
197
  '--offset[Skip the first n matching rows before limit]:number' \\
198
198
  '--no-truncate[Return every matched row, overriding --limit]' \\
@@ -294,11 +294,11 @@ ${y} '--json[Output JSON]' \\
294
294
  ;;
295
295
  meet|event)
296
296
  _arguments \\
297
- ${Wd("event")}
297
+ ${il("event")}
298
298
  ;;
299
299
  remind)
300
300
  _arguments \\
301
- ${Wd("reminder")}
301
+ ${il("reminder")}
302
302
  ;;
303
303
  update)
304
304
  _arguments \\
@@ -317,7 +317,7 @@ ${Wd("reminder")}
317
317
  '--remove-ac[Remove one acceptance criterion by exact text]:criteria' \\
318
318
  '--expected[Short alias for --expected-result]:expected_result' \\
319
319
  '--actual[Short alias for --actual-result]:actual_result' \\
320
- ${P}
320
+ ${F}
321
321
  '--author[Mutation author]:author' \\
322
322
  '--message[History message]:message' \\
323
323
  '--force[Force override]' \\
@@ -326,12 +326,12 @@ ${P}
326
326
  ;;
327
327
  update-many)
328
328
  _arguments \\
329
- ${Kd("applying updates",c,a,f)}
329
+ ${al("applying updates",c,a,f)}
330
330
  '--filter-ac-missing[Select only items missing acceptance_criteria]' \\
331
331
  '--filter-estimates-missing[Select only items missing estimated_minutes]' \\
332
332
  '--filter-resolution-missing[Select only terminal items missing resolution]' \\
333
333
  '--filter-metadata-missing[Select only items missing any tracked metadata]' \\
334
- ${I}
334
+ ${E}
335
335
  '--ids[Explicit comma-separated ID allowlist]:ids' \\
336
336
  '--limit[Limit matched item count]:number' \\
337
337
  '--offset[Skip first n matched rows]:number' \\
@@ -382,7 +382,7 @@ ${I}
382
382
  '--dep-remove[Dependency removal selector id=<id>,kind=<kind>,author=<author>,created_at=<timestamp>]:dep_remove' \\
383
383
  '--replace-deps[Atomically replace dependencies with provided --dep values]' \\
384
384
  '--replace-tests[Atomically replace linked tests with provided --test values]' \\
385
- ${P}
385
+ ${F}
386
386
  '--author[Mutation author]:author' \\
387
387
  '--message[History message]:message' \\
388
388
  '--force[Force override]' \\
@@ -391,8 +391,8 @@ ${P}
391
391
  ;;
392
392
  close-many)
393
393
  _arguments \\
394
- ${Kd("closing",c,a,f)}
395
- ${I}
394
+ ${al("closing",c,a,f)}
395
+ ${E}
396
396
  '--ids[Explicit comma-separated ID allowlist]:ids' \\
397
397
  '--limit[Limit matched item count]:number' \\
398
398
  '--offset[Skip first n matched rows]:number' \\
@@ -505,7 +505,7 @@ ${h} '--json[Output JSON]' \\
505
505
  '--sprint[Filter by sprint]:value' \\
506
506
  '--release[Filter by release]:value' \\
507
507
  '--parent[Filter by parent item ID]:value' \\
508
- ${k}
508
+ ${S}
509
509
  ${w} '--json[Output JSON]' \\
510
510
  '--quiet[Suppress stdout]'
511
511
  ;;
@@ -784,6 +784,9 @@ ${w} '--json[Output JSON]' \\
784
784
  '--offset[Skip the first lookup matches]:number' \\
785
785
  '--no-truncate[Return every lookup match]' \\
786
786
  '--strict-read[Require authoritative source reads]' \\
787
+ '--explain[Include ranked source-to-work rationale]' \\
788
+ '--lines[Attribute an inclusive source line range]:start_end' \\
789
+ '--decision-depth[Maximum governing-decision relationship depth]:number' \\
787
790
  '--author[Mutation author]:author' \\
788
791
  '--message[History message]:message' \\
789
792
  '--force[Force override]' \\
@@ -1121,7 +1124,7 @@ ${w} '--json[Output JSON]' \\
1121
1124
  esac
1122
1125
  }
1123
1126
 
1124
- compdef _pm pm`}function j_(e=[],t=[],n=!1,o={}){let s=Es.filter(Q=>Q==="list"||Q.startsWith("list-")),r=s.join(" "),i=Es.join(" "),a=e.length===0,c=Rs(e,o),d=As(o),l=a?"(__pm_type_choices)":c,m="(__pm_status_choices)",f=xs,_=st(t),y=n||t.length>0,w=y?`'${_}'`:"'(__pm_tag_choices)'",g=je(s,o.command_flags?.list),h=je(["create"],o.command_flags?.create),k=je(["update"],o.command_flags?.update),I=je(["update-many"],o.command_flags?.["update-many"]),P=je(["search"],o.command_flags?.search),C=je(["calendar","cal"],o.command_flags?.calendar),j=je(["context","ctx"],o.command_flags?.context);return`# Fish shell completion for pm
1127
+ compdef _pm pm`}function eh(e=[],t=[],n=!1,o={}){let s=As.filter(Z=>Z==="list"||Z.startsWith("list-")),r=s.join(" "),i=As.join(" "),a=e.length===0,c=Ts(e,o),d=Os(o),l=a?"(__pm_type_choices)":c,m="(__pm_status_choices)",f=Cs,_=it(t),y=n||t.length>0,w=y?`'${_}'`:"'(__pm_tag_choices)'",g=Ge(s,o.command_flags?.list),h=Ge(["create"],o.command_flags?.create),S=Ge(["update"],o.command_flags?.update),E=Ge(["update-many"],o.command_flags?.["update-many"]),F=Ge(["search"],o.command_flags?.search),T=Ge(["calendar","cal"],o.command_flags?.calendar),j=Ge(["context","ctx"],o.command_flags?.context);return`# Fish shell completion for pm
1125
1128
  # Save to ~/.config/fish/completions/pm.fish
1126
1129
  # or run: pm completion fish > ~/.config/fish/completions/pm.fish
1127
1130
 
@@ -1174,11 +1177,11 @@ function __pm_tag_choices
1174
1177
  ' $resolved
1175
1178
  end
1176
1179
  `}
1177
- ${a?Xd("type","completion-types",c):""}
1178
- ${Xd("status","completion-statuses",d)}
1180
+ ${a?ll("type","completion-types",c):""}
1181
+ ${ll("status","completion-statuses",d)}
1179
1182
 
1180
1183
  # Subcommands
1181
- ${L_()}
1184
+ ${J_()}
1182
1185
 
1183
1186
  # list* flags
1184
1187
  for list_cmd in ${r}
@@ -1343,7 +1346,7 @@ complete -c pm -n '__fish_seen_subcommand_from update' -l clear-type-options
1343
1346
  complete -c pm -n '__fish_seen_subcommand_from update' -l author -d 'Mutation author' -r
1344
1347
  complete -c pm -n '__fish_seen_subcommand_from update' -l message -d 'History message' -r
1345
1348
  complete -c pm -n '__fish_seen_subcommand_from update' -l force -d 'Force override'
1346
- ${k}
1349
+ ${S}
1347
1350
 
1348
1351
  # update-many flags
1349
1352
  complete -c pm -n '__fish_seen_subcommand_from update-many' -l filter-status -d 'Filter by status before applying updates' -r -a '${m}'
@@ -1463,7 +1466,7 @@ complete -c pm -n '__fish_seen_subcommand_from update-many' -l clear-type-option
1463
1466
  complete -c pm -n '__fish_seen_subcommand_from update-many' -l author -d 'Mutation author' -r
1464
1467
  complete -c pm -n '__fish_seen_subcommand_from update-many' -l message -d 'History message' -r
1465
1468
  complete -c pm -n '__fish_seen_subcommand_from update-many' -l force -d 'Force override'
1466
- ${I}
1469
+ ${E}
1467
1470
 
1468
1471
  # files flags
1469
1472
  complete -c pm -n '__fish_seen_subcommand_from files' -a 'discover lookup' -d 'Linked-file subcommand'
@@ -1481,6 +1484,9 @@ complete -c pm -n '__fish_seen_subcommand_from files' -l limit -d 'Maximum looku
1481
1484
  complete -c pm -n '__fish_seen_subcommand_from files' -l offset -d 'Skip the first lookup matches' -r
1482
1485
  complete -c pm -n '__fish_seen_subcommand_from files' -l no-truncate -d 'Return every lookup match'
1483
1486
  complete -c pm -n '__fish_seen_subcommand_from files' -l strict-read -d 'Require authoritative source reads'
1487
+ complete -c pm -n '__fish_seen_subcommand_from files' -l explain -d 'Include ranked source-to-work rationale'
1488
+ complete -c pm -n '__fish_seen_subcommand_from files' -l lines -d 'Attribute an inclusive source line range' -r
1489
+ complete -c pm -n '__fish_seen_subcommand_from files' -l decision-depth -d 'Maximum governing-decision relationship depth' -r
1484
1490
 
1485
1491
 
1486
1492
  # search flags
@@ -1529,7 +1535,7 @@ complete -c pm -n '__fish_seen_subcommand_from search' -l has-body -d
1529
1535
  complete -c pm -n '__fish_seen_subcommand_from search' -l empty-body -d 'Select only items with empty body'
1530
1536
  complete -c pm -n '__fish_seen_subcommand_from search' -l has-linked-command -d 'Select only items that have a linked command'
1531
1537
  complete -c pm -n '__fish_seen_subcommand_from search' -l no-linked-command -d 'Select only items with no linked command'
1532
- ${P}
1538
+ ${F}
1533
1539
 
1534
1540
  # calendar flags
1535
1541
  complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l view -d 'Calendar view' -r -a 'agenda day week month'
@@ -1552,7 +1558,7 @@ complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l recurrence-lookb
1552
1558
  complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l occurrence-limit -d 'Cap occurrences per recurring event' -r
1553
1559
  complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l limit -d 'Limit returned events' -r
1554
1560
  complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l format -d 'Output override' -r -a 'markdown toon json'
1555
- ${C}
1561
+ ${T}
1556
1562
 
1557
1563
  # context flags
1558
1564
  complete -c pm -n '__fish_seen_subcommand_from context ctx' -l date -d 'Anchor date/time (ISO/date string or relative)' -r
@@ -1990,7 +1996,7 @@ complete -c pm -n '__fish_seen_subcommand_from completion' -a 'bash zsh fish' -d
1990
1996
  complete -c pm -n '__fish_seen_subcommand_from templates' -a 'save list show' -d 'Templates command'
1991
1997
 
1992
1998
  # extension lifecycle flags
1993
- complete -c pm -n '__fish_seen_subcommand_from extension' -a '${Rn}' -d 'Extension action subcommand'
1999
+ complete -c pm -n '__fish_seen_subcommand_from extension' -a '${An}' -d 'Extension action subcommand'
1994
2000
  complete -c pm -n '__fish_seen_subcommand_from extension' -l init -d 'Generate starter extension scaffold'
1995
2001
  complete -c pm -n '__fish_seen_subcommand_from extension' -l scaffold -d 'Alias for --init'
1996
2002
  complete -c pm -n '__fish_seen_subcommand_from extension' -l capability -d 'Capability the init scaffold targets' -r -a '${bt.join(" ")}'
@@ -2026,7 +2032,7 @@ complete -c pm -n '__fish_seen_subcommand_from extension' -l fail-on-warn -d 'Al
2026
2032
 
2027
2033
  # package lifecycle flags
2028
2034
  for package_cmd in package packages
2029
- complete -c pm -n "__fish_seen_subcommand_from $package_cmd" -a '${Rn}' -d 'Package action subcommand'
2035
+ complete -c pm -n "__fish_seen_subcommand_from $package_cmd" -a '${An}' -d 'Package action subcommand'
2030
2036
  complete -c pm -n "__fish_seen_subcommand_from $package_cmd" -l init -d 'Generate starter package scaffold'
2031
2037
  complete -c pm -n "__fish_seen_subcommand_from $package_cmd" -l scaffold -d 'Alias for --init'
2032
2038
  complete -c pm -n "__fish_seen_subcommand_from $package_cmd" -l capability -d 'Capability the init scaffold targets' -r -a '${bt.join(" ")}'
@@ -2060,9 +2066,9 @@ for package_cmd in package packages
2060
2066
  complete -c pm -n "__fish_seen_subcommand_from $package_cmd" -l ignore-global -d 'Alias for --isolated'
2061
2067
  complete -c pm -n "__fish_seen_subcommand_from $package_cmd" -l strict-exit -d 'Return non-zero exit when doctor warnings are present'
2062
2068
  complete -c pm -n "__fish_seen_subcommand_from $package_cmd" -l fail-on-warn -d 'Alias for --strict-exit (doctor)'
2063
- end`}var U_={bash:'Add to ~/.bashrc or ~/.bash_profile: eval "$(pm completion bash)"',zsh:'Add to ~/.zshrc: eval "$(pm completion zsh)"',fish:"Run: pm completion fish > ~/.config/fish/completions/pm.fish"};function G_(e,t=[],n=[],o=!1,s={}){let r=e.trim().toLowerCase();if(!Bd.includes(r))throw new p(`Unknown shell: "${e}". Supported shells: ${Bd.join(", ")}.`,u.USAGE);let i=r,a;return i==="bash"?a=M_(t,n,o,s):i==="zsh"?a=D_(t,n,o,s):a=j_(t,n,o,s),{shell:i,script:a,setup_hint:U_[i]}}import q_ from"node:fs/promises";import Rt 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]="fc124f85-8d28-508b-a3f7-2fe767382197")}catch{}})();var Cs="index/manifest.json",Ts="search/embeddings.jsonl",z_="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function H_(e){return e.progress===!0||process.stderr.isTTY===!0}function M(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
2064
- `)}catch{}}function B_(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new p("Reindex mode must be one of keyword|semantic|hybrid",u.USAGE)}async function V_(e,t,n,o){let s=[];return{candidates:await Nr(e,t,n,s,o),warnings:s}}async function $s(e,t,n,o,s){let r=Ge(T()),i=[];for(let a of t)if(!(s&&!s.has(a.metadata.id))){if(typeof a.body=="string"){i.push({metadata:a.metadata,body:a.body});continue}try{let c=await q_.readFile(a.item_path,"utf8"),d=Mt(c,{format:a.item_format,schema:n,extensionFieldNames:r,onWarning:l=>o.push(l)});i.push({metadata:a.metadata,body:d.body})}catch{o.push(`item_list_item_read_failed:${Rt.relative(e,a.item_path)}`),i.push({metadata:a.metadata,body:""})}}return i}function W_(e,t,n){let o=e.metadata;return{id:o.id,mode:t,updated_at:o.updated_at,corpus:Ur(e,{fields:n})}}var rt=Us;function K_(e){let t=T(),n=rt(e.search?.provider);if(!n)return null;let o=nr(t,n);if(!o)return null;let s=o.runtime_definition??o.definition,r=rt(s.name)??rt(o.definition.name);if(!r)return null;let i=s.embedBatch,a=s.embed_batch,c=s.embed,d=typeof i=="function"?i:typeof a=="function"?a:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:r,embedBatch:d,embed:l}}function Y_(e){let t=T(),n=rt(e.vector_store?.adapter);if(!n)return null;let o=or(t,n);if(!o)return null;let s=o.runtime_definition??o.definition,r=rt(s.name)??rt(o.definition.name);if(!r)return null;let i=s.upsert,a=s.delete;return{adapterName:r,...typeof i=="function"?{upsert:i}:{},...typeof a=="function"?{delete:a}:{}}}function Os(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new p(`Invalid vector returned by ${t}`,u.GENERIC_FAILURE);return e}async function J_(e,t,n){let o=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let r=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:o}));if(!Array.isArray(r))throw new p(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,u.GENERIC_FAILURE);return r.map((i,a)=>Os(i,`extension search provider "${e.name}" embedBatch output at index ${a}`))}if(!e.embed)throw new p(`Extension search provider "${e.name}" does not implement embed/embedBatch`,u.GENERIC_FAILURE);let s=[];for(let[r,i]of n.entries()){let a=await Promise.resolve(e.embed({input:i,settings:t,model:o}));s.push(Os(a,`extension search provider "${e.name}" embed output at index ${r}`))}return s}function tl(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function nl(e,t,n){let o=n?ht(n.name,tl(e)):t?ht(t.name,t.model):null;if(!o)throw new p("No embedding identity available for semantic reindex mode",u.USAGE);return o}function X_(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,o)=>n.localeCompare(o))}async function ol(e,t,n,o,s,r,i,a){let c=o?.name??n?.name,d=Gr(c,e.search.embedding_corpus_max_characters).maxCharacters,l=Xn(e),m=s.map(y=>qr(y,{providerName:c,maxCharacters:d,fields:l})),f=[],_=null;if(o)try{f=await J_(o,e,m),_=ht(o.name,tl(e))}catch(y){if(!n)throw new p(`Extension search provider "${o.name}" failed to generate embeddings: ${y instanceof Error?y.message:String(y)}`,u.GENERIC_FAILURE);r.push(`Extension search provider "${o.name}" failed; falling back to built-in provider (${y instanceof Error?y.message:String(y)})`)}if(f.length===0){if(!n)throw new p(`No embedding executor available for reindex mode '${t}'`,u.USAGE);let y=await zr(n,e,m,{onProgress:w=>{w.phase==="complete"&&(i.batches_completed=w.batch_index),M(a,`embedding_batch_${w.phase} batch=${w.batch_index}/${w.batch_total} size=${w.batch_size} completed_inputs=${w.completed_inputs}/${w.total_inputs}`)}});r.push(...y.warnings),f=y.vectors,_=ht(n.name,n.model)}if(M(a,`embedding_complete vectors=${f.length}`),f.length!==s.length)throw new p(`Embedding output size mismatch (expected ${s.length}, received ${f.length})`,u.GENERIC_FAILURE);if(!_)throw new p(`No embedding identity available for reindex mode '${t}'`,u.USAGE);return{vectors:f,embeddingIdentity:_}}async function Z_(e,t,n,o,s,r){let i=Object.keys(n);if(t){if(i.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:i.sort((a,c)=>a.localeCompare(c)),settings:o}))}catch(a){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${a instanceof Error?a.message:String(a)}`,u.GENERIC_FAILURE)}else i.length>0&&s.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${i.length}`);if(!e)return}e&&await Wr(e,i,{},r)}async function sl(e,t,n,o,s){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:o}))}catch(r){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${r instanceof Error?r.message:String(r)}`,u.GENERIC_FAILURE)}else s.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Vr(e,n)}}function Q_(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function eh(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(o=>({id:o.metadata.id,type:o.metadata.type,status:o.metadata.status,priority:o.metadata.priority,updated_at:o.metadata.updated_at}))}}function th(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Jn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new p(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,u.USAGE);let n=Hr(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new p(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,u.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function nh(e){let t=F(e.settings,T()),n=await V_(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(o=>({metadata:o.metadata,body:typeof o.body=="string"?o.body:""}))}}async function oh(e){let t=await Qn(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return nl(e.settings,Jn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Wt(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(z_))}async function sh(e){let t=await Qn(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=nl(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),o=new Set(e.metadataDocuments.map(d=>d.metadata.id)),s=X_(t.entries,o),r=Wt(t.embedding,n);e.forceFullSemantic&&!r&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let i=e.forceFullSemantic||r?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),a=new Set(i.map(d=>d.metadata.id)),c=a.size>0?await $s(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,a):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:s,resetRequired:r,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function rh(e){let t=new Set(e.metadataDocuments.map(s=>s.metadata.id)),n=await $s(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,M(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let o=await ol(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...o,staleDocuments:n,vectorDimension:Zn(o.vectors,"Reindex embeddings")}}async function ih(e){let t=await ol(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,o=t.embeddingIdentity,s=Zn(n,"Reindex embeddings");if(!(!e.resetRequired&&(Wt(e.ledgerEmbedding,o)||Yr(e.ledgerEmbedding,s))))return{vectors:n,embeddingIdentity:o,staleDocuments:e.staleDocuments,vectorDimension:s,resetRequired:e.resetRequired};let i=await rh(e);return n=i.vectors,o=i.embeddingIdentity,s=i.vectorDimension,{vectors:n,embeddingIdentity:o,staleDocuments:i.staleDocuments,vectorDimension:s,resetRequired:!0}}async function ah(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(M(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new p(`Extension vector adapter "${t}" does not support upserting vectors.`,u.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,M(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof p)throw t;if(!e.activeVectorStore)throw new p(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,u.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),M(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){M(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Br(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,M(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new p(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,u.USAGE)}function ch(e,t){return e.map((n,o)=>({id:n.metadata.id,vector:Os(t[o],`reindex embeddings output at index ${o}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function dh(e){M(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await ih({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(M(e.progressEnabled,"vector_reset_start"),await Z_(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),M(e.progressEnabled,"vector_reset_complete")):await sl(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=ch(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await ah({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Kr(t.embeddingIdentity,t.vectorDimension)}}async function lh(e){let t=await sh(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(r=>[r.metadata.id,r.metadata.updated_at]));if(M(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return M(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await sl(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let o=await dh({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let s=new Map(o.staleDocuments.map(r=>[r.metadata.id,r]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(r=>s.get(r.metadata.id)??r),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:o.embeddingMetadata}}async function mh(e){let t=Rt.join(e.pmRoot,Cs),n=Rt.join(e.pmRoot,Ts),o=Xn(e.settings),s=e.documentsForKeywordArtifacts.map(i=>JSON.stringify(W_(i,e.mode,o))).join(`
2065
- `);M(e.progressEnabled,"writing keyword artifacts"),await V(t,`${JSON.stringify(e.manifest,null,2)}
2066
- `),await V(n,`${s}
2067
- `);let r=[];if(e.mode!=="keyword")try{M(e.progressEnabled,"writing vectorization status ledger"),await Jr(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(i){r.push(`search_vectorization_status_ledger_write_failed:${i instanceof Error?i.message:String(i)}`)}return r}async function ph(e,t){let n=B_(e.mode),o=H_(e),s=e.full===!0;M(o,`start mode=${n}`);let r=x(process.cwd(),t.path);if(!await E(A(r)))throw new p(`Tracker is not initialized at ${r}. Run pm init first.`,u.NOT_FOUND);let i=Fr(await R(r)).settings,a=null;try{a=await Y(r,Lr,i.locks.ttl_seconds,O(void 0,"pm-reindex"),!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms)}catch(c){throw c instanceof p&&c.exitCode===u.CONFLICT?new p("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",u.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=K_(i),d=Y_(i),l=th({requestedMode:n,pmRoot:r,settings:i,extensionEmbedding:c,extensionVectorAdapter:d}),m=n;M(o,"loading item corpus");let f=await nh({pmRoot:r,settings:i}),_=f.warnings,{documentCandidates:y,metadataDocuments:w}=f;M(o,`loaded_items=${w.length}`);let g=S(),h=eh(m,g,w),k=Rt.join(r,Cs),I=Rt.join(r,Ts),P=m==="keyword"?await $s(r,y,i.schema,_):w,C=[],j={},U=null,Q=Q_(m);if(m==="keyword"&&await oh({pmRoot:r,settings:i,forceFullSemantic:s,extensionEmbedding:c,reindexWarnings:_}),m!=="keyword"){let oe=await lh({pmRoot:r,settings:i,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:y,metadataDocuments:w,documentsForKeywordArtifacts:P,forceFullSemantic:s,reindexWarnings:_,semanticWarnings:C,semanticSummary:Q,progressEnabled:o});P=oe.documentsForKeywordArtifacts,j=oe.vectorizationLedgerEntries,U=oe.vectorizationEmbeddingMetadata}let de=await mh({pmRoot:r,mode:m,manifest:h,documentsForKeywordArtifacts:P,settings:i,vectorizationLedgerEntries:j,vectorizationEmbeddingMetadata:U,progressEnabled:o}),Ie=[...await N({path:k,scope:"project",op:"reindex:manifest"}),...await N({path:I,scope:"project",op:"reindex:embeddings"}),...await er({mode:m,total_items:w.length})];return M(o,"done"),{ok:!0,mode:m,total_items:w.length,semantic:Q,artifacts:{manifest:Cs,embeddings:Ts},warnings:[..._,...C,...de,...Ie],generated_at:g}}finally{await a?.()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c8f2b88e-1883-5744-868b-3a16f3814813")}catch{}})();var dl=Symbol("pm.active-extension-host-context");function Z(e){return{fullChangedFields:!0,options:e}}var v=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[dl]=!0,n}run(t,n={}){return vh({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}list(t={}){return this.runTyped("list",{options:t})}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},o={}){return this.runTyped("graph",{subcommand:t,...n,options:o})}append(t,n,o={}){return this.runTyped("append",{id:t,...Z({...o,body:n})})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,o,s,r={}){return this.runTyped("config",{scope:t,configAction:n,...o===void 0?{}:{key:o},...s===void 0?{}:{value:s},options:r})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,o,s){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-field",to:n,...s?{fieldTypeScope:s}:{}}})}schemaRemapStatus(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,o={},s,r){return this.runTyped("plan",{...n===void 0?{}:{id:n},...s===void 0?{}:{stepRef:s},...r===void 0?{}:{reorderTo:r},options:{...o,subcommand:t}})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,o){return this.plan("update-step",t,o,n)}planCompleteStep(t,n,o={}){return this.plan("complete-step",t,o,n)}planBlockStep(t,n,o){return this.plan("block-step",t,o,n)}planReorderStep(t,n,o,s={}){return this.plan("reorder-step",t,s,n,o)}planRemoveStep(t,n,o={}){return this.plan("remove-step",t,o,n)}planLink(t,n,o){return this.plan("link",t,o,n)}planUnlink(t,n,o){return this.plan("unlink",t,o,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Z(t))}update(t,n={}){return this.runTyped("update",{id:t,...Z(n)})}close(t,n,o={}){return this.runTyped("close",{id:t,reason:n,...Z(o)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Z(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Z(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Z(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Z(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Z(n)})}restore(t,n,o={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...o,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Z(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Z(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Z(n)})}closeTask(t,n,o={}){return this.runTyped("close-task",{id:t,reason:n,...Z(o)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function hI(e={},t={}){return new v(t).context(e)}function gI(e={},t={}){return new v(t).list(e)}function yI(e,t={},n={}){return new v(n).search(e,t)}function bI(e,t={},n={}){return new v(n).get(e,t)}function wI(e={},t={}){return new v(t).next(e)}function vI(e={},t={}){return new v(t).aggregate(e)}function kI(e={},t={}){return new v(t).stats(e)}function SI(e={},t={}){return new v(t).duplicates(e)}function II(e,t={},n={}){return new v(n).comments(e,t)}function EI(e,t={},n={}){return new v(n).notes(e,t)}function xI(e,t={},n={}){return new v(n).learnings(e,t)}function RI(e,t={},n={}){return new v(n).files(e,t)}function AI(e,t={},n={}){return new v(n).filesDiscover(e,t)}function CI(e,t={}){return new v(t).filesLookup(e)}function TI(e,t={},n={}){return new v(n).docs(e,t)}function OI(e,t={},n={}){return new v(n).deps(e,t)}function $I(e,t={},n={},o={}){return new v(o).graph(e,t,n)}function PI(e,t,n={},o={}){return new v(o).append(e,t,n)}function FI(e,t={},n={}){return new v(n).init(e,t)}function LI(e,t,n,o,s={},r={}){return new v(r).config(e,t,n,o,s)}function NI(e,t={},n={}){return new v(n).schema(e,t)}function MI(e={}){return new v(e).schemaList()}function DI(e,t={}){return new v(t).schemaShow(e)}function jI(e,t={},n={}){return new v(n).schemaAddType(e,t)}function UI(e,t={},n={}){return new v(n).schemaRemoveType(e,t)}function GI(e,t={},n={}){return new v(n).schemaAddStatus(e,t)}function qI(e,t={},n={}){return new v(n).schemaRemoveStatus(e,t)}function zI(e,t={},n={}){return new v(n).schemaAddField(e,t)}function HI(e,t={},n={}){return new v(n).schemaRemoveField(e,t)}function BI(e={}){return new v(e).schemaListFields()}function VI(e,t={}){return new v(t).schemaShowField(e)}function WI(e,t={},n={}){return new v(n).schemaApplyPreset(e,t)}function KI(e={},t={}){return new v(t).schemaInferTypes(e)}function YI(e,t,n,o={}){return new v(o).schemaRenameType(e,t,n)}function JI(e,t,n,o,s={}){return new v(s).schemaRenameField(e,t,n,o)}function XI(e,t,n,o={}){return new v(o).schemaRemapStatus(e,t,n)}function ZI(e,t={}){return new v(t).schemaShowStatus(e)}function QI(e,t={},n={}){return new v(n).profile(e,t)}function eE(e={}){return new v(e).profileList()}function tE(e,t={}){return new v(t).profileShow(e)}function nE(e,t={},n={}){return new v(n).profileApply(e,t)}function oE(e,t={}){return new v(t).profileLint(e)}function sE(e={},t={}){return new v(t).validate(e)}function rE(e={},t={}){return new v(t).health(e)}function iE(e={},t={}){return new v(t).gc(e)}function aE(e,t,n={}){return new v(n).historyRedact(e,t)}function cE(e,t={},n={}){return new v(n).historyRepair(e,t)}function dE(e={},t={}){return new v(t).historyRepairAll(e)}function lE(e,t={},n={}){return new v(n).historyCompact(e,t)}function mE(e,t={}){return new v(t).historyCompactBulk(e)}function pE(e={},t={}){return new v(t).create(e)}function uE(e,t={},n={}){return new v(n).update(e,t)}function fE(e,t,n={},o={}){return new v(o).close(e,t,n)}function _E(e,t={},n={}){return new v(n).claim(e,t)}function hE(e={},t={}){return new v(t).claimNext(e)}function gE(e,t={},n={}){return new v(n).release(e,t)}function yE(e,t={},n={}){return new v(n).copy(e,t)}function bE(e,t={},n={}){return new v(n).delete(e,t)}function wE(e,t,n={},o={}){return new v(o).restore(e,t,n)}function vE(e,t={},n={}){return new v(n).focus(e,t)}function kE(e,t={},n={}){return new v(n).startTask(e,t)}function SE(e,t={},n={}){return new v(n).pauseTask(e,t)}function IE(e,t,n={},o={}){return new v(o).closeTask(e,t,n)}function EE(e,t={},n={}){return new v(n).extension(e,t)}function xE(e={},t={}){return new v(t).extensionList(e)}function RE(e,t={},n={}){return new v(n).extensionActivate(e,t)}function AE(e,t={},n={}){return new v(n).extensionDeactivate(e,t)}function CE(e,t={},n={}){return new v(n).package(e,t)}function TE(e={},t={}){return new v(t).packageList(e)}function OE(e,t={},n={}){return new v(n).packageInstall(e,t)}function $E(e,t={},n={}){return new v(n).packageUninstall(e,t)}function PE(e={},t={}){return new v(t).packageDoctor(e)}function FE(e,t={},n={}){return new v(n).packageManage(e,t)}function LE(e,t={},n={}){return new v(n).packageDescribe(e,t)}function NE(e={},t={}){return new v(t).packageReload(e)}function ME(e={},t={}){return new v(t).packageCatalog(e)}function DE(e,t={},n={}){return new v(n).packageActivate(e,t)}function jE(e,t={},n={}){return new v(n).packageDeactivate(e,t)}function UE(e,t={},n={}){return new v(n).upgrade(e,t)}function fh(e,t,n){return JSON.stringify([rl.resolve(e),rl.resolve(n??process.cwd()),t.extensions.enabled,t.extensions.disabled,t.extensions.policy])}async function _h(e,t,n){let o=fh(e,t,n);return rc(o,()=>tg(e,t,n))}async function GE(e,t={}){let n=await R(e),o=t.extensionRegistrations??(t.noExtensions===!0?null:await _h(e,n,t.cwd)),s=F(n,o),r=q(n.schema),i=mt(n.schema);return{types:[...s.types],statuses:r.definitions.map(a=>a.id),openStatus:r.open_status,closeStatus:r.close_status,canceledStatus:r.canceled_status,fields:oc(i.definitions),extensionCommands:sc(o?.commands??[])}}async function qE(e,t={}){let n=typeof e=="string"?{...t,pmRoot:e}:e??t,o={json:!0,quiet:n.quiet??!0,noExtensions:n.noExtensions??!1,noPager:!0,profile:n.profile??!1,path:n.pmRoot};return bo(n,o)}function ce(e,t){let n=b(e,t);if(!n)throw new p(`Missing required argument: ${t}`,64);return n}var il=Xs(),ll=new uh;function Cn(){Un(zs()),Gn(Hs()),qn(Bs()),zn(Vs()),Hn(Ws()),Bn(Ks()),Vn(Ys())}async function ml(e,t,n,o){return Zs(()=>t===void 0?il.read(()=>al(e,n,o)):il.write(()=>gh(t,()=>al(e,n,o))))}async function zE(e,t){let n=e.cwd,o=n??process.cwd();return ml(cn({path:e.path,noExtensions:e.noExtensions}),n,o,()=>ll.run(!0,t))}async function al(e,t,n){let o=x(t,e.path);if(e.noExtensions)return Cn(),Oo({pmRoot:o},()=>n(null));if(!await E(A(o)))return Cn(),n(null);let s=null,r;try{let i=await R(o),a=await Mn({pmRoot:o,settings:i,cwd:t,noExtensions:!1}),c=await jn({...a,loaded:a.loaded});r={loadResult:a,activationResult:c},Un(c.hooks),Gn(c.commands),qn(c.parsers),zn(c.preflight),Hn(c.services),Bn(c.renderers),Vn(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:o,packages:a.loaded}}catch(i){Cn(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Oo({pmRoot:o,packages:s?.packages},()=>n(s))}finally{Cn(),r&&await Dn(r.loadResult,r.activationResult).catch(()=>{})}}async function hh(e,t,n,o,s){if(!s)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let r=we(e),a=s.registrations.commands.find(d=>we(d.action)===r)?.command??s.commands.handlers.find(d=>we(d.command)===r)?.command;if(!a)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let c=await tr({command:po(a),args:W(n.args??t.args),options:uo(t,n),global:o,pm_root:s.pmRoot,sdk:mc(s.pmRoot,v.forActiveExtensionHost({pmRoot:s.pmRoot,author:typeof o.author=="string"&&o.author.trim()?o.author.trim():"pm-extension"}))});if(!c.handled){let d=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new p(`Unsupported native pm action: ${e}${d}`,u.USAGE)}return c.result}async function gh(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var yh=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function bh(e){let t=ce(e,"action"),n=we(t),o=it(Io,n),s=o?.action??n,r={...e,action:s};return o?.options!==void 0&&(r.options={...o.options,...On(e.options)}),s==="package"&&(r.options={...On(r.options),vocabulary:"package"}),{action:s,args:r}}function wh(e){return!yh.has(we(e))}async function vh(e){let t=bh(e),n=cn(t.args),o=wh(t.action),s=b(t.args,"cwd"),r=s??process.cwd();try{return e[dl]===!0||ll.getStore()===!0?await cl(t.action,t.args,n,null):await ml(n,s,r,i=>cl(t.action,t.args,n,i))}finally{o&&So()}}function it(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Tn(e){return b(e.args,"target")??b(e.options,"target")}function L(e,t=e.options){return e.id??ce(t,"id")}async function kh(e){let t=He("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),ko(await ye(b(e.args,"status")??b(t,"status"),t,e.global),t)}async function Sh(e){let t=He("search",e.options);return t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.compact=!0),ko(await yo(ce(e.args,"query"),t,e.global),t)}async function Ih(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options);return me(await yt(o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Eh(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options),s={...o,...o.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...o.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return me(await Jo(L(e,s),s,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function xh(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options);return me(await be(L(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Rh(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options),s=b(e.args,"reason")??b(e.args,"text")??b(o,"reason")??b(o,"text");return me(await Je(L(e,o),s,o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Ah(e){let t=en(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),bc(L(e),t,e.global)}function Ch(e){let t=W(e.options.lookupPath);if(t&&t.length>0)return ho({paths:t,scope:e.options.scope==="project"||e.options.scope==="global"?e.options.scope:void 0,limit:B(e.options.limit,"files lookup limit"),offset:B(e.options.offset,"files lookup offset"),noTruncate:e.options.noTruncate===!0,strictRead:e.options.strictRead===!0},e.global);let n=L(e);return e.options.discover===!0?go(n,mo(e.options),e.global):Oa(n,dn(e.options),e.global)}function Th(e){return Ja({subcommand:b(e.args,"subcommand")??b(e.options,"subcommand"),limit:ya(e.args,e.options)},e.global)}function Oh(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Ca(e.global,t)}function $h(e){let t=b(e.args,"configAction")??b(e.options,"configAction")??b(e.options,"action");if(t===void 0)throw new p("Missing required argument: configAction",64);return Fa(b(e.args,"scope")??b(e.options,"scope")??"project",t,b(e.args,"key")??b(e.options,"key"),e.options,e.global,b(e.args,"value")??b(e.options,"value"))}function Ph(e){let t={...e.options};return t.compact===void 0&&(t.compact=t.full!==!0),delete t.full,Ui(t,e.global)}function Fh(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new p(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new p(`${t} must be a finite integer.`,64);let o=Number.parseInt(n,10);if(!Number.isInteger(o))throw new p(`${t} must be a finite integer.`,64);return o}}function Lh(e){let t=b(e.args,"subcommand")??ce(e.options,"subcommand"),n=e.options;return Dc({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:Nh(e),reorderTo:Fh(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function Nh(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function Mh(e){let t=b(e.args,"subcommand")??ce(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:b(e.args,"name")??b(e.options,"name"),author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:W(n)}}function Dh(e){let{ctx:t,subcommand:n,name:o,author:s,force:r}=e,a=it({list:()=>sa(t.global),show:()=>ra(o,t.global),"show-status":()=>ia(o,t.global),"list-fields":()=>da(t.global),"show-field":()=>la(o,t.global),"remove-type":()=>ea(o,{author:s,force:r},t.global),"remove-field":()=>ca(o,{author:s,force:r},t.global),"remove-status":()=>oa(o,{author:s,force:r},t.global),"apply-preset":()=>ma(b(t.args,"typePreset")??b(t.options,"typePreset"),{author:s,force:r},t.global)},n);return a?a():null}function jh(e){let{ctx:t,name:n,author:o,force:s,aliases:r}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return aa(n,{type:b(t.args,"fieldType")??b(t.options,"fieldType"),commands:i===void 0?void 0:W(i),description:b(t.args,"description")??b(t.options,"description"),cliFlag:b(t.args,"cliFlag")??b(t.options,"cliFlag"),alias:r,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:W(a),author:o,force:s},t.global)}function Uh(e){let{ctx:t,name:n,author:o,force:s,aliases:r}=e,i=t.args.role??t.options.role;return na(n,{role:i===void 0?void 0:W(i),alias:r,description:b(t.args,"description")??b(t.options,"description"),order:B(t.args.order??t.options.order,"schema add-status order"),author:o,force:s},t.global)}function Gh(e){let{ctx:t,name:n,author:o,force:s,aliases:r}=e;return Qi(n,{description:b(t.args,"description")??b(t.options,"description"),defaultStatus:b(t.args,"defaultStatus")??b(t.args,"default_status")??b(t.options,"defaultStatus")??b(t.options,"default_status"),folder:b(t.args,"folder")??b(t.options,"folder"),alias:r,author:o,force:s},t.global)}function qh(e){let{ctx:t,subcommand:n,name:o,author:s,force:r}=e,i=b(t.args,"to")??ce(t.options,"to"),a=b(t.args,"migrationId")??b(t.args,"migration_id")??b(t.options,"migrationId")??b(t.options,"migration_id"),c=b(t.args,"fieldTypeScope")??b(t.options,"fieldTypeScope")??b(t.args,"type")??b(t.options,"type"),d=n==="rename-type"?{kind:"rename-type",from:o??"",to:i}:n==="rename-field"?{kind:"rename-field",from:o??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:o??"",to:i};return Zi(d,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:r},t.global)}function zh(e){let t=Mh(e),n=Dh(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return qh(t);if(t.subcommand==="add-field")return jh(t);if(t.subcommand==="add-status")return Uh(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?pa({minCount:B(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):Gh(t);throw new p(`Unknown pm schema subcommand "${t.subcommand}". Allowed: add-type, remove-type, add-status, remove-status, add-field, remove-field, rename-type, rename-field, remap-status, list-fields, show-field, apply-preset, list, show, show-status`,64)}function Hh(e){let t=b(e.args,"subcommand")??ce(e.options,"subcommand"),n=t.trim().toLowerCase(),o=b(e.args,"name")??b(e.options,"name"),r=it({list:()=>Sd(),show:()=>Id(o),lint:()=>Ed(o),apply:()=>xd(o,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!r)throw new p(`Unknown pm profile subcommand "${t}". Allowed: list, show, apply, lint`,64);return r()}async function Bh(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options);return me(await fc(L(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Vh(e){let{changedFields:t,runnerOptions:n}=ie(e.args,e.options);return me(await xc(_o(n),e.global),{changedFields:t})}async function Wh(e){let{changedFields:t,runnerOptions:n}=ie(e.args,e.options),o=b(e.args,"reason"),s=o!==void 0&&n.reason===void 0?{...n,reason:o}:{...n};return e.force&&s.force===void 0&&(s.force=!0),me(await yc(fo(s),e.global),{changedFields:t})}async function Kh(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options),s=b(o,"target")??ce(e.args,"target");return me(await Le(L(e,o),s,o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function pl(e){let t={...e};return delete t.assignee,t}async function Yh(e){let t=x(process.cwd(),e.global.path),n=await R(t),o=Qa(q(n.schema)),s=L(e),r=await io(s,e.force,e.global,e.options),i=await be(s,{...pl(e.options),status:o,force:e.force},e.global);return{id:s,action:"start_task",claim:r,update:i}}async function Jh(e){let t=x(process.cwd(),e.global.path),n=await R(t),o=L(e),s=q(n.schema).open_status,r=await be(o,{...pl(e.options),status:s,force:e.force},e.global),i=await nn(o,e.force,e.global,e.options);return{id:o,action:"pause_task",update:r,release:i}}async function Xh(e){let t=L(e),n=b(e.args,"reason")??b(e.args,"text")??b(e.options,"reason")??b(e.options,"text"),o=await Je(t,n,{...e.options,force:e.force},e.global),s=await nn(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:o,release:s}}function Zh(e){let t={...e.args,...e.options};return Ka(ce(t,"subcommand"),b(t,"id")??e.id,b(t,"target"),va(t),e.global)}function Qh(e){return Sa(x(process.cwd(),e.global.path),{...e.args,...e.options})}var ul={init:e=>La(b(e.args,"prefix"),e.global,e.options),context:e=>so(He("context",e.options),e.global),next:e=>ro(He("next",e.options),e.global),eval:ed,events:td,merge:nd,workspace:od,meet:bn,event:bn,remind:bn,list:kh,get:e=>co(L(e),e.global,He("get",e.options)),search:Sh,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:W(e.options.status);return vo(e.global,{...t.length===0?{}:{status:t},since:b(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:B(e.options.limit,"limit")})},create:Ih,copy:Eh,focus:e=>Zo(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:xh,restore:Kh,claim:e=>e.options.next===!0||e.args.next===!0?Hi(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):io(L(e),e.force,e.global,e.options),release:e=>nn(L(e),e.force,e.global,e.options),"start-task":Yh,"pause-task":Jh,"close-task":Xh,close:Rh,comments:Ah,notes:e=>vc(L(e),en(e.options),e.global),learnings:e=>wc(L(e),en(e.options),e.global),files:Ch,docs:e=>Ta(L(e),dn(e.options),e.global),test:e=>Xa(L(e),e.options,e.global),"test-all":e=>Za(e.options,e.global),telemetry:Th,validate:e=>ln(e.options,e.global,{runUpdate:(t,n,o)=>be(t,n,o)}),health:Oh,contracts:e=>bo(e.options,e.global),config:$h,activity:Ph,aggregate:e=>oo(e.options,e.global),extension:e=>an(Tn(e),e.options,e.global),package:e=>an(Tn(e),e.options,e.global),install:e=>an(Tn(e),{...e.options,install:!0},e.global),upgrade:e=>ua(Tn(e),e.options,e.global),delete:e=>Xo(L(e),e.options,e.global),deps:e=>Wa(L(e),e.options,e.global),graph:Zh,"files-discover":e=>go(L(e),e.options,e.global),"files-lookup":e=>ho({paths:W(e.options.paths),scope:e.options.scope==="project"||e.options.scope==="global"?e.options.scope:void 0,limit:B(e.options.limit,"files lookup limit"),offset:B(e.options.offset,"files lookup offset"),noTruncate:e.options.noTruncate===!0,strictRead:e.options.strictRead===!0},e.global),history:e=>Bi(L(e),e.options,e.global),"history-redact":e=>Ni(L(e),e.options,e.global),"history-repair":$d,"history-compact":Pd,"history-author-acknowledge":Qh,plan:Lh,schema:zh,profile:Hh,stats:e=>wo(e.global,Fd(e.options)),append:Bh,"update-many":Vh,"close-many":Wh,gc:e=>fa(e.global,e.options)};function HE(e=hr){return e.map(t=>{let n=we(t),o=it(Io,n),s=o?.action??n,r=it(ul,s)!==void 0;return{action:t,resolved_action:s,covered:r,route:r?o?"alias":"native":"missing"}})}async function cl(e,t,n,o){let s=lo(t,e);pr(e,s);let r={action:e,args:t,options:s,id:b(t,"id"),force:t.force===!0||s.force===!0,global:n,activeExtensions:o},i=it(ul,e),a=i?await i(r):await hh(e,t,s,n,o);return fr(e,s,a)}var eg={closeManyOptionsFromFlat:fo,extensionOptionsFromArgs:uo,globalOptions:cn,mutationListOptions:wa,normalizeActionName:we,normalizeCommandPath:po,normalizeMcpUpdateOptions:ka,normalizeMcpOptionsArrays:ba,optionsWithAuthor:lo,readRequiredString:ce,readScalarString:ha,readScalarStringAllowBlank:ga,readStringArray:W,updateManyOptionsFromFlat:_o,withAddNoteOption:dn,withFilesDiscoveryOptions:mo,withMutationCompaction:ie};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=eg);async function tg(e,t,n){let o=await Mn({pmRoot:e,settings:t,cwd:n??process.cwd(),noExtensions:!1}),s=await jn(o);try{return s.registrations}finally{try{await Dn(o,s)}catch{}}}export{ac as a,kl as b,Eo as c,kt as d,fn as e,mc as f,cg as g,dg as h,lg as i,mg as j,pg as k,tc as l,ug as m,gl as n,So as o,To as p,pc as q,Pl as r,Ll as s,Nl as t,Oo as u,fc as v,Le as w,yc as x,bc as y,wc as z,vc as A,xc as B,Ry as C,Rc as D,qo as E,Dc as F,Jo as G,Xo as H,Zo as I,Uc as J,Gc as K,Jp as L,Xp as M,Hc as N,Vc as O,Wc as P,Kc as Q,mu as R,It as S,Zc as T,yn as U,Qc as V,tt as W,as as X,gu as Y,Hb as Z,Bb as _,ls as $,rd as aa,aw as ba,cw as ca,ad as da,ld as ea,xw as fa,Fu as ga,gs as ha,Nu as ia,Mu as ja,Jw as ka,Sd as la,Id as ma,Ed as na,xd as oa,Xw as pa,Zw as qa,Qw as ra,ev as sa,ys as ta,of as ua,Td as va,Od as wa,lf as xa,mf as ya,pf as za,z as Aa,uf as Ba,ff as Ca,_f as Da,hf as Ea,ws as Fa,Ld as Ga,ot as Ha,bs as Ia,Nd as Ja,gf as Ka,Md as La,yf as Ma,bf as Na,wf as Oa,vf as Pa,kf as Qa,Cf as Ra,Gd as Sa,Tf as Ta,Mf as Ua,Hf as Va,Vf as Wa,G_ as Xa,ph as Ya,v as Za,hI as _a,gI as $a,yI as ab,bI as bb,wI as cb,vI as db,kI as eb,SI as fb,II as gb,EI as hb,xI as ib,RI as jb,AI as kb,CI as lb,TI as mb,OI as nb,$I as ob,PI as pb,FI as qb,LI as rb,NI as sb,MI as tb,DI as ub,jI as vb,UI as wb,GI as xb,qI as yb,zI as zb,HI as Ab,BI as Bb,VI as Cb,WI as Db,KI as Eb,YI as Fb,JI as Gb,XI as Hb,ZI as Ib,QI as Jb,eE as Kb,tE as Lb,nE as Mb,oE as Nb,sE as Ob,rE as Pb,iE as Qb,aE as Rb,cE as Sb,dE as Tb,lE as Ub,mE as Vb,pE as Wb,uE as Xb,fE as Yb,_E as Zb,hE as _b,gE as $b,yE as ac,bE as bc,wE as cc,vE as dc,kE as ec,SE as fc,IE as gc,EE as hc,xE as ic,RE as jc,AE as kc,CE as lc,TE as mc,OE as nc,$E as oc,PE as pc,FE as qc,LE as rc,NE as sc,ME as tc,DE as uc,jE as vc,UE as wc,GE as xc,qE as yc,ce as zc,zE as Ac,vh as Bc,HE as Cc};
2068
- //# sourceMappingURL=chunk-YC3UF2IO.js.map
2069
+ end`}var th={bash:'Add to ~/.bashrc or ~/.bash_profile: eval "$(pm completion bash)"',zsh:'Add to ~/.zshrc: eval "$(pm completion zsh)"',fish:"Run: pm completion fish > ~/.config/fish/completions/pm.fish"};function nh(e,t=[],n=[],o=!1,s={}){let r=e.trim().toLowerCase();if(!sl.includes(r))throw new p(`Unknown shell: "${e}". Supported shells: ${sl.join(", ")}.`,u.USAGE);let i=r,a;return i==="bash"?a=Z_(t,n,o,s):i==="zsh"?a=Q_(t,n,o,s):a=eh(t,n,o,s),{shell:i,script:a,setup_hint:th[i]}}import oh from"node:fs/promises";import At 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]="fc124f85-8d28-508b-a3f7-2fe767382197")}catch{}})();var $s="index/manifest.json",Ps="search/embeddings.jsonl",sh="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function rh(e){return e.progress===!0||process.stderr.isTTY===!0}function M(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
2070
+ `)}catch{}}function ih(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new p("Reindex mode must be one of keyword|semantic|hybrid",u.USAGE)}async function ah(e,t,n,o){let s=[];return{candidates:await zr(e,t,n,s,o),warnings:s}}async function Ls(e,t,n,o,s){let r=ze(O()),i=[];for(let a of t)if(!(s&&!s.has(a.metadata.id))){if(typeof a.body=="string"){i.push({metadata:a.metadata,body:a.body});continue}try{let c=await oh.readFile(a.item_path,"utf8"),d=Dt(c,{format:a.item_format,schema:n,extensionFieldNames:r,onWarning:l=>o.push(l)});i.push({metadata:a.metadata,body:d.body})}catch{o.push(`item_list_item_read_failed:${At.relative(e,a.item_path)}`),i.push({metadata:a.metadata,body:""})}}return i}function ch(e,t,n){let o=e.metadata;return{id:o.id,mode:t,updated_at:o.updated_at,corpus:Wr(e,{fields:n})}}var at=Hs;function dh(e){let t=O(),n=at(e.search?.provider);if(!n)return null;let o=ir(t,n);if(!o)return null;let s=o.runtime_definition??o.definition,r=at(s.name)??at(o.definition.name);if(!r)return null;let i=s.embedBatch,a=s.embed_batch,c=s.embed,d=typeof i=="function"?i:typeof a=="function"?a:void 0,l=typeof c=="function"?c:void 0;return!d&&!l?null:{name:r,embedBatch:d,embed:l}}function lh(e){let t=O(),n=at(e.vector_store?.adapter);if(!n)return null;let o=ar(t,n);if(!o)return null;let s=o.runtime_definition??o.definition,r=at(s.name)??at(o.definition.name);if(!r)return null;let i=s.upsert,a=s.delete;return{adapterName:r,...typeof i=="function"?{upsert:i}:{},...typeof a=="function"?{delete:a}:{}}}function Fs(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new p(`Invalid vector returned by ${t}`,u.GENERIC_FAILURE);return e}async function mh(e,t,n){let o=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let r=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:o}));if(!Array.isArray(r))throw new p(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,u.GENERIC_FAILURE);return r.map((i,a)=>Fs(i,`extension search provider "${e.name}" embedBatch output at index ${a}`))}if(!e.embed)throw new p(`Extension search provider "${e.name}" does not implement embed/embedBatch`,u.GENERIC_FAILURE);let s=[];for(let[r,i]of n.entries()){let a=await Promise.resolve(e.embed({input:i,settings:t,model:o}));s.push(Fs(a,`extension search provider "${e.name}" embed output at index ${r}`))}return s}function fl(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function _l(e,t,n){let o=n?yt(n.name,fl(e)):t?yt(t.name,t.model):null;if(!o)throw new p("No embedding identity available for semantic reindex mode",u.USAGE);return o}function ph(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,o)=>n.localeCompare(o))}async function hl(e,t,n,o,s,r,i,a){let c=o?.name??n?.name,d=Kr(c,e.search.embedding_corpus_max_characters).maxCharacters,l=Qn(e),m=s.map(y=>Yr(y,{providerName:c,maxCharacters:d,fields:l})),f=[],_=null;if(o)try{f=await mh(o,e,m),_=yt(o.name,fl(e))}catch(y){if(!n)throw new p(`Extension search provider "${o.name}" failed to generate embeddings: ${y instanceof Error?y.message:String(y)}`,u.GENERIC_FAILURE);r.push(`Extension search provider "${o.name}" failed; falling back to built-in provider (${y instanceof Error?y.message:String(y)})`)}if(f.length===0){if(!n)throw new p(`No embedding executor available for reindex mode '${t}'`,u.USAGE);let y=await Jr(n,e,m,{onProgress:w=>{w.phase==="complete"&&(i.batches_completed=w.batch_index),M(a,`embedding_batch_${w.phase} batch=${w.batch_index}/${w.batch_total} size=${w.batch_size} completed_inputs=${w.completed_inputs}/${w.total_inputs}`)}});r.push(...y.warnings),f=y.vectors,_=yt(n.name,n.model)}if(M(a,`embedding_complete vectors=${f.length}`),f.length!==s.length)throw new p(`Embedding output size mismatch (expected ${s.length}, received ${f.length})`,u.GENERIC_FAILURE);if(!_)throw new p(`No embedding identity available for reindex mode '${t}'`,u.USAGE);return{vectors:f,embeddingIdentity:_}}async function uh(e,t,n,o,s,r){let i=Object.keys(n);if(t){if(i.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:i.sort((a,c)=>a.localeCompare(c)),settings:o}))}catch(a){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${a instanceof Error?a.message:String(a)}`,u.GENERIC_FAILURE)}else i.length>0&&s.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${i.length}`);if(!e)return}e&&await ei(e,i,{},r)}async function gl(e,t,n,o,s){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:o}))}catch(r){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${r instanceof Error?r.message:String(r)}`,u.GENERIC_FAILURE)}else s.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Qr(e,n)}}function fh(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function _h(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(o=>({id:o.metadata.id,type:o.metadata.type,status:o.metadata.status,priority:o.metadata.priority,updated_at:o.metadata.updated_at}))}}function hh(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Zn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new p(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,u.USAGE);let n=Xr(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new p(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,u.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function gh(e){let t=P(e.settings,O()),n=await ah(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(o=>({metadata:o.metadata,body:typeof o.body=="string"?o.body:""}))}}async function yh(e){let t=await to(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return _l(e.settings,Zn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Wt(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(sh))}async function bh(e){let t=await to(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=_l(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),o=new Set(e.metadataDocuments.map(d=>d.metadata.id)),s=ph(t.entries,o),r=Wt(t.embedding,n);e.forceFullSemantic&&!r&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let i=e.forceFullSemantic||r?e.metadataDocuments:e.metadataDocuments.filter(d=>t.entries[d.metadata.id]!==d.metadata.updated_at),a=new Set(i.map(d=>d.metadata.id)),c=a.size>0?await Ls(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,a):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:s,resetRequired:r,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function wh(e){let t=new Set(e.metadataDocuments.map(s=>s.metadata.id)),n=await Ls(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,M(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let o=await hl(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...o,staleDocuments:n,vectorDimension:eo(o.vectors,"Reindex embeddings")}}async function vh(e){let t=await hl(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,o=t.embeddingIdentity,s=eo(n,"Reindex embeddings");if(!(!e.resetRequired&&(Wt(e.ledgerEmbedding,o)||ni(e.ledgerEmbedding,s))))return{vectors:n,embeddingIdentity:o,staleDocuments:e.staleDocuments,vectorDimension:s,resetRequired:e.resetRequired};let i=await wh(e);return n=i.vectors,o=i.embeddingIdentity,s=i.vectorDimension,{vectors:n,embeddingIdentity:o,staleDocuments:i.staleDocuments,vectorDimension:s,resetRequired:!0}}async function kh(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(M(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new p(`Extension vector adapter "${t}" does not support upserting vectors.`,u.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,M(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof p)throw t;if(!e.activeVectorStore)throw new p(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,u.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),M(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){M(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Zr(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,M(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new p(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,u.USAGE)}function Sh(e,t){return e.map((n,o)=>({id:n.metadata.id,vector:Fs(t[o],`reindex embeddings output at index ${o}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function Ih(e){M(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await vh({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(M(e.progressEnabled,"vector_reset_start"),await uh(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),M(e.progressEnabled,"vector_reset_complete")):await gl(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=Sh(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await kh({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:ti(t.embeddingIdentity,t.vectorDimension)}}async function Eh(e){let t=await bh(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(r=>[r.metadata.id,r.metadata.updated_at]));if(M(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return M(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await gl(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let o=await Ih({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let s=new Map(o.staleDocuments.map(r=>[r.metadata.id,r]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(r=>s.get(r.metadata.id)??r),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:o.embeddingMetadata}}async function xh(e){let t=At.join(e.pmRoot,$s),n=At.join(e.pmRoot,Ps),o=Qn(e.settings),s=e.documentsForKeywordArtifacts.map(i=>JSON.stringify(ch(i,e.mode,o))).join(`
2071
+ `);M(e.progressEnabled,"writing keyword artifacts"),await B(t,`${JSON.stringify(e.manifest,null,2)}
2072
+ `),await B(n,`${s}
2073
+ `);let r=[];if(e.mode!=="keyword")try{M(e.progressEnabled,"writing vectorization status ledger"),await oi(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(i){r.push(`search_vectorization_status_ledger_write_failed:${i instanceof Error?i.message:String(i)}`)}return r}async function Rh(e,t){let n=ih(e.mode),o=rh(e),s=e.full===!0;M(o,`start mode=${n}`);let r=I(process.cwd(),t.path);if(!await x(A(r)))throw new p(`Tracker is not initialized at ${r}. Run pm init first.`,u.NOT_FOUND);let i=Gr(await R(r)).settings,a=null;try{a=await K(r,qr,i.locks.ttl_seconds,C(void 0,"pm-reindex"),!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms)}catch(c){throw c instanceof p&&c.exitCode===u.CONFLICT?new p("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",u.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=dh(i),d=lh(i),l=hh({requestedMode:n,pmRoot:r,settings:i,extensionEmbedding:c,extensionVectorAdapter:d}),m=n;M(o,"loading item corpus");let f=await gh({pmRoot:r,settings:i}),_=f.warnings,{documentCandidates:y,metadataDocuments:w}=f;M(o,`loaded_items=${w.length}`);let g=k(),h=_h(m,g,w),S=At.join(r,$s),E=At.join(r,Ps),F=m==="keyword"?await Ls(r,y,i.schema,_):w,T=[],j={},U=null,Z=fh(m);if(m==="keyword"&&await yh({pmRoot:r,settings:i,forceFullSemantic:s,extensionEmbedding:c,reindexWarnings:_}),m!=="keyword"){let oe=await Eh({pmRoot:r,settings:i,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:y,metadataDocuments:w,documentsForKeywordArtifacts:F,forceFullSemantic:s,reindexWarnings:_,semanticWarnings:T,semanticSummary:Z,progressEnabled:o});F=oe.documentsForKeywordArtifacts,j=oe.vectorizationLedgerEntries,U=oe.vectorizationEmbeddingMetadata}let de=await xh({pmRoot:r,mode:m,manifest:h,documentsForKeywordArtifacts:F,settings:i,vectorizationLedgerEntries:j,vectorizationEmbeddingMetadata:U,progressEnabled:o}),Ee=[...await N({path:S,scope:"project",op:"reindex:manifest"}),...await N({path:E,scope:"project",op:"reindex:embeddings"}),...await sr({mode:m,total_items:w.length})];return M(o,"done"),{ok:!0,mode:m,total_items:w.length,semantic:Z,artifacts:{manifest:$s,embeddings:Ps},warnings:[..._,...T,...de,...Ee],generated_at:g}}finally{await a?.()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a294f940-5bb9-55a4-bf2c-64842a3a177b")}catch{}})();var kl=Symbol("pm.active-extension-host-context");function X(e){return{fullChangedFields:!0,options:e}}var v=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[kl]=!0,n}run(t,n={}){return Nh({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return uc(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},o={}){return this.runTyped("graph",{subcommand:t,...n,options:o})}append(t,n,o={}){return this.runTyped("append",{id:t,...X({...o,body:n})})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,o,s,r={}){return this.runTyped("config",{scope:t,configAction:n,...o===void 0?{}:{key:o},...s===void 0?{}:{value:s},options:r})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,o,s){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-field",to:n,...s?{fieldTypeScope:s}:{}}})}schemaRemapStatus(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,o={},s,r){return this.runTyped("plan",{...n===void 0?{}:{id:n},...s===void 0?{}:{stepRef:s},...r===void 0?{}:{reorderTo:r},options:{...o,subcommand:t}})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,o){return this.plan("update-step",t,o,n)}planCompleteStep(t,n,o={}){return this.plan("complete-step",t,o,n)}planBlockStep(t,n,o){return this.plan("block-step",t,o,n)}planReorderStep(t,n,o,s={}){return this.plan("reorder-step",t,s,n,o)}planRemoveStep(t,n,o={}){return this.plan("remove-step",t,o,n)}planLink(t,n,o){return this.plan("link",t,o,n)}planUnlink(t,n,o){return this.plan("unlink",t,o,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",X(t))}update(t,n={}){return this.runTyped("update",{id:t,...X(n)})}close(t,n,o={}){return this.runTyped("close",{id:t,reason:n,...X(o)})}claim(t,n={}){return this.runTyped("claim",{id:t,...X(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...X(t)})}release(t,n={}){return this.runTyped("release",{id:t,...X(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...X(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...X(n)})}restore(t,n,o={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...o,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...X(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...X(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...X(n)})}closeTask(t,n,o={}){return this.runTyped("close-task",{id:t,reason:n,...X(o)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function BI(e={},t={}){return new v(t).context(e)}function VI(e={},t={}){return new v(t).list(e)}function WI(e,t={},n={}){return new v(n).search(e,t)}function KI(e,t={},n={}){return new v(n).get(e,t)}function YI(e={},t={}){return new v(t).next(e)}function JI(e={},t={}){return new v(t).aggregate(e)}function XI(e={},t={}){return new v(t).stats(e)}function ZI(e={},t={}){return new v(t).duplicates(e)}function QI(e,t={},n={}){return new v(n).comments(e,t)}function eE(e,t={},n={}){return new v(n).notes(e,t)}function tE(e,t={},n={}){return new v(n).learnings(e,t)}function nE(e,t={},n={}){return new v(n).files(e,t)}function oE(e,t={},n={}){return new v(n).filesDiscover(e,t)}function sE(e,t={}){return new v(t).filesLookup(e)}function rE(e,t={},n={}){return new v(n).docs(e,t)}function iE(e,t={},n={}){return new v(n).deps(e,t)}function aE(e,t={},n={},o={}){return new v(o).graph(e,t,n)}function cE(e,t,n={},o={}){return new v(o).append(e,t,n)}function dE(e,t={},n={}){return new v(n).init(e,t)}function lE(e,t,n,o,s={},r={}){return new v(r).config(e,t,n,o,s)}function mE(e,t={},n={}){return new v(n).schema(e,t)}function pE(e={}){return new v(e).schemaList()}function uE(e,t={}){return new v(t).schemaShow(e)}function fE(e,t={},n={}){return new v(n).schemaAddType(e,t)}function _E(e,t={},n={}){return new v(n).schemaRemoveType(e,t)}function hE(e,t={},n={}){return new v(n).schemaAddStatus(e,t)}function gE(e,t={},n={}){return new v(n).schemaRemoveStatus(e,t)}function yE(e,t={},n={}){return new v(n).schemaAddField(e,t)}function bE(e,t={},n={}){return new v(n).schemaRemoveField(e,t)}function wE(e={}){return new v(e).schemaListFields()}function vE(e,t={}){return new v(t).schemaShowField(e)}function kE(e,t={},n={}){return new v(n).schemaApplyPreset(e,t)}function SE(e={},t={}){return new v(t).schemaInferTypes(e)}function IE(e,t,n,o={}){return new v(o).schemaRenameType(e,t,n)}function EE(e,t,n,o,s={}){return new v(s).schemaRenameField(e,t,n,o)}function xE(e,t,n,o={}){return new v(o).schemaRemapStatus(e,t,n)}function RE(e,t={}){return new v(t).schemaShowStatus(e)}function AE(e,t={},n={}){return new v(n).profile(e,t)}function CE(e={}){return new v(e).profileList()}function TE(e,t={}){return new v(t).profileShow(e)}function OE(e,t={},n={}){return new v(n).profileApply(e,t)}function $E(e,t={}){return new v(t).profileLint(e)}function PE(e={},t={}){return new v(t).validate(e)}function FE(e={},t={}){return new v(t).health(e)}function LE(e={},t={}){return new v(t).gc(e)}function NE(e,t,n={}){return new v(n).historyRedact(e,t)}function ME(e,t={},n={}){return new v(n).historyRepair(e,t)}function DE(e={},t={}){return new v(t).historyRepairAll(e)}function jE(e,t={},n={}){return new v(n).historyCompact(e,t)}function UE(e,t={}){return new v(t).historyCompactBulk(e)}function GE(e={},t={}){return new v(t).create(e)}function qE(e,t={},n={}){return new v(n).update(e,t)}function zE(e,t,n={},o={}){return new v(o).close(e,t,n)}function HE(e,t={},n={}){return new v(n).claim(e,t)}function BE(e={},t={}){return new v(t).claimNext(e)}function VE(e,t={},n={}){return new v(n).release(e,t)}function WE(e,t={},n={}){return new v(n).copy(e,t)}function KE(e,t={},n={}){return new v(n).delete(e,t)}function YE(e,t,n={},o={}){return new v(o).restore(e,t,n)}function JE(e,t={},n={}){return new v(n).focus(e,t)}function XE(e,t={},n={}){return new v(n).startTask(e,t)}function ZE(e,t={},n={}){return new v(n).pauseTask(e,t)}function QE(e,t,n={},o={}){return new v(o).closeTask(e,t,n)}function ex(e,t={},n={}){return new v(n).extension(e,t)}function tx(e={},t={}){return new v(t).extensionList(e)}function nx(e,t={},n={}){return new v(n).extensionActivate(e,t)}function ox(e,t={},n={}){return new v(n).extensionDeactivate(e,t)}function sx(e,t={},n={}){return new v(n).package(e,t)}function rx(e={},t={}){return new v(t).packageList(e)}function ix(e,t={},n={}){return new v(n).packageInstall(e,t)}function ax(e,t={},n={}){return new v(n).packageUninstall(e,t)}function cx(e={},t={}){return new v(t).packageDoctor(e)}function dx(e,t={},n={}){return new v(n).packageManage(e,t)}function lx(e,t={},n={}){return new v(n).packageDescribe(e,t)}function mx(e={},t={}){return new v(t).packageReload(e)}function px(e={},t={}){return new v(t).packageCatalog(e)}function ux(e,t={},n={}){return new v(n).packageActivate(e,t)}function fx(e,t={},n={}){return new v(n).packageDeactivate(e,t)}function _x(e,t={},n={}){return new v(n).upgrade(e,t)}function Ch(e,t,n){return JSON.stringify([yl.resolve(e),yl.resolve(n??process.cwd()),t.extensions.enabled,t.extensions.disabled,t.extensions.policy])}async function Th(e,t,n){let o=Ch(e,t,n);return hc(o,()=>hg(e,t,n))}async function hx(e,t={}){let n=await R(e),o=t.extensionRegistrations??(t.noExtensions===!0?null:await Th(e,n,t.cwd)),s=P(n,o),r=q(n.schema),i=ut(n.schema);return{types:[...s.types],statuses:r.definitions.map(a=>a.id),openStatus:r.open_status,closeStatus:r.close_status,canceledStatus:r.canceled_status,fields:fc(i.definitions),extensionCommands:_c(o?.commands??[])}}async function gx(e,t={}){let n=typeof e=="string"?{...t,pmRoot:e}:e??t,o={json:!0,quiet:n.quiet??!0,noExtensions:n.noExtensions??!1,noPager:!0,profile:n.profile??!1,path:n.pmRoot};return ko(n,o)}function ce(e,t){let n=b(e,t);if(!n)throw new p(`Missing required argument: ${t}`,64);return n}var bl=tr(),Sl=new Ah;function Tn(){Gn(Ws()),qn(Ks()),zn(Ys()),Hn(Js()),Bn(Xs()),Vn(Zs()),Wn(Qs())}async function Il(e,t,n,o){return nr(()=>t===void 0?bl.read(()=>wl(e,n,o)):bl.write(()=>$h(t,()=>wl(e,n,o))))}async function yx(e,t){let n=e.cwd,o=n??process.cwd();return Il(en({path:e.path,noExtensions:e.noExtensions}),n,o,()=>Sl.run(!0,t))}async function wl(e,t,n){let o=I(t,e.path);if(e.noExtensions)return Tn(),Fo({pmRoot:o},()=>n(null));if(!await x(A(o)))return Tn(),n(null);let s=null,r;try{let i=await R(o),a=await Dn({pmRoot:o,settings:i,cwd:t,noExtensions:!1}),c=await Un({...a,loaded:a.loaded});r={loadResult:a,activationResult:c},Gn(c.hooks),qn(c.commands),zn(c.parsers),Hn(c.preflight),Bn(c.services),Vn(c.renderers),Wn(c.registrations),s={registrations:c.registrations,commands:c.commands,pmRoot:o,packages:a.loaded}}catch(i){Tn(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",i)}try{return await Fo({pmRoot:o,packages:s?.packages},()=>n(s))}finally{Tn(),r&&await jn(r.loadResult,r.activationResult).catch(()=>{})}}async function Oh(e,t,n,o,s){if(!s)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let r=be(e),a=s.registrations.commands.find(d=>be(d.action)===r)?.command??s.commands.handlers.find(d=>be(d.command)===r)?.command;if(!a)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let c=await rr({command:ao(a),args:V(n.args??t.args),options:co(t,n),global:o,pm_root:s.pmRoot,sdk:kc(s.pmRoot,v.forActiveExtensionHost({pmRoot:s.pmRoot,author:typeof o.author=="string"&&o.author.trim()?o.author.trim():"pm-extension"}))});if(!c.handled){let d=c.warnings.length>0?` (${c.warnings.join(", ")})`:"";throw new p(`Unsupported native pm action: ${e}${d}`,u.USAGE)}return c.result}async function $h(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}var Ph=new Set(["activity","aggregate","context","contracts","deps","files-discover","get","graph","health","history","list","next","search","stats","telemetry","validate"]);function Fh(e){let t=ce(e,"action"),n=be(t),o=ct(Ro,n),s=o?.action??n,r={...e,action:s};return o?.options!==void 0&&(r.options={...o.options,...$n(e.options)}),s==="package"&&(r.options={...$n(r.options),vocabulary:"package"}),{action:s,args:r}}function Lh(e){return!Ph.has(be(e))}async function Nh(e){let t=Fh(e),n=en(t.args),o=Lh(t.action),s=b(t.args,"cwd"),r=s??process.cwd();try{return e[kl]===!0||Sl.getStore()===!0?await vl(t.action,t.args,n,null):await Il(n,s,r,i=>vl(t.action,t.args,n,i))}finally{o&&xo()}}function ct(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function On(e){return b(e.args,"target")??b(e.options,"target")}function L(e,t=e.options){return e.id??ce(t,"id")}async function Mh(e){let t=We("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),Eo(await we(b(e.args,"status")??b(t,"status"),t,e.global),t)}async function Dh(e){let t=We("search",e.options);return t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.compact=!0),Eo(await vo(ce(e.args,"query"),t,e.global),t)}async function jh(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options);return pe(await kt(o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Uh(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options),s={...o,...o.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...o.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return pe(await Qo(L(e,s),s,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Gh(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options);return pe(await ve(L(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function qh(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options),s=b(e.args,"reason")??b(e.args,"text")??b(o,"reason")??b(o,"text");return pe(await Ze(L(e,o),s,o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function zh(e){let t=cn(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0,t.limit===void 0&&t.fullHistory!==!0&&(t.limit="20")),Tc(L(e),t,e.global)}function El(e,t){return Oa(Vd(e.options,t,te),e.global)}function Hh(e){let t=V(e.options.lookupPath);if(t&&t.length>0)return El(e,t);let n=L(e);return e.options.discover===!0?uo(n,io(e.options),e.global):Ta(n,tn(e.options),e.global)}function Bh(e){return ic({subcommand:b(e.args,"subcommand")??b(e.options,"subcommand"),limit:Ji(e.args,e.options)},e.global)}function Vh(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),Aa(e.global,t)}function Wh(e){let t=b(e.args,"configAction")??b(e.options,"configAction")??b(e.options,"action");if(t===void 0)throw new p("Missing required argument: configAction",64);return Va(b(e.args,"scope")??b(e.options,"scope")??"project",t,b(e.args,"key")??b(e.options,"key"),e.options,e.global,b(e.args,"value")??b(e.options,"value"))}function Kh(e){let t={...e.options};return t.compact===void 0&&(t.compact=t.full!==!0),delete t.full,Hi(t,e.global)}function Yh(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new p(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new p(`${t} must be a finite integer.`,64);let o=Number.parseInt(n,10);if(!Number.isInteger(o))throw new p(`${t} must be a finite integer.`,64);return o}}function Jh(e){let t=b(e.args,"subcommand")??ce(e.options,"subcommand"),n=e.options;return Yc({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:Xh(e),reorderTo:Yh(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global})}function Xh(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function Zh(e){let t=b(e.args,"subcommand")??ce(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:b(e.args,"name")??b(e.options,"name"),author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:V(n)}}function Qh(e){let{ctx:t,subcommand:n,name:o,author:s,force:r}=e,a=ct({list:()=>fa(t.global),show:()=>_a(o,t.global),"show-status":()=>ha(o,t.global),"list-fields":()=>ba(t.global),"show-field":()=>wa(o,t.global),"remove-type":()=>la(o,{author:s,force:r},t.global),"remove-field":()=>ya(o,{author:s,force:r},t.global),"remove-status":()=>ua(o,{author:s,force:r},t.global),"apply-preset":()=>va(b(t.args,"typePreset")??b(t.options,"typePreset"),{author:s,force:r},t.global)},n);return a?a():null}function eg(e){let{ctx:t,name:n,author:o,force:s,aliases:r}=e,i=t.args.commands??t.options.commands,a=t.args.requiredTypes??t.options.requiredTypes;return ga(n,{type:b(t.args,"fieldType")??b(t.options,"fieldType"),commands:i===void 0?void 0:V(i),description:b(t.args,"description")??b(t.options,"description"),cliFlag:b(t.args,"cliFlag")??b(t.options,"cliFlag"),alias:r,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:a===void 0?void 0:V(a),author:o,force:s},t.global)}function tg(e){let{ctx:t,name:n,author:o,force:s,aliases:r}=e,i=t.args.role??t.options.role;return pa(n,{role:i===void 0?void 0:V(i),alias:r,description:b(t.args,"description")??b(t.options,"description"),order:te(t.args.order??t.options.order,"schema add-status order"),author:o,force:s},t.global)}function ng(e){let{ctx:t,name:n,author:o,force:s,aliases:r}=e;return da(n,{description:b(t.args,"description")??b(t.options,"description"),defaultStatus:b(t.args,"defaultStatus")??b(t.args,"default_status")??b(t.options,"defaultStatus")??b(t.options,"default_status"),folder:b(t.args,"folder")??b(t.options,"folder"),alias:r,author:o,force:s},t.global)}function og(e){let{ctx:t,subcommand:n,name:o,author:s,force:r}=e,i=b(t.args,"to")??ce(t.options,"to"),a=b(t.args,"migrationId")??b(t.args,"migration_id")??b(t.options,"migrationId")??b(t.options,"migration_id"),c=b(t.args,"fieldTypeScope")??b(t.options,"fieldTypeScope")??b(t.args,"type")??b(t.options,"type"),d=n==="rename-type"?{kind:"rename-type",from:o??"",to:i}:n==="rename-field"?{kind:"rename-field",from:o??"",to:i,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:o??"",to:i};return aa(d,{migrationId:a,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:s,force:r},t.global)}function sg(e){let t=Zh(e),n=Qh(t);if(n!==null)return n;if(t.subcommand==="rename-type"||t.subcommand==="rename-field"||t.subcommand==="remap-status")return og(t);if(t.subcommand==="add-field")return eg(t);if(t.subcommand==="add-status")return tg(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?ka({minCount:te(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):ng(t);throw le({command_path:"schema",token:t.subcommand,allowed:ca,exit_code:64})}function rg(e){let t=b(e.args,"subcommand")??ce(e.options,"subcommand"),n=t.trim().toLowerCase(),o=b(e.args,"name")??b(e.options,"name"),r=ct({list:()=>Ld(),show:()=>Nd(o),lint:()=>Md(o),apply:()=>Dd(o,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!r)throw le({command_path:"profile",token:t,allowed:Fd,exit_code:64});return r()}async function ig(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options);return pe(await Ec(L(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function ag(e){let{changedFields:t,runnerOptions:n}=ie(e.args,e.options);return pe(await Mc(mo(n),e.global),{changedFields:t})}async function cg(e){let{changedFields:t,runnerOptions:n}=ie(e.args,e.options),o=b(e.args,"reason"),s=o!==void 0&&n.reason===void 0?{...n,reason:o}:{...n};return e.force&&s.force===void 0&&(s.force=!0),pe(await Cc(lo(s),e.global),{changedFields:t})}async function dg(e){let{changedFields:t,idOnly:n,runnerOptions:o}=ie(e.args,e.options),s=b(o,"target")??ce(e.args,"target");return pe(await Me(L(e,o),s,o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function xl(e){let t={...e};return delete t.assignee,t}async function lg(e){let t=I(process.cwd(),e.global.path),n=await R(t),o=dc(q(n.schema)),s=L(e),r=await yo(s,e.force,e.global,e.options),i=await ve(s,{...xl(e.options),status:o,force:e.force},e.global);return{id:s,action:"start_task",claim:r,update:i}}async function mg(e){let t=I(process.cwd(),e.global.path),n=await R(t),o=L(e),s=q(n.schema).open_status,r=await ve(o,{...xl(e.options),status:s,force:e.force},e.global),i=await ln(o,e.force,e.global,e.options);return{id:o,action:"pause_task",update:r,release:i}}async function pg(e){let t=L(e),n=b(e.args,"reason")??b(e.args,"text")??b(e.options,"reason")??b(e.options,"text"),o=await Ze(t,n,{...e.options,force:e.force},e.global),s=await ln(t,e.force,e.global,e.options);return{id:t,action:"close_task",close:o,release:s}}function ug(e){let t={...e.args,...e.options};return Vi(ce(t,"subcommand"),b(t,"id")??e.id,b(t,"target"),Qi(t),e.global)}function fg(e){return ta(I(process.cwd(),e.global.path),{...e.args,...e.options})}var Rl={init:e=>Wa(b(e.args,"prefix"),e.global,e.options),context:e=>ho(We("context",e.options),e.global),next:e=>go(We("next",e.options),e.global),eval:md,events:pd,merge:ud,workspace:fd,meet:wn,event:wn,remind:wn,list:Mh,get:e=>wo(L(e),e.global,We("get",e.options)),search:Dh,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:V(e.options.status);return Io(e.global,{...t.length===0?{}:{status:t},since:b(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:te(e.options.limit,"limit")})},create:jh,copy:Uh,focus:e=>ts(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:Gh,restore:dg,claim:e=>e.options.next===!0||e.args.next===!0?Na(e.force,e.global,{...e.options,...e.args},{...e.options,...e.args}):yo(L(e),e.force,e.global,e.options),release:e=>ln(L(e),e.force,e.global,e.options),"start-task":lg,"pause-task":mg,"close-task":pg,close:qh,comments:zh,notes:e=>$c(L(e),cn(e.options),e.global),learnings:e=>Oc(L(e),cn(e.options),e.global),files:Hh,docs:e=>Ca(L(e),tn(e.options),e.global),test:e=>ac(L(e),e.options,e.global),"test-all":e=>cc(e.options,e.global),telemetry:Bh,validate:e=>an(e.options,e.global,{runUpdate:(t,n,o)=>ve(t,n,o)}),health:Vh,assurance:e=>$a(e.args,e.options,e.global),contracts:e=>ko(e.options,e.global),config:Wh,activity:Kh,aggregate:e=>fo(e.options,e.global),extension:e=>rn(On(e),e.options,e.global),package:e=>rn(On(e),e.options,e.global),install:e=>rn(On(e),{...e.options,install:!0},e.global),upgrade:e=>qa(On(e),e.options,e.global),delete:e=>es(L(e),e.options,e.global),deps:e=>Bi(L(e),e.options,e.global),graph:ug,"files-discover":e=>uo(L(e),e.options,e.global),"files-lookup":e=>El(e,V(e.options.paths)),history:e=>Ma(L(e),e.options,e.global),"history-redact":e=>Ui(L(e),e.options,e.global),"history-repair":Hd,"history-compact":Bd,"history-author-acknowledge":fg,plan:Jh,schema:sg,profile:rg,stats:e=>So(e.global,Wd(e.options)),append:ig,"update-many":ag,"close-many":cg,gc:e=>za(e.global,e.options)};function bx(e=Sr){return e.map(t=>{let n=be(t),o=ct(Ro,n),s=o?.action??n,r=ct(Rl,s)!==void 0;return{action:t,resolved_action:s,covered:r,route:r?o?"alias":"native":"missing"}})}async function vl(e,t,n,o){let s=ro(t,e);br(e,s);let r={action:e,args:t,options:s,id:b(t,"id"),force:t.force===!0||s.force===!0,global:n,activeExtensions:o},i=ct(Rl,e),a=i?await i(r):await Oh(e,t,s,n,o);return vr(e,s,a)}var _g={closeManyOptionsFromFlat:lo,extensionOptionsFromArgs:co,globalOptions:en,mutationListOptions:Zi,normalizeActionName:be,normalizeCommandPath:ao,normalizeMcpUpdateOptions:ea,normalizeMcpOptionsArrays:Xi,optionsWithAuthor:ro,readRequiredString:ce,readScalarString:Ki,readScalarStringAllowBlank:Yi,readStringArray:V,updateManyOptionsFromFlat:mo,withAddNoteOption:tn,withFilesDiscoveryOptions:io,withMutationCompaction:ie};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=_g);async function hg(e,t,n){let o=await Dn({pmRoot:e,settings:t,cwd:n??process.cwd(),noExtensions:!1}),s=await Un(o);try{return s.registrations}finally{try{await jn(o,s)}catch{}}}export{yc as a,Nl as b,Ao as c,It as d,fn as e,kc as f,Sg as g,Ig as h,Eg as i,xg as j,Rg as k,mc as l,Ag as m,Ol as n,xo as o,Po as p,Sc as q,Wl as r,Yl as s,Jl as t,Fo as u,Ec as v,Me as w,Cc as x,Tc as y,Oc as z,$c as A,Mc as B,fp as C,Dc as D,Bo as E,Yc as F,Qo as G,es as H,ts as I,Xc as J,Zc as K,mu as L,pu as M,td as N,od as O,sd as P,rd as Q,xu as R,Et as S,dd as T,bn as U,ld as V,ot as W,ls as X,$u as Y,fw as Z,_w as _,us as $,hd as aa,Ow as ba,$w as ca,yd as da,vd as ea,Jw as fa,Yu as ga,ws as ha,Xu as ia,Zu as ja,Fd as ka,Ld as la,Nd as ma,Md as na,Dd as oa,wv as pa,vv as qa,kv as ra,Sv as sa,vs as ta,bf as ua,qd as va,zd as wa,Ef as xa,xf as ya,Rf as za,z as Aa,Af as Ba,Cf as Ca,Tf as Da,Of as Ea,Ss as Fa,Kd as Ga,rt as Ha,ks as Ia,Yd as Ja,$f as Ka,Jd as La,Pf as Ma,Ff as Na,Lf as Oa,Nf as Pa,Mf as Qa,Hf as Ra,el as Sa,Bf as Ta,Zf as Ua,r_ as Va,a_ as Wa,nh as Xa,Rh as Ya,v as Za,BI as _a,VI as $a,WI as ab,KI as bb,YI as cb,JI as db,XI as eb,ZI as fb,QI as gb,eE as hb,tE as ib,nE as jb,oE as kb,sE as lb,rE as mb,iE as nb,aE as ob,cE as pb,dE as qb,lE as rb,mE as sb,pE as tb,uE as ub,fE as vb,_E as wb,hE as xb,gE as yb,yE as zb,bE as Ab,wE as Bb,vE as Cb,kE as Db,SE as Eb,IE as Fb,EE as Gb,xE as Hb,RE as Ib,AE as Jb,CE as Kb,TE as Lb,OE as Mb,$E as Nb,PE as Ob,FE as Pb,LE as Qb,NE as Rb,ME as Sb,DE as Tb,jE as Ub,UE as Vb,GE as Wb,qE as Xb,zE as Yb,HE as Zb,BE as _b,VE as $b,WE as ac,KE as bc,YE as cc,JE as dc,XE as ec,ZE as fc,QE as gc,ex as hc,tx as ic,nx as jc,ox as kc,sx as lc,rx as mc,ix as nc,ax as oc,cx as pc,dx as qc,lx as rc,mx as sc,px as tc,ux as uc,fx as vc,_x as wc,hx as xc,gx as yc,ce as zc,yx as Ac,Nh as Bc,bx as Cc};
2074
+ //# sourceMappingURL=chunk-WMEZHCFI.js.map