@unbrained/pm-cli 2026.8.6 → 2026.8.7

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 (209) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +30 -0
  3. package/dist/cli/main.js +4 -2
  4. package/dist/cli/register-operations.js +11 -2
  5. package/dist/cli/stats-analytics-json.d.ts +9 -0
  6. package/dist/cli/stats-analytics-json.js +69 -0
  7. package/dist/cli-bundle/bundle-manifest.json +397 -397
  8. package/dist/cli-bundle/chunks/append-7BXBFDGD.js +2 -0
  9. package/dist/cli-bundle/chunks/{chunk-TPKDJ5WL.js → chunk-2AXF3VSK.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-R6RKEYYW.js → chunk-2XS43CCV.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-T45OHXDW.js → chunk-3A6KWB72.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-3ISTDB42.js +8 -0
  13. package/dist/cli-bundle/chunks/{chunk-SXECIECW.js → chunk-4MTI7XOV.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-MCS73BKB.js → chunk-6BX5UDCN.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-A3XQ7VPU.js → chunk-6QPO7KLR.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-BP6EMEDP.js → chunk-7MXHZHSQ.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-GU3TSEHD.js → chunk-7ZPMJW4U.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-343QETLI.js → chunk-AGYNSNCI.js} +2 -2
  19. package/dist/cli-bundle/chunks/chunk-B4H7FEFH.js +5 -0
  20. package/dist/cli-bundle/chunks/{chunk-CA3BURYF.js → chunk-B4KLBBMN.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-3ZJRFYY2.js → chunk-CALJHNBL.js} +12 -12
  22. package/dist/cli-bundle/chunks/{chunk-M357ZCOR.js → chunk-CFIGP5LY.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-SVV3DQES.js → chunk-CS6MRHG7.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-DWOAOZHZ.js → chunk-CUGNQQKH.js} +2 -2
  25. package/dist/cli-bundle/chunks/chunk-D4FPS43D.js +164 -0
  26. package/dist/cli-bundle/chunks/{chunk-L6LGKJX3.js → chunk-H5Y5YE6A.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-5PBP2ZP3.js → chunk-H5Y6UV6E.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-QJ7C3JIW.js → chunk-H7KGWPDF.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-D7I3TUGV.js → chunk-HFSD77TQ.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-AOBDLU4T.js → chunk-HX2GTA6L.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-4AVFKHHC.js → chunk-J2IEKAVR.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-OXY3SJ3N.js → chunk-K44PYFXH.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-M4VEE3FK.js → chunk-K4KGEEBT.js} +2 -2
  34. package/dist/cli-bundle/chunks/chunk-KFLK5TRH.js +21 -0
  35. package/dist/cli-bundle/chunks/{chunk-FDBRXV25.js → chunk-KL6IEBV2.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-JQ4NZ5EB.js → chunk-KWQZDZSS.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-UVVXHGYS.js → chunk-KZ4X3DGU.js} +2 -2
  38. package/dist/cli-bundle/chunks/chunk-LD77HJMQ.js +13 -0
  39. package/dist/cli-bundle/chunks/{chunk-AYRUGRNS.js → chunk-ME2JJ4LA.js} +2 -2
  40. package/dist/cli-bundle/chunks/chunk-NFLJ3FHD.js +2 -0
  41. package/dist/cli-bundle/chunks/{chunk-MDTH7SAE.js → chunk-NG6OXIBR.js} +8 -8
  42. package/dist/cli-bundle/chunks/{chunk-R6LSRGPS.js → chunk-NYIGHWQY.js} +2 -2
  43. package/dist/cli-bundle/chunks/{chunk-3KFVGGRE.js → chunk-NZ75GNSA.js} +2 -2
  44. package/dist/cli-bundle/chunks/{chunk-Q3VOP62W.js → chunk-PCJWJNC2.js} +2 -2
  45. package/dist/cli-bundle/chunks/{chunk-C3YABSJK.js → chunk-PD3225AM.js} +2 -2
  46. package/dist/cli-bundle/chunks/{chunk-JFZIS6JF.js → chunk-PDEGKG7P.js} +2 -2
  47. package/dist/cli-bundle/chunks/chunk-PIE5HBNA.js +2 -0
  48. package/dist/cli-bundle/chunks/{chunk-SD3YXU2U.js → chunk-PW2H7YJR.js} +20 -20
  49. package/dist/cli-bundle/chunks/{chunk-PECV7L5T.js → chunk-TPKN3S7S.js} +2 -2
  50. package/dist/cli-bundle/chunks/{chunk-F4NREH3G.js → chunk-TPXAXTCO.js} +2 -2
  51. package/dist/cli-bundle/chunks/chunk-UFWUJO4V.js +2 -0
  52. package/dist/cli-bundle/chunks/{chunk-WSI5KZQJ.js → chunk-UQLZQVFW.js} +2 -2
  53. package/dist/cli-bundle/chunks/{chunk-4OVGQW22.js → chunk-VT3Z5G7D.js} +2 -2
  54. package/dist/cli-bundle/chunks/{chunk-RUAU5OSH.js → chunk-WOD3WWUN.js} +2 -2
  55. package/dist/cli-bundle/chunks/{chunk-DQGJ2RWT.js → chunk-WSJEIGJF.js} +2 -2
  56. package/dist/cli-bundle/chunks/{chunk-RAFUN7IX.js → chunk-WYNUU7ZW.js} +49 -46
  57. package/dist/cli-bundle/chunks/{chunk-5ZKQPA44.js → chunk-YGPNCCXZ.js} +2 -2
  58. package/dist/cli-bundle/chunks/close-CMY3BAUG.js +2 -0
  59. package/dist/cli-bundle/chunks/close-many-SA4XZCTK.js +2 -0
  60. package/dist/cli-bundle/chunks/comments-EZ556ZD3.js +2 -0
  61. package/dist/cli-bundle/chunks/copy-ZSGPA52X.js +2 -0
  62. package/dist/cli-bundle/chunks/{create-TG67IVFI.js → create-I5DVV4YG.js} +2 -2
  63. package/dist/cli-bundle/chunks/delete-RL3JACSW.js +2 -0
  64. package/dist/cli-bundle/chunks/{deps-AJUGP2OH.js → deps-S7UBCECS.js} +2 -2
  65. package/dist/cli-bundle/chunks/{docs-QOCLDRKJ.js → docs-ZZNVBBYO.js} +2 -2
  66. package/dist/cli-bundle/chunks/{files-3ST5TY64.js → files-27C337VT.js} +2 -2
  67. package/dist/cli-bundle/chunks/focus-5Z2SG7LU.js +2 -0
  68. package/dist/cli-bundle/chunks/{history-compact-7BJFML4S.js → history-compact-HJQK67CZ.js} +2 -2
  69. package/dist/cli-bundle/chunks/{history-redact-WJN3HYXR.js → history-redact-PWC6PDWA.js} +2 -2
  70. package/dist/cli-bundle/chunks/{history-repair-XDNZUB7F.js → history-repair-N3CY4WBF.js} +2 -2
  71. package/dist/cli-bundle/chunks/{learnings-SZMUPVNA.js → learnings-4FH23XDT.js} +2 -2
  72. package/dist/cli-bundle/chunks/{profile-KL53JIAC.js → profile-5Y5XXH5N.js} +2 -2
  73. package/dist/cli-bundle/chunks/{register-list-query-QH7ONPKU.js → register-list-query-FJZCJ67O.js} +2 -2
  74. package/dist/cli-bundle/chunks/{register-mutation-OCRQNZK4.js → register-mutation-YGYPW3BL.js} +3 -3
  75. package/dist/cli-bundle/chunks/register-operations-WMDSUMQF.js +2 -0
  76. package/dist/cli-bundle/chunks/{register-setup-QWBQ6HBS.js → register-setup-DL7FFABC.js} +2 -2
  77. package/dist/cli-bundle/chunks/restore-6KYBV5BY.js +2 -0
  78. package/dist/cli-bundle/chunks/{schema-QJ27OTRV.js → schema-EQGKBYXJ.js} +2 -2
  79. package/dist/cli-bundle/chunks/update-QVTYOD6I.js +2 -0
  80. package/dist/cli-bundle/chunks/update-many-DJSBU525.js +2 -0
  81. package/dist/cli-bundle/focused-chunks/{chunk-MBBMTDD3.js → chunk-2ECLECMK.js} +3 -3
  82. package/dist/cli-bundle/focused-chunks/{chunk-CL3NB7VW.js → chunk-3K4XV2BF.js} +2 -2
  83. package/dist/cli-bundle/focused-chunks/{chunk-ME4XVOBJ.js → chunk-4EX25PXM.js} +2 -2
  84. package/dist/cli-bundle/focused-chunks/chunk-4VJQTS3P.js +2 -0
  85. package/dist/cli-bundle/focused-chunks/chunk-73JUDYXT.js +2 -0
  86. package/dist/cli-bundle/focused-chunks/{chunk-GSW2Y7VZ.js → chunk-CIXVQPB7.js} +2 -2
  87. package/dist/cli-bundle/focused-chunks/{chunk-7YTZ7A4E.js → chunk-DLTS3IHM.js} +2 -2
  88. package/dist/cli-bundle/focused-chunks/{chunk-YHDCGUIW.js → chunk-DQ6FKGL3.js} +10 -10
  89. package/dist/cli-bundle/focused-chunks/{chunk-YLPZHWX7.js → chunk-HNL6IFGS.js} +2 -2
  90. package/dist/cli-bundle/focused-chunks/chunk-JLG2C4EQ.js +2 -0
  91. package/dist/cli-bundle/focused-chunks/{chunk-6KDHXURF.js → chunk-MHMTKV5V.js} +2 -2
  92. package/dist/cli-bundle/focused-chunks/{chunk-GEYU23YS.js → chunk-MOTJFQ3F.js} +22 -22
  93. package/dist/cli-bundle/focused-chunks/{chunk-EYO4F74Z.js → chunk-NBJKQP4S.js} +2 -2
  94. package/dist/cli-bundle/focused-chunks/{chunk-XNVXIQ4B.js → chunk-QHRTT7WT.js} +2 -2
  95. package/dist/cli-bundle/focused-chunks/{chunk-27DK4A5O.js → chunk-R2LEMEV5.js} +2 -2
  96. package/dist/cli-bundle/focused-chunks/{chunk-4JC3AOGS.js → chunk-RPNYG5MO.js} +2 -2
  97. package/dist/cli-bundle/focused-chunks/{chunk-EAXXF2HW.js → chunk-RW5IYD4J.js} +2 -2
  98. package/dist/cli-bundle/focused-chunks/{chunk-TQMFQYXR.js → chunk-TIKDBG4D.js} +16 -16
  99. package/dist/cli-bundle/focused-chunks/{chunk-N7QN3NE6.js → chunk-VZFU2R4M.js} +2 -2
  100. package/dist/cli-bundle/focused-chunks/{chunk-GIERI4YU.js → chunk-YZEZAPJK.js} +2 -2
  101. package/dist/cli-bundle/focused-chunks/chunk-ZJIMJHDB.js +2 -0
  102. package/dist/cli-bundle/main.js +2 -2
  103. package/dist/cli-bundle/sdk-authoring.js +1 -1
  104. package/dist/cli-bundle/sdk-contracts.js +1 -1
  105. package/dist/cli-bundle/sdk-core.js +29 -28
  106. package/dist/cli-bundle/sdk-governance.js +1 -1
  107. package/dist/cli-bundle/sdk-graph.js +1 -1
  108. package/dist/cli-bundle/sdk-merge.js +1 -1
  109. package/dist/cli-bundle/sdk-query.js +1 -1
  110. package/dist/cli-bundle/sdk-runtime.js +1 -1
  111. package/dist/cli-bundle/sdk-testing.js +1 -1
  112. package/dist/cli-bundle/sdk.js +1 -1
  113. package/dist/core/extensions/reserved-host-flags.js +3 -2
  114. package/dist/core/history/workspace-history.d.ts +22 -2
  115. package/dist/core/history/workspace-history.js +60 -36
  116. package/dist/core/output/output.d.ts +2 -0
  117. package/dist/core/output/output.js +3 -2
  118. package/dist/core/shared/command-types.d.ts +2 -0
  119. package/dist/core/shared/command-types.js +2 -2
  120. package/dist/mcp/tool-definitions.js +6 -2
  121. package/dist/sdk/author-attribution.js +23 -7
  122. package/dist/sdk/cli-bootstrap.d.ts +2 -0
  123. package/dist/sdk/cli-bootstrap.js +7 -2
  124. package/dist/sdk/cli-contracts/completeness.js +51 -4
  125. package/dist/sdk/cli-contracts/flag-contracts.js +3 -2
  126. package/dist/sdk/cli-contracts/registration-helpers.js +3 -2
  127. package/dist/sdk/cli-contracts/runtime-contracts.js +14 -8
  128. package/dist/sdk/cli-contracts/tool-parameter-tables.js +116 -10
  129. package/dist/sdk/cli-contracts/tool-schema.js +18 -2
  130. package/dist/sdk/cli-program.js +3 -2
  131. package/dist/sdk/completion.js +5 -2
  132. package/dist/sdk/contracts.d.ts +1 -0
  133. package/dist/sdk/contracts.js +2 -2
  134. package/dist/sdk/core.d.ts +3 -1
  135. package/dist/sdk/core.js +4 -3
  136. package/dist/sdk/extension.js +9 -11
  137. package/dist/sdk/generated-error-code-catalog.js +112 -2
  138. package/dist/sdk/history-analytics.d.ts +141 -0
  139. package/dist/sdk/history-analytics.js +283 -0
  140. package/dist/sdk/improvement-ledger-validation.d.ts +3 -0
  141. package/dist/sdk/improvement-ledger-validation.js +63 -0
  142. package/dist/sdk/improvement-ledger.d.ts +139 -0
  143. package/dist/sdk/improvement-ledger.js +261 -0
  144. package/dist/sdk/index.d.ts +6 -2
  145. package/dist/sdk/index.js +8 -4
  146. package/dist/sdk/lifecycle/plan.js +6 -3
  147. package/dist/sdk/merge/install.js +10 -2
  148. package/dist/sdk/read-output-budget.js +24 -22
  149. package/dist/sdk/read-output-contracts.d.ts +10 -2
  150. package/dist/sdk/read-output-contracts.js +124 -65
  151. package/dist/sdk/read-output-rows.d.ts +29 -0
  152. package/dist/sdk/read-output-rows.js +100 -0
  153. package/dist/sdk/read-output-session.d.ts +69 -0
  154. package/dist/sdk/read-output-session.js +200 -0
  155. package/dist/sdk/runtime-input.d.ts +2 -0
  156. package/dist/sdk/runtime-input.js +14 -2
  157. package/dist/sdk/runtime-primitives.d.ts +1 -1
  158. package/dist/sdk/runtime-primitives.js +3 -3
  159. package/dist/sdk/runtime-stats-options.d.ts +9 -0
  160. package/dist/sdk/runtime-stats-options.js +38 -0
  161. package/dist/sdk/runtime.d.ts +1 -0
  162. package/dist/sdk/runtime.js +6 -27
  163. package/dist/sdk/stats.d.ts +40 -0
  164. package/dist/sdk/stats.js +112 -29
  165. package/docs/IMPROVEMENT_ANALYTICS.md +103 -0
  166. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +5 -5
  167. package/docs/README.md +1 -0
  168. package/docs/READ_OUTPUT_CONTRACTS.md +60 -1
  169. package/marketplace.json +2 -2
  170. package/package.json +3 -3
  171. package/packages/pm-beads/package.json +1 -1
  172. package/packages/pm-calendar/package.json +1 -1
  173. package/packages/pm-command-kit/package.json +1 -1
  174. package/packages/pm-digital-twin/package.json +1 -1
  175. package/packages/pm-governance-audit/package.json +1 -1
  176. package/packages/pm-guide-shell/package.json +1 -1
  177. package/packages/pm-kanban/package.json +1 -1
  178. package/packages/pm-lifecycle-hooks/package.json +1 -1
  179. package/packages/pm-linked-test-adapters/package.json +1 -1
  180. package/packages/pm-search-advanced/package.json +1 -1
  181. package/packages/pm-templates/package.json +1 -1
  182. package/packages/pm-todos/package.json +1 -1
  183. package/packages/pm-vcs/package.json +1 -1
  184. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  185. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  186. package/sdk/public-surface.json +374 -821
  187. package/dist/cli-bundle/chunks/append-XAJ5Z4XS.js +0 -2
  188. package/dist/cli-bundle/chunks/chunk-AJE3AHPD.js +0 -8
  189. package/dist/cli-bundle/chunks/chunk-E7BFPLUZ.js +0 -5
  190. package/dist/cli-bundle/chunks/chunk-HS7OVAUN.js +0 -164
  191. package/dist/cli-bundle/chunks/chunk-SV3YQ4RY.js +0 -2
  192. package/dist/cli-bundle/chunks/chunk-V663653R.js +0 -20
  193. package/dist/cli-bundle/chunks/chunk-XPOQQJTX.js +0 -13
  194. package/dist/cli-bundle/chunks/chunk-YCCDXBNU.js +0 -2
  195. package/dist/cli-bundle/chunks/chunk-ZFBWCKYF.js +0 -2
  196. package/dist/cli-bundle/chunks/close-DI66JMSB.js +0 -2
  197. package/dist/cli-bundle/chunks/close-many-VFKT6U3O.js +0 -2
  198. package/dist/cli-bundle/chunks/comments-E73HIEZJ.js +0 -2
  199. package/dist/cli-bundle/chunks/copy-WBYVLCPC.js +0 -2
  200. package/dist/cli-bundle/chunks/delete-6XKUVVQN.js +0 -2
  201. package/dist/cli-bundle/chunks/focus-R2AWS63Y.js +0 -2
  202. package/dist/cli-bundle/chunks/register-operations-HIBJXRGB.js +0 -2
  203. package/dist/cli-bundle/chunks/restore-FXA5QPM7.js +0 -2
  204. package/dist/cli-bundle/chunks/update-7GBO4SXG.js +0 -2
  205. package/dist/cli-bundle/chunks/update-many-VF6ZKQUO.js +0 -2
  206. package/dist/cli-bundle/focused-chunks/chunk-74CWP3A4.js +0 -2
  207. package/dist/cli-bundle/focused-chunks/chunk-7AZDTGPA.js +0 -2
  208. package/dist/cli-bundle/focused-chunks/chunk-LKQXXO62.js +0 -2
  209. package/dist/cli-bundle/focused-chunks/chunk-QL5H3AQH.js +0 -2
@@ -1,19 +1,19 @@
1
- import{A as p,Ad as cr,Af as V,B as he,Bf as ue,C as h,Cb as We,D as w,Da as He,F as ce,G as Q,H as b,I as rr,Lf as tt,Mf as rt,Na as J,Oa as ge,Pa as Ye,Qa as nr,R as L,Sc as ir,Ta as or,Tc as sr,Z as de,_ as qe,ad as Ke,b as z,bb as Be,c as v,d as S,e as Ue,f as ae,gd as Qe,hd as Je,lc as Ge,mf as et,t as je,td as ar,uc as ye,ud as Xe,uf as Ee,zd as Ze,zf as X}from"./chunk-HS7OVAUN.js";import{mkdir as _o,readFile as ho}from"node:fs/promises";import dr 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]="71a8cd89-54fc-5f8a-b93b-9e4a79bb34b6")}catch{}})();function go(e){let t=e.trim();if(!t)throw new h("--rollback requires a non-empty checkpoint ID",p.USAGE);if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new h("--rollback checkpoint ID must match [a-zA-Z0-9._-]+",p.USAGE);return t}function yo(e,t){let r=t.replace(/[-:.TZ]/g,"").slice(0,14),n=Math.random().toString(36).slice(2,8);return`${e}-${r}-${n}`}function ur(e,t){return dr.join(e,"checkpoints",t)}function lr(e,t,r){return dr.join(ur(e,t),`${r}.json`)}async function Eo(e,t,r,n){let o=ur(e,t);await _o(o,{recursive:!0});let i=lr(e,t,r);return await S(i,`${JSON.stringify(n,null,2)}
2
- `),i}function wo(e,t){if(!Array.isArray(e.items))throw new h(`Checkpoint ${t} is missing items`,p.GENERIC_FAILURE);return e.items.map(r=>{if(!r||typeof r!="object")throw new h(`Checkpoint ${t} contains an invalid item entry`,p.GENERIC_FAILURE);let n=r;if(typeof n.id!="string"||n.id.trim().length===0)throw new h(`Checkpoint ${t} contains an item entry without ID`,p.GENERIC_FAILURE);if(typeof n.target_updated_at!="string"||n.target_updated_at.trim().length===0)throw new h(`Checkpoint ${t} contains an item entry without target_updated_at`,p.GENERIC_FAILURE);return{id:n.id.trim(),target_updated_at:n.target_updated_at.trim()}})}async function bo(e,t,r,n){let o=go(r),i=lr(e,t,o);if(!await z(i))throw new h(`Checkpoint ${o} not found`,p.NOT_FOUND);let s=await ho(i,"utf8"),a;try{a=JSON.parse(s)}catch(u){throw new h(`Checkpoint ${o} contains invalid JSON: ${b(u)}`,p.GENERIC_FAILURE)}if(!a||typeof a!="object")throw new h(`Checkpoint ${o} is invalid`,p.GENERIC_FAILURE);let c=a;if(c.schema_version!==n)throw new h(`Checkpoint ${o} has unsupported schema version`,p.GENERIC_FAILURE);let d=wo(c,o);return{record:c,items:d,path:i,id:typeof c.id=="string"?c.id:o,created_at:typeof c.created_at=="string"?c.created_at:L(),author:typeof c.author=="string"?c.author:"unknown"}}async function To(e,t){let r=[],n=[];for(let o of e)try{let i=await t(o.id,o.target_updated_at);r.push({id:o.id,status:"restored",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(o.id)}catch(i){r.push({id:o.id,status:"failed",error:b(i)})}return{rows:r,restored_ids:n,failed_count:r.filter(o=>o.status==="failed").length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4507a449-1c20-5684-9ed8-e72c9bc694c1")}catch{}})();function Z(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function So(e,t){let r=Z(t);return!e||!r?null:[...e.search_providers].reverse().find(o=>(Z(o.runtime_definition?.name)??Z(o.definition?.name))===r)??null}function xo(e,t){let r=Z(t);return!e||!r?null:[...e.vector_store_adapters].reverse().find(o=>(Z(o.runtime_definition?.name)??Z(o.definition?.name))===r)??null}function Fd(e){return e.runtime_definition??e.definition}import{readFile as Io}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]="7426082f-94a6-5b4e-9748-d3faab2fe1d4")}catch{}})();var Ao=e=>Io(e,"utf8");async function vo(e,t,r=Ao){if(t!==void 0)throw new h("--body and --body-file are mutually exclusive; provide the body inline with --body or from a file with --body-file, not both.",p.USAGE,{code:"body_file_conflicts_with_body",required:"Choose exactly one body source.",why:"Both --body and --body-file set the item body; allowing both would make the effective body ambiguous.",nextSteps:["Re-run with only --body <text> or only --body-file <path>."]});let n=e.trim();if(n.length===0)throw new h("--body-file requires a file path.",p.USAGE,{code:"body_file_missing_path",required:"Pass a readable file path: --body-file <path>.",why:"An empty --body-file value has no file to read the body from."});try{return await r(n)}catch(o){let i=o?.code,s=i==="EISDIR",a=i?` (${i})`:"";throw new h(s?`--body-file "${n}" is a directory, not a file. Point it at a readable file.`:`--body-file could not read "${n}"${a}. Check that the file exists and is readable.`,p.NOT_FOUND,{code:"body_file_unreadable",required:"Point --body-file at an existing, readable file.",why:`The body content is loaded from the file at the supplied path, so an unreadable path cannot produce a body${i?` (underlying error: ${i})`:""}.`,nextSteps:[`Verify the path: ls -l "${n}"`,"Or pass the body inline with --body <text>."]})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a376062-2e23-5991-80a5-27183909caf3")}catch{}})();var Co=new Set(["none","null","undefined"]);function Wd(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new h("Config set parent-reference-policy requires --policy with one of: warn, strict_error (alias: strict)",p.USAGE)}function Lo(e){if(typeof e!="string")throw new h("--parent must be a string. Use --unset parent to clear this field.",p.USAGE);let t=e.trim();if(t.length===0)throw new h("--parent must not be empty. Use --parent none to unset.",p.USAGE);if(fr(t))throw new h(`--parent must not use placeholder token "${t}". Use --unset parent to clear this field.`,p.USAGE);return t}function fr(e){return Co.has(e.trim().toLowerCase())}function No(e,t){if(t==="strict_error")throw new h(`Parent item "${e}" was not found. Create it first or use --parent none.`,p.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${e}`]}}function Ro(e,t,r){let n=Ee(e,r),o=Ee(t,r);if(n!==o)return;let i=t!==o||e!==n?` (normalized from parent "${t}" and item "${e}")`:"";throw new h(`Parent item "${o}" cannot be the same as item "${n}"${i}. Use --unset parent to clear this field.`,p.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var nt={critical:0,high:1,medium:2,low:3,minimal:4},Do=Object.keys(nt),ko=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${Do.join(", ")}), case-insensitive`;function we(e){return new h(`Invalid priority "${e}". Accepted values: ${ko}.`,p.USAGE)}function Mo(e){if(typeof e=="number"){if(Number.isInteger(e)&&e>=0&&e<=4)return e;throw we(String(e))}if(typeof e!="string")throw we(String(e));let t=e.trim();if(t.length===0)throw we(e);let r=t.toLowerCase();if(Object.prototype.hasOwnProperty.call(nt,r))return nt[r];if(/^[0-4]$/.test(t))return Number(t);throw we(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bf76a01e-7292-59df-94ca-1e41aaff7365")}catch{}})();var Oo=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,Po=64;function eu(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new h("Config set sprint-release-format-policy requires --policy with one of: warn, strict_error (alias: strict)",p.USAGE)}function zo(e,t,r){let n=t.trim();if(n.length===0)throw new h(`--${e} must not be empty. Use --${e} none to unset.`,p.USAGE);if(n.length<=Po&&Oo.test(n))return{value:n,warnings:[]};let i="Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._/-]* (no spaces).";if(r==="strict_error")throw new h(`Invalid --${e} value "${n}". ${i}`,p.USAGE);return{value:n,warnings:[`validation_warning:${e}_format:${n}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0e997bc-8bdb-5602-8606-73ecf77b2a35")}catch{}})();var mr={open:"open_status",closed:"close_status",canceled:"canceled_status",cancelled:"canceled_status"},pr="all";function su(e){if(typeof e!="string")return!1;let t=e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);return t.length===1&&t[0]===pr}function Fo(e,t){let r=e.trim().toLowerCase();if(r.length===0)return;let n=mr[r];return n?t[n]:Ke(e,t)}function $o(e){let t=new Set(Object.keys(mr));for(let r of e.definitions){t.add(r.id);for(let n of r.aliases)t.add(n)}return[...t]}function Vo(e,t){let r=e.trim().toLowerCase(),n,o=Number.POSITIVE_INFINITY;for(let i of $o(t)){let s=Be(r,i.toLowerCase(),2);s!==null&&s<o&&(n=i,o=s)}return n}function Uo(e,t,r){if(typeof e!="string")return;let n=r?.strict===!0,o=r?.flagLabel??"--status",i=e.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length===0)return;if(i.filter(c=>c.trim().toLowerCase()===pr).length>0){if(i.length===1)return;throw new h(`Invalid ${o} value "all". Use it by itself, or omit ${o} to search every status.`,p.USAGE)}let a=[];for(let c of i){let d=Fo(c,t);if(d===void 0){if(n){let u=Vo(c,t);throw new h(`Invalid ${o} value "${c}". Use open|closed|canceled or a configured status id${u?`. Did you mean "${u}"?`:"."}`,p.USAGE)}a.push(c);continue}a.push(d)}return[...new Set(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]="b7a167e0-3041-5056-a672-ea0a054ed8df")}catch{}})();var jo={bug:"Issue",bugfix:"Issue",defect:"Issue",incident:"Issue",enhancement:"Feature",story:"Feature",userstory:"Feature","user-story":"Feature","user story":"Feature",change:"Chore",ticket:"Task",todo:"Task"};function qo(e){if(e!==void 0)return jo[e.trim().toLowerCase()]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d11dc0f-e313-5b39-965d-6bc84ad52966")}catch{}})();function hr(e){let t=[],r=new Set;for(let n of e)for(let o of Object.keys(n))r.has(o)||(r.add(o),t.push(o));return t}function ot(e){return e==null?"":Array.isArray(e)?e.map(t=>ot(t)).join(";"):typeof e=="object"?JSON.stringify(e):String(e)}function _r(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Ho(e){if(e.length===0)return"";let t=hr(e),r=[t.map(n=>_r(n)).join(",")];for(let n of e)r.push(t.map(o=>_r(ot(n[o]))).join(","));return r.join(`
1
+ import{A as p,Ad as cr,B as he,C as h,Cb as We,D as w,Da as He,F as ce,G as Q,H as b,Hf as Ee,I as rr,Mf as X,Na as J,Nf as V,Oa as ge,Of as ue,Pa as Ye,Qa as nr,R as L,Sc as ir,Ta as or,Tc as sr,Yf as tt,Z as de,Zf as rt,_ as qe,ad as Ke,b as z,bb as Be,c as v,d as S,e as Ue,f as ae,gd as Qe,hd as Je,lc as Ge,t as je,td as ar,uc as ye,ud as Xe,yf as et,zd as Ze}from"./chunk-D4FPS43D.js";import{mkdir as _o,readFile as ho}from"node:fs/promises";import dr 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]="71a8cd89-54fc-5f8a-b93b-9e4a79bb34b6")}catch{}})();function go(e){let t=e.trim();if(!t)throw new h("--rollback requires a non-empty checkpoint ID",p.USAGE);if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new h("--rollback checkpoint ID must match [a-zA-Z0-9._-]+",p.USAGE);return t}function yo(e,t){let r=t.replace(/[-:.TZ]/g,"").slice(0,14),n=Math.random().toString(36).slice(2,8);return`${e}-${r}-${n}`}function ur(e,t){return dr.join(e,"checkpoints",t)}function lr(e,t,r){return dr.join(ur(e,t),`${r}.json`)}async function Eo(e,t,r,n){let o=ur(e,t);await _o(o,{recursive:!0});let i=lr(e,t,r);return await S(i,`${JSON.stringify(n,null,2)}
2
+ `),i}function wo(e,t){if(!Array.isArray(e.items))throw new h(`Checkpoint ${t} is missing items`,p.GENERIC_FAILURE);return e.items.map(r=>{if(!r||typeof r!="object")throw new h(`Checkpoint ${t} contains an invalid item entry`,p.GENERIC_FAILURE);let n=r;if(typeof n.id!="string"||n.id.trim().length===0)throw new h(`Checkpoint ${t} contains an item entry without ID`,p.GENERIC_FAILURE);if(typeof n.target_updated_at!="string"||n.target_updated_at.trim().length===0)throw new h(`Checkpoint ${t} contains an item entry without target_updated_at`,p.GENERIC_FAILURE);return{id:n.id.trim(),target_updated_at:n.target_updated_at.trim()}})}async function bo(e,t,r,n){let o=go(r),i=lr(e,t,o);if(!await z(i))throw new h(`Checkpoint ${o} not found`,p.NOT_FOUND);let s=await ho(i,"utf8"),a;try{a=JSON.parse(s)}catch(u){throw new h(`Checkpoint ${o} contains invalid JSON: ${b(u)}`,p.GENERIC_FAILURE)}if(!a||typeof a!="object")throw new h(`Checkpoint ${o} is invalid`,p.GENERIC_FAILURE);let c=a;if(c.schema_version!==n)throw new h(`Checkpoint ${o} has unsupported schema version`,p.GENERIC_FAILURE);let d=wo(c,o);return{record:c,items:d,path:i,id:typeof c.id=="string"?c.id:o,created_at:typeof c.created_at=="string"?c.created_at:L(),author:typeof c.author=="string"?c.author:"unknown"}}async function To(e,t){let r=[],n=[];for(let o of e)try{let i=await t(o.id,o.target_updated_at);r.push({id:o.id,status:"restored",changed_fields:i.changed_fields,warnings:i.warnings}),n.push(o.id)}catch(i){r.push({id:o.id,status:"failed",error:b(i)})}return{rows:r,restored_ids:n,failed_count:r.filter(o=>o.status==="failed").length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4507a449-1c20-5684-9ed8-e72c9bc694c1")}catch{}})();function Z(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function So(e,t){let r=Z(t);return!e||!r?null:[...e.search_providers].reverse().find(o=>(Z(o.runtime_definition?.name)??Z(o.definition?.name))===r)??null}function xo(e,t){let r=Z(t);return!e||!r?null:[...e.vector_store_adapters].reverse().find(o=>(Z(o.runtime_definition?.name)??Z(o.definition?.name))===r)??null}function Fd(e){return e.runtime_definition??e.definition}import{readFile as Io}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]="7426082f-94a6-5b4e-9748-d3faab2fe1d4")}catch{}})();var Ao=e=>Io(e,"utf8");async function vo(e,t,r=Ao){if(t!==void 0)throw new h("--body and --body-file are mutually exclusive; provide the body inline with --body or from a file with --body-file, not both.",p.USAGE,{code:"body_file_conflicts_with_body",required:"Choose exactly one body source.",why:"Both --body and --body-file set the item body; allowing both would make the effective body ambiguous.",nextSteps:["Re-run with only --body <text> or only --body-file <path>."]});let n=e.trim();if(n.length===0)throw new h("--body-file requires a file path.",p.USAGE,{code:"body_file_missing_path",required:"Pass a readable file path: --body-file <path>.",why:"An empty --body-file value has no file to read the body from."});try{return await r(n)}catch(o){let i=o?.code,s=i==="EISDIR",a=i?` (${i})`:"";throw new h(s?`--body-file "${n}" is a directory, not a file. Point it at a readable file.`:`--body-file could not read "${n}"${a}. Check that the file exists and is readable.`,p.NOT_FOUND,{code:"body_file_unreadable",required:"Point --body-file at an existing, readable file.",why:`The body content is loaded from the file at the supplied path, so an unreadable path cannot produce a body${i?` (underlying error: ${i})`:""}.`,nextSteps:[`Verify the path: ls -l "${n}"`,"Or pass the body inline with --body <text>."]})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a376062-2e23-5991-80a5-27183909caf3")}catch{}})();var Co=new Set(["none","null","undefined"]);function Wd(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new h("Config set parent-reference-policy requires --policy with one of: warn, strict_error (alias: strict)",p.USAGE)}function Lo(e){if(typeof e!="string")throw new h("--parent must be a string. Use --unset parent to clear this field.",p.USAGE);let t=e.trim();if(t.length===0)throw new h("--parent must not be empty. Use --parent none to unset.",p.USAGE);if(fr(t))throw new h(`--parent must not use placeholder token "${t}". Use --unset parent to clear this field.`,p.USAGE);return t}function fr(e){return Co.has(e.trim().toLowerCase())}function No(e,t){if(t==="strict_error")throw new h(`Parent item "${e}" was not found. Create it first or use --parent none.`,p.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${e}`]}}function Ro(e,t,r){let n=Ee(e,r),o=Ee(t,r);if(n!==o)return;let i=t!==o||e!==n?` (normalized from parent "${t}" and item "${e}")`:"";throw new h(`Parent item "${o}" cannot be the same as item "${n}"${i}. Use --unset parent to clear this field.`,p.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var nt={critical:0,high:1,medium:2,low:3,minimal:4},ko=Object.keys(nt),Do=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${ko.join(", ")}), case-insensitive`;function we(e){return new h(`Invalid priority "${e}". Accepted values: ${Do}.`,p.USAGE)}function Mo(e){if(typeof e=="number"){if(Number.isInteger(e)&&e>=0&&e<=4)return e;throw we(String(e))}if(typeof e!="string")throw we(String(e));let t=e.trim();if(t.length===0)throw we(e);let r=t.toLowerCase();if(Object.prototype.hasOwnProperty.call(nt,r))return nt[r];if(/^[0-4]$/.test(t))return Number(t);throw we(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bf76a01e-7292-59df-94ca-1e41aaff7365")}catch{}})();var Oo=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,Po=64;function eu(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new h("Config set sprint-release-format-policy requires --policy with one of: warn, strict_error (alias: strict)",p.USAGE)}function zo(e,t,r){let n=t.trim();if(n.length===0)throw new h(`--${e} must not be empty. Use --${e} none to unset.`,p.USAGE);if(n.length<=Po&&Oo.test(n))return{value:n,warnings:[]};let i="Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._/-]* (no spaces).";if(r==="strict_error")throw new h(`Invalid --${e} value "${n}". ${i}`,p.USAGE);return{value:n,warnings:[`validation_warning:${e}_format:${n}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0e997bc-8bdb-5602-8606-73ecf77b2a35")}catch{}})();var mr={open:"open_status",closed:"close_status",canceled:"canceled_status",cancelled:"canceled_status"},pr="all";function su(e){if(typeof e!="string")return!1;let t=e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);return t.length===1&&t[0]===pr}function Fo(e,t){let r=e.trim().toLowerCase();if(r.length===0)return;let n=mr[r];return n?t[n]:Ke(e,t)}function $o(e){let t=new Set(Object.keys(mr));for(let r of e.definitions){t.add(r.id);for(let n of r.aliases)t.add(n)}return[...t]}function Vo(e,t){let r=e.trim().toLowerCase(),n,o=Number.POSITIVE_INFINITY;for(let i of $o(t)){let s=Be(r,i.toLowerCase(),2);s!==null&&s<o&&(n=i,o=s)}return n}function Uo(e,t,r){if(typeof e!="string")return;let n=r?.strict===!0,o=r?.flagLabel??"--status",i=e.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length===0)return;if(i.filter(c=>c.trim().toLowerCase()===pr).length>0){if(i.length===1)return;throw new h(`Invalid ${o} value "all". Use it by itself, or omit ${o} to search every status.`,p.USAGE)}let a=[];for(let c of i){let d=Fo(c,t);if(d===void 0){if(n){let u=Vo(c,t);throw new h(`Invalid ${o} value "${c}". Use open|closed|canceled or a configured status id${u?`. Did you mean "${u}"?`:"."}`,p.USAGE)}a.push(c);continue}a.push(d)}return[...new Set(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]="b7a167e0-3041-5056-a672-ea0a054ed8df")}catch{}})();var jo={bug:"Issue",bugfix:"Issue",defect:"Issue",incident:"Issue",enhancement:"Feature",story:"Feature",userstory:"Feature","user-story":"Feature","user story":"Feature",change:"Chore",ticket:"Task",todo:"Task"};function qo(e){if(e!==void 0)return jo[e.trim().toLowerCase()]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d11dc0f-e313-5b39-965d-6bc84ad52966")}catch{}})();function hr(e){let t=[],r=new Set;for(let n of e)for(let o of Object.keys(n))r.has(o)||(r.add(o),t.push(o));return t}function ot(e){return e==null?"":Array.isArray(e)?e.map(t=>ot(t)).join(";"):typeof e=="object"?JSON.stringify(e):String(e)}function _r(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Ho(e){if(e.length===0)return"";let t=hr(e),r=[t.map(n=>_r(n)).join(",")];for(let n of e)r.push(t.map(o=>_r(ot(n[o]))).join(","));return r.join(`
3
3
  `)}function Yo(e){if(e.length===0)return"";let t=hr(e),r=e.map(s=>t.map(a=>ot(s[a]))),n=t.map((s,a)=>Math.max(s.length,...r.map(c=>c[a].length))),o=(s,a)=>s.padEnd(n[a]),i=[t.map((s,a)=>o(s,a)).join(" | ")];i.push(n.map(s=>"-".repeat(s)).join("-+-"));for(let s of r)i.push(s.map((a,c)=>o(a,c)).join(" | "));return i.join(`
4
4
  `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="43a56374-808c-5fa6-bd6c-5d93175df0d2")}catch{}})();function gr(e,t){return We(e,t)}function Bo(e,t,r){let n={};for(let o of t.command_to_fields.get(r)??[]){let i=ir(e,o);i!==void 0&&(n[o.metadata_key]=sr(o,i))}return n}function Wo(e,t){for(let[r,n]of Object.entries(t)){let o=e[r];if(Array.isArray(n)){if(Array.isArray(o)){let i=o.map(a=>String(a));if(!n.map(a=>String(a)).every(a=>i.includes(a)))return!1;continue}if(!gr(o,n[n.length-1]))return!1;continue}if(!gr(o,n))return!1}return!0}import{spawnSync as Er}from"node:child_process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12bfc6e7-8979-58e8-8276-98cc859f3e32")}catch{}})();var Go="PM_DISABLE_OLLAMA_AUTO_DEFAULTS",Ko="PM_OLLAMA_MODEL",Qo="http://localhost:11434",Jo="qwen3-embedding:0.6b",Xo=".agents/pm/search/lancedb/",Zo=1500,ei=2500,ti=/qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i,ri=/embed|embedding/i,R=w;function ni(){let e=R(process.env[Go]);if(!e)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}function yr(e){return e.some(t=>R(t)!==null)}function oi(e){let t=R(e);return!!(t&&t.toLowerCase()!=="ollama")}function ii(e){let t=R(e);return!!(t&&t.toLowerCase()!=="lancedb")}function si(e){return oi(e.search?.provider)||ii(e.vector_store?.adapter)||yr([e.providers?.openai?.base_url,e.providers?.openai?.model,e.providers?.openai?.api_key])?!0:yr([e.vector_store?.qdrant?.url,e.vector_store?.qdrant?.api_key])}function ai(){let e=Er("ollama",["--version"],{encoding:"utf8",timeout:Zo});return e.error?!1:e.status===0}function ci(e){let t=e.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;let r=t.map(i=>i.split(/\s+/)[0]?.trim()).filter(i=>!!(i&&i.length>0)).filter(i=>i.toUpperCase()!=="NAME");if(r.length===0)return null;let n=r.find(i=>ti.test(i));return n||(r.find(i=>ri.test(i))??null)}function di(e){let t=R(e.providers?.ollama?.model);if(t)return t;let r=R(process.env[Ko]);if(r)return r;let n=Er("ollama",["list"],{encoding:"utf8",timeout:ei});if(!n.error&&n.status===0){let o=ci(typeof n.stdout=="string"?n.stdout:"");if(o)return o}return null}function ui(e){return{baseUrl:R(e.providers?.ollama?.base_url)===null,model:R(e.providers?.ollama?.model)===null,lancedbPath:R(e.vector_store?.lancedb?.path)===null,embeddingModel:R(e.search?.embedding_model)===null}}function li(e){return e.baseUrl||e.model||e.lancedbPath||e.embeddingModel}function fi(e,t,r){if(!t.baseUrl&&!t.model)return;let n=e.providers??={},o=n.ollama??={};t.baseUrl&&(o.base_url=Qo),t.model&&(o.model=r)}function mi(e,t){if(!t.lancedbPath)return;let r=e.vector_store??={},n=r.lancedb??={};n.path=Xo}function pi(e,t,r){if(!t.embeddingModel)return;let n=e.search??={};n.embedding_model=r}function ee(e){let t={settings:e,auto_ollama_defaults_applied:!1};if(ni()||si(e))return t;let r=ui(e);if(!li(r)||r.model&&!ai())return t;let n=structuredClone(e),o=di(n);return o?(fi(n,r,o),mi(n,r),pi(n,r,o),{settings:n,auto_ollama_defaults_applied:!0}):{...t,auto_ollama_defaults_skipped_reason:"no_installed_embedding_model",auto_ollama_defaults_remediation:`Run ollama pull ${Jo} or configure providers.ollama.model explicitly (and search.embedding_model if you need an override).`}}import{spawn as _i}from"node:child_process";import{mkdirSync as wr,rmSync as Tr,statSync as hi}from"node:fs";import be 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]="d8d5f7e9-5293-564b-bc44-f5ba30336893")}catch{}})();var Sr="reindex",gi="search/pending-refresh.json",yi="search/pending-refresh.gate.lock",Ei=3e4,wi="PM_SEARCH_REFRESH_INLINE",xr="PM_SEARCH_REFRESH_CHILD",bi=3e4;function br(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Ti(){if(br(process.env[wi])||br(process.env[xr]))return!0;let e=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||e==="test"}function Ir(e){return be.join(e,gi)}function Ar(e){return be.join(e,yi)}function Si(e){let t=Ar(e);try{if(Date.now()-hi(t).mtimeMs<Ei)return!1;Tr(t,{recursive:!0,force:!0})}catch{}try{return wr(be.dirname(t),{recursive:!0}),wr(t),!0}catch{return!1}}function xi(e){try{Tr(Ar(e),{recursive:!0,force:!0})}catch{}}async function vr(e,t,r){for(let n=0;n<50;n+=1){if(Si(e))try{return await t()}finally{xi(e)}await Ii(20)}return r}function Ii(e){return new Promise(t=>{setTimeout(t,e)})}async function st(e){let t=await v(Ir(e));if(!t||t.trim().length===0)return[];try{let r=JSON.parse(t);return Array.isArray(r.ids)?r.ids.filter(n=>typeof n=="string"&&n.length>0):[]}catch{return[]}}async function Cr(e,t){await S(Ir(e),`${JSON.stringify({ids:t})}
5
- `)}async function it(e,t){let r=t.filter(i=>typeof i=="string"&&i.trim().length>0);if(r.length===0)return;let n=async()=>{let i=await st(e),s=[...new Set([...i,...r])].sort((a,c)=>a.localeCompare(c));await Cr(e,s)};await vr(e,async()=>(await n(),!0),!1)||await n()}async function Ai(e){return vr(e,async()=>{let t=await st(e);return t.length>0&&await Cr(e,[]),t},[])}function vi(){return be.join(de(import.meta.url,["../../.."]),"dist","cli","search-refresh.js")}function at(e){try{let t=_i(process.execPath,[vi()],{detached:!0,stdio:"ignore",env:{...process.env,PM_PATH:e,[xr]:"1"}});t.on("error",()=>{}),t.unref()}catch{}}function Ci(e){setTimeout(()=>at(e),bi)}async function Lr(e,t){await it(e,t),at(e)}async function Au(e,t,r=Ci){let n=[],o=[];if(!await z(e))return{processed:o,rounds:0,warnings:n};let i;try{let l=await X(e),f=l.warnings.find(m=>m.startsWith("settings_read_"));if(f)return r(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${f}`]};i=ee(l.settings).settings}catch(l){return r(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${b(l)}`]}}let s=null;try{s=await et(e,Sr,i.locks.ttl_seconds,Ze(void 0,"pm-search-refresh"),!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms)}catch{}if(!s)return{processed:o,rounds:0,warnings:n};let a=0,c=!1,d=!1;try{for(;;){let l=await Ai(e);if(l.length===0)break;a+=1;try{let f=await t(e,l);if(n.push(...f.warnings),f.warnings.some(m=>m.startsWith("search_semantic_refresh_skipped:settings_read_failed:"))){await it(e,l),c=!0,d=!0;break}o.push(...f.refreshed)}catch(f){n.push(`search_background_refresh_failed:${b(f)}`),await it(e,l),c=!0;break}}}finally{await s?.()}return d&&r(e),(c?[]:await st(e)).length>0&&at(e),{processed:[...new Set(o)].sort((l,f)=>l.localeCompare(f)),rounds:a,warnings:n}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5ce7132-0024-5d42-9cb8-585933beb7c7")}catch{}})();var Li=3e4;function q(e,t,r=Li){let n=e??r;if(!Number.isFinite(n)||n<=0)throw new Error(`${t} timeout must be a positive finite number`);return Math.floor(n)}function H(e,t){if(e)return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error(`${t} execution requires a fetch implementation`)}async function Ni(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${b(t)})`}}async function Te(e){let t=new AbortController,r=setTimeout(()=>{t.abort()},e.timeoutMs);try{let n;try{n=await e.fetcher(e.endpoint,{method:e.method,headers:e.headers,body:JSON.stringify(e.body),signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`${e.requestLabel} timed out after ${e.timeoutMs}ms`):new Error(`${e.requestLabel} execution failed: ${b(o)}`)}if(!n.ok){let o=await Ni(n),i=o.length>0?`: ${o}`:"";throw new Error(`${e.requestLabel} failed with status ${n.status} ${n.statusText}${i}`)}try{return await n.json()}catch(o){throw new Error(`${e.responseLabel} JSON parse failed: ${b(o)}`)}}finally{clearTimeout(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]="af754be6-8026-530a-8a20-b03d4ed742e1")}catch{}})();function Du(e,t){let r=w(e);if(!r)return"unconfigured";let n=w(t);return n&&n.toLowerCase()===r.toLowerCase()?"configured":"auto-detected"}function Ri(e){let t=ce(e),r=t.toLowerCase();return r.endsWith("/embeddings")?t:r.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function Rr(e){let t=e.search?.embedding_model;return w(t)||null}function Di(e){let t=w(e.providers?.openai?.base_url),r=w(e.providers?.openai?.model);if(!t||!r)return null;let n=Rr(e),o=w(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:n??r,...o?{api_key:o}:{}}}function ki(e){let t=w(e.providers?.ollama?.base_url),r=w(e.providers?.ollama?.model);if(!t||!r)return null;let n=Rr(e);return{name:"ollama",base_url:t,model:n??r}}function Dr(e){let t=(Array.isArray(e)?e:[e]).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new Error("Embedding input must include at least one non-empty string");return t}function Mi(e){let t=[],r=[],n=new Map;for(let o of e){let i=n.get(o);if(i===void 0){let s=t.length;t.push(o),n.set(o,s),r.push(s);continue}r.push(i)}return{uniqueInputs:t,originalToUniqueIndex:r}}function Oi(e){let t=e.map((n,o)=>({embedding:n.embedding,index:n.index,position:o}));if(t.some(n=>n.index!==void 0)){for(let n of t)if(!Number.isInteger(n.index))throw new TypeError(`OpenAI embedding response entry at position ${n.position} is missing a valid integer index`);return[...t].sort((n,o)=>{let i=n.index-o.index;return i!==0?i:n.position-o.position})}return t}function Se(e){let t=Di(e),r=ki(e),n=[t,r].filter(a=>a!==null),o=w(e.search?.provider),i=o?o.toLowerCase():null;return{active:(i?n.find(a=>a.name===i):void 0)??n[0]??null,available:n}}function Nr(e){let t=ce(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:Ri(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function Pi(e,t){let r=Dr(t);return e.name==="openai"?{target:Nr(e),method:"POST",headers:{"content-type":"application/json",...e.api_key?{authorization:`Bearer ${e.api_key}`}:{}},body:{model:e.model,input:r.length===1?r[0]:r}}:{target:Nr(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:r}}}function zi(e,t){if(e.name==="openai"){let o=t.data;if(!Array.isArray(o)||o.length===0)throw new Error("OpenAI embedding response must include a non-empty data array");return Oi(o).map((s,a)=>{let c=s.embedding;if(!Q(c))throw new Error(`OpenAI embedding response entry at index ${a} is missing a numeric embedding vector`);return[...c]})}let r=t.embedding;if(Q(r))return[[...r]];let n=t.embeddings;if(Array.isArray(n)&&n.length>0)return n.map((o,i)=>{if(!Q(o))throw new Error(`Ollama embedding response entry at index ${i} is missing a numeric embedding vector`);return[...o]});throw new Error("Ollama embedding response must include embedding or embeddings vectors")}async function kr(e,t,r={}){let n=q(r.timeout_ms,"Embedding request"),o=H(r.fetcher,"Embedding request"),i=Dr(t),s=Mi(i),a=Pi(e,s.uniqueInputs),c=await Te({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:n,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),d=zi(e,c);if(d.length!==s.uniqueInputs.length)throw new Error(`Embedding response cardinality mismatch: expected ${s.uniqueInputs.length} vector(s), received ${d.length}`);return s.originalToUniqueIndex.map(u=>[...d[u]])}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="61c0153b-8fa5-5c26-aa88-ca9807f2d160")}catch{}})();var xe=["title","description","tags","status","type","priority","assignee","parent","goal","value","why_now","risk","confidence","estimated_minutes","acceptance_criteria","resolution","expected_result","actual_result","body","comments","notes","learnings","reminders","events","dependencies","plan"];function ct(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...xe];let r=new Set(xe),n=Array.from(new Set(t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0&&r.has(o))));return n.length>0?n:[...xe]}var Fi=8e3,dt=3200,Y="...[semantic corpus truncated]",$i="search_embedding_corpus_max_characters_invalid:using_provider_default";function k(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function Vi(e){return(e.reminders??[]).map(t=>k([t.at,t.text]))}function Ui(e){return(e.events??[]).map(t=>k([t.start_at,t.end_at,t.title,t.description,t.location,t.all_day===!0?"all day":void 0,t.timezone,t.recurrence?.freq,t.recurrence?.interval,t.recurrence?.count,t.recurrence?.until,t.recurrence?.by_weekday?.join(" "),t.recurrence?.by_month_day?.join(" "),t.recurrence?.exdates?.join(" ")]))}function ji(e,t){e.push(t.title,t.body,t.status,t.owner,t.evidence,t.blocked_reason,t.superseded_by);for(let r of t.linked_items??[])e.push(`${r.kind} ${r.id}`,r.note);for(let r of t.files??[])e.push(r.path,r.note);for(let r of t.tests??[])e.push(r.command,r.path,r.note);for(let r of t.docs??[])e.push(r.path,r.note)}function qi(e,t){for(let r of t.plan_decisions??[])e.push(r.decision,r.rationale,r.evidence);for(let r of t.plan_discoveries??[])e.push(r.text);for(let r of t.plan_validation??[])e.push(r.text,r.command,r.expected)}function Ou(e){let t=[];t.push(e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context);for(let r of e.plan_steps??[])ji(t,r);return qi(t,e),t.filter(r=>typeof r=="string"&&r.length>0).join(" ")}function Hi(e){let t=(e.plan_steps??[]).map(s=>k([s.order,s.id,s.title,s.body,s.status,s.owner,s.evidence,s.blocked_reason,s.superseded_by,(s.linked_items??[]).map(a=>k([a.kind,a.id,a.note])).join(" "),(s.files??[]).map(a=>k([a.path,a.note])).join(" "),(s.tests??[]).map(a=>k([a.command,a.path,a.note])).join(" "),(s.docs??[]).map(a=>k([a.path,a.note])).join(" ")])),r=(e.plan_decisions??[]).map(s=>k([s.decision,s.rationale,s.evidence,s.step_id])),n=(e.plan_discoveries??[]).map(s=>k([s.text,s.step_id])),o=(e.plan_validation??[]).map(s=>k([s.text,s.command,s.expected]));if([e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context,...t,...r,...n,...o].some(s=>s!==void 0))return{mode:e.plan_mode,scope:e.plan_scope,harness:e.plan_harness,resume_context:e.plan_resume_context,steps:t,decisions:r,discoveries:n,validation:o}}function D(e){return typeof e=="string"&&e.trim().length>0}var Yi={title:e=>e.metadata.title,description:e=>e.metadata.description,tags:e=>e.metadata.tags,status:e=>e.metadata.status,type:e=>e.metadata.type,priority:e=>typeof e.metadata.priority=="number"?e.metadata.priority:void 0,assignee:e=>D(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>D(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>D(e.metadata.goal)?e.metadata.goal:void 0,value:e=>D(e.metadata.value)?e.metadata.value:void 0,why_now:e=>D(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>D(e.metadata.risk)?e.metadata.risk:void 0,confidence:e=>e.metadata.confidence!==void 0&&e.metadata.confidence!==null?e.metadata.confidence:void 0,estimated_minutes:e=>typeof e.metadata.estimated_minutes=="number"?e.metadata.estimated_minutes:void 0,acceptance_criteria:e=>D(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>D(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>D(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>D(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>(e.metadata.comments??[]).map(t=>t.text),notes:e=>(e.metadata.notes??[]).map(t=>t.text),learnings:e=>(e.metadata.learnings??[]).map(t=>t.text),reminders:e=>Vi(e.metadata),events:e=>Ui(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>Hi(e.metadata)};function Mr(e,t={}){let r=t.fields??xe,n={};for(let o of r){let i=Yi[o];if(!i)continue;let s=i(e);s!==void 0&&(n[o]=s)}return n}function Bi(e){return e?.trim().toLowerCase()==="ollama"?dt:Fi}function te(e,t){let r=Bi(e),n=rr(t);return n!==null?{maxCharacters:n,warning:null}:{maxCharacters:r,warning:t==null?null:$i}}function ut(e,t={}){let r=JSON.stringify(Mr(e,{fields:t.fields})),n=te(t.providerName,t.maxCharacters).maxCharacters;if(r.length<=n)return r;if(n<=Y.length)return Y.slice(0,n);let o=Math.max(0,n-Y.length);return`${r.slice(0,o)}${Y}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c518b97-bc75-5e3f-91e8-d6779d565558")}catch{}})();function Wi(e,t){let r=e.search.embedding_batch_size,n=e.search.embedding_timeout_ms,o=e.search.scanner_max_batch_retries,i=Number.isFinite(r)&&r>0?Math.floor(r):1,s=Number.isFinite(n)&&n>0?Math.floor(n):3e4,a=Number.isFinite(o)&&o>=0?Math.floor(o):0;return{batchSize:i,timeoutMs:s,maxRetries:a,maxBatchInputCharacters:Number.POSITIVE_INFINITY,maxInputCharacters:t}}function Gi(e,t,r){let n=[],o=[],i=0;for(let s of e){let a=o.length>=t,c=o.length>0&&Number.isFinite(r)&&i+s.length>r;(a||c)&&(n.push(o),o=[],i=0),o.push(s),i+=s.length}return n.push(o),n}function Ki(e,t){return e.name!=="ollama"?t:{...t,maxBatchInputCharacters:dt}}function Qi(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let r=Math.max(0,t-Y.length);return`${e.slice(0,r)}${Y}`.slice(0,t)}function Or(e){let t=b(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function Ji(e,t,r,n,o,i){let s=`Embedding batch ${t} failed after ${o} attempt(s): ${b(i)}`,a=`provider=${e.name} model=${e.model} batch_size=${r} timeout_ms=${n}`;return Or(i)?`${s} (${a}; guidance=check provider availability or lower search.embedding_batch_size, raise search.embedding_timeout_ms, or run keyword search while semantic indexing catches up)`:`${s} (${a})`}async function lt(e,t,r,n,o,i){let s=null;for(let a=0;a<=o;a+=1)try{let c=await kr(e,t,{timeout_ms:n});return a>0&&i.push(`search_embedding_batch_retry_succeeded:batch=${r}:attempt=${a+1}:size=${t.length}`),c}catch(c){if(s=c,Or(c)&&t.length>1){let d=Math.ceil(t.length/2),u=t.slice(0,d),l=t.slice(d);return i.push(`search_embedding_batch_split_after_timeout:batch=${r}:size=${t.length}:parts=${u.length}|${l.length}`),[...await lt(e,u,`${r}.1`,n,o,i),...await lt(e,l,`${r}.2`,n,o,i)]}if(a<o){let d=Math.min(1e3*2**a,8e3);await new Promise(u=>setTimeout(u,d))}}throw new Error(Ji(e,r,t.length,n,o+1,s))}async function ft(e,t,r,n={}){if(r.length===0)return{vectors:[],warnings:[]};let o=[],i=te(e.name,t.search.embedding_corpus_max_characters);i.warning&&o.push(i.warning);let s=Ki(e,Wi(t,i.maxCharacters)),a=0,c=r.map(f=>{let m=Qi(f,s.maxInputCharacters);return m.length<f.length&&(a+=1),m});a>0&&o.push(`search_embedding_input_truncated:count=${a}:max_characters=${s.maxInputCharacters}`);let d=Gi(c,s.batchSize,s.maxBatchInputCharacters),u=[],l=0;for(let f=0;f<d.length;f+=1){let m=d[f];n.onProgress?.({batch_index:f+1,batch_total:d.length,batch_size:m.length,completed_inputs:l,total_inputs:c.length,phase:"start"}),u.push(...await lt(e,m,String(f+1),s.timeoutMs,s.maxRetries,o)),l+=m.length,n.onProgress?.({batch_index:f+1,batch_total:d.length,batch_size:m.length,completed_inputs:l,total_inputs:c.length,phase:"complete"})}return{vectors:u,warnings:o}}import{mkdir as Xi,readFile as Zi,stat as _t,unlink as es}from"node:fs/promises";import{basename as Pr,dirname as mt,isAbsolute as ts,join as rs,resolve as ht}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]="7bac9506-dcad-5e52-848b-3e2631d4936c")}catch{}})();var gt="pm_items",ns=/[^a-zA-Z0-9_-]/g,os=128,is=".pm-cli-local-vectors",pt=1,B=new Map;function fe(e){return(w(e.collection_name)??gt).replaceAll(ns,"_").slice(0,os)}function Ie(e){if(!Q(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function Fr(e){if(!Number.isFinite(e)||e<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(e)}function ss(e){let t=e.result;if(!Array.isArray(t))throw new TypeError("Qdrant query response must include a result array");let r=t.map((n,o)=>{let i=n.id,s=typeof i=="number"?String(i):i,a=w(s);if(!a)throw new Error(`Qdrant query response entry at index ${o} is missing a non-empty id`);let c=n.score;if(typeof c!="number"||!Number.isFinite(c))throw new TypeError(`Qdrant query response entry at index ${o} is missing a finite numeric score`);let d=n.payload;if(d!==void 0&&(typeof d!="object"||d===null||Array.isArray(d)))throw new Error(`Qdrant query response entry at index ${o} must provide payload as an object when set`);return{id:a,score:c,...d?{payload:d}:{}}});return r.sort((n,o)=>n.score!==o.score?o.score-n.score:n.id.localeCompare(o.id)),r}function yt(e){let t=w(e.result?.status);if(t)return{status:t};let r=w(e.status);if(r)return{status:r};throw new Error("Qdrant upsert response must include status metadata")}async function le(e,t,r,n,o){return await Te({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:r,fetcher:n,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function as(e){let t=w(e.vector_store?.qdrant?.url);if(!t)return null;let r=w(e.vector_store?.collection_name),n=w(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...r&&r!==gt?{collection_name:r}:{},...n?{api_key:n}:{}}}function cs(e){let t=ht(e),r=mt(t);return Pr(t)==="pm"&&Pr(r)===".agents"?mt(r):t}function ds(e,t){return!t||ts(e)?e:ht(cs(t),e)}function us(e,t){let r=w(e.vector_store?.lancedb?.path);if(!r)return null;let n=w(e.vector_store?.collection_name);return{name:"lancedb",path:ds(r,t),...n&&n!==gt?{collection_name:n}:{}}}function ls(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector upsert records must include at least one entry");return e.map((t,r)=>{let n=w(t.id);if(!n)throw new Error(`Vector upsert record at index ${r} is missing a non-empty id`);let o=Ie(t.vector),i=t.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`Vector upsert record at index ${r} must provide payload as an object when set`);return{id:n,vector:o,...i?{payload:i}:{}}})}function fs(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector delete ids must include at least one entry");let t=e.map((n,o)=>{let i=w(n);if(!i)throw new Error(`Vector delete id at index ${o} is missing a non-empty value`);return i}).sort((n,o)=>n.localeCompare(o)),r=[];for(let n of t)r.at(-1)!==n&&r.push(n);return r}function ms(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function ps(e){return e.replace(/\/points\?wait=true$/,"")}function Ae(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function ve(e,t){return re(e,t)}function re(e,t){return rs(ht(e),is,`${t}.json`)}function Et(e,t){return typeof e=="object"&&e!==null&&e.code===t}function _s(e,t,r){let n=w(e.id);if(!n)throw new Error(`LanceDB local snapshot '${r}' record at index ${t} is missing a non-empty id`);let o=Ie(e.vector),i=e.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`LanceDB local snapshot '${r}' record '${n}' must provide payload as an object when set`);return{id:n,vector:o,...i?{payload:i}:{}}}function hs(e,t,r){let n;try{n=JSON.parse(r)}catch(c){throw new Error(`LanceDB local snapshot at '${e}' is not valid JSON: ${b(c)}`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`LanceDB local snapshot at '${e}' must be a JSON object`);if(n.version!==pt)throw new Error(`LanceDB local snapshot at '${e}' must include version=${pt}`);let i=w(n.table);if(!i)throw new Error(`LanceDB local snapshot at '${e}' must include a non-empty table value`);if(i!==t)throw new Error(`LanceDB local snapshot at '${e}' table mismatch: expected '${t}', received '${i}'`);let s=n.records;if(!Array.isArray(s))throw new TypeError(`LanceDB local snapshot at '${e}' must include a records array`);let a=new Map;for(let c=0;c<s.length;c+=1){let d=_s(s[c],c,e);a.set(d.id,d)}return a}async function gs(e){try{let t=await _t(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!Et(t,"ENOENT"))throw t;return null}}function ys(e,t){if(!t)return null;if(t.mtimeMs===null&&t.size===null&&t.records.size===0)return t.records;let r=new Map;return B.set(e,{records:r,mtimeMs:null,size:null}),r}function Es(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function wt(e,t){let r=ve(e,t),n=re(e,t),o=await gs(n),i=B.get(r);if(!o){let a=ys(r,i);if(a)return a}if(Es(i,o))return i.records;let s=new Map;try{let a=await Zi(n,"utf8");s=hs(n,t,a)}catch(a){if(!Et(a,"ENOENT"))throw a}return B.set(r,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function ws(e){let t=[...e.values()];return t.sort((r,n)=>r.id.localeCompare(n.id)),t.map(r=>({id:r.id,vector:[...r.vector],...r.payload?{payload:r.payload}:{}}))}async function $r(e){try{await es(e)}catch(t){if(!Et(t,"ENOENT"))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${b(t)}`)}}async function Vr(e,t,r){let n=re(e,t);if(r.size===0){await $r(n);return}let o=mt(n);try{await Xi(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${b(s)}`)}let i=`${JSON.stringify({version:pt,table:t,records:ws(r)})}
5
+ `)}async function it(e,t){let r=t.filter(i=>typeof i=="string"&&i.trim().length>0);if(r.length===0)return;let n=async()=>{let i=await st(e),s=[...new Set([...i,...r])].sort((a,c)=>a.localeCompare(c));await Cr(e,s)};await vr(e,async()=>(await n(),!0),!1)||await n()}async function Ai(e){return vr(e,async()=>{let t=await st(e);return t.length>0&&await Cr(e,[]),t},[])}function vi(){return be.join(de(import.meta.url,["../../.."]),"dist","cli","search-refresh.js")}function at(e){try{let t=_i(process.execPath,[vi()],{detached:!0,stdio:"ignore",env:{...process.env,PM_PATH:e,[xr]:"1"}});t.on("error",()=>{}),t.unref()}catch{}}function Ci(e){setTimeout(()=>at(e),bi)}async function Lr(e,t){await it(e,t),at(e)}async function Au(e,t,r=Ci){let n=[],o=[];if(!await z(e))return{processed:o,rounds:0,warnings:n};let i;try{let l=await X(e),f=l.warnings.find(m=>m.startsWith("settings_read_"));if(f)return r(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${f}`]};i=ee(l.settings).settings}catch(l){return r(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${b(l)}`]}}let s=null;try{s=await et(e,Sr,i.locks.ttl_seconds,Ze(void 0,"pm-search-refresh"),!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms)}catch{}if(!s)return{processed:o,rounds:0,warnings:n};let a=0,c=!1,d=!1;try{for(;;){let l=await Ai(e);if(l.length===0)break;a+=1;try{let f=await t(e,l);if(n.push(...f.warnings),f.warnings.some(m=>m.startsWith("search_semantic_refresh_skipped:settings_read_failed:"))){await it(e,l),c=!0,d=!0;break}o.push(...f.refreshed)}catch(f){n.push(`search_background_refresh_failed:${b(f)}`),await it(e,l),c=!0;break}}}finally{await s?.()}return d&&r(e),(c?[]:await st(e)).length>0&&at(e),{processed:[...new Set(o)].sort((l,f)=>l.localeCompare(f)),rounds:a,warnings:n}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5ce7132-0024-5d42-9cb8-585933beb7c7")}catch{}})();var Li=3e4;function q(e,t,r=Li){let n=e??r;if(!Number.isFinite(n)||n<=0)throw new Error(`${t} timeout must be a positive finite number`);return Math.floor(n)}function H(e,t){if(e)return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error(`${t} execution requires a fetch implementation`)}async function Ni(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${b(t)})`}}async function Te(e){let t=new AbortController,r=setTimeout(()=>{t.abort()},e.timeoutMs);try{let n;try{n=await e.fetcher(e.endpoint,{method:e.method,headers:e.headers,body:JSON.stringify(e.body),signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`${e.requestLabel} timed out after ${e.timeoutMs}ms`):new Error(`${e.requestLabel} execution failed: ${b(o)}`)}if(!n.ok){let o=await Ni(n),i=o.length>0?`: ${o}`:"";throw new Error(`${e.requestLabel} failed with status ${n.status} ${n.statusText}${i}`)}try{return await n.json()}catch(o){throw new Error(`${e.responseLabel} JSON parse failed: ${b(o)}`)}}finally{clearTimeout(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]="af754be6-8026-530a-8a20-b03d4ed742e1")}catch{}})();function ku(e,t){let r=w(e);if(!r)return"unconfigured";let n=w(t);return n&&n.toLowerCase()===r.toLowerCase()?"configured":"auto-detected"}function Ri(e){let t=ce(e),r=t.toLowerCase();return r.endsWith("/embeddings")?t:r.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function Rr(e){let t=e.search?.embedding_model;return w(t)||null}function ki(e){let t=w(e.providers?.openai?.base_url),r=w(e.providers?.openai?.model);if(!t||!r)return null;let n=Rr(e),o=w(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:n??r,...o?{api_key:o}:{}}}function Di(e){let t=w(e.providers?.ollama?.base_url),r=w(e.providers?.ollama?.model);if(!t||!r)return null;let n=Rr(e);return{name:"ollama",base_url:t,model:n??r}}function kr(e){let t=(Array.isArray(e)?e:[e]).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new Error("Embedding input must include at least one non-empty string");return t}function Mi(e){let t=[],r=[],n=new Map;for(let o of e){let i=n.get(o);if(i===void 0){let s=t.length;t.push(o),n.set(o,s),r.push(s);continue}r.push(i)}return{uniqueInputs:t,originalToUniqueIndex:r}}function Oi(e){let t=e.map((n,o)=>({embedding:n.embedding,index:n.index,position:o}));if(t.some(n=>n.index!==void 0)){for(let n of t)if(!Number.isInteger(n.index))throw new TypeError(`OpenAI embedding response entry at position ${n.position} is missing a valid integer index`);return[...t].sort((n,o)=>{let i=n.index-o.index;return i!==0?i:n.position-o.position})}return t}function Se(e){let t=ki(e),r=Di(e),n=[t,r].filter(a=>a!==null),o=w(e.search?.provider),i=o?o.toLowerCase():null;return{active:(i?n.find(a=>a.name===i):void 0)??n[0]??null,available:n}}function Nr(e){let t=ce(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:Ri(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function Pi(e,t){let r=kr(t);return e.name==="openai"?{target:Nr(e),method:"POST",headers:{"content-type":"application/json",...e.api_key?{authorization:`Bearer ${e.api_key}`}:{}},body:{model:e.model,input:r.length===1?r[0]:r}}:{target:Nr(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:r}}}function zi(e,t){if(e.name==="openai"){let o=t.data;if(!Array.isArray(o)||o.length===0)throw new Error("OpenAI embedding response must include a non-empty data array");return Oi(o).map((s,a)=>{let c=s.embedding;if(!Q(c))throw new Error(`OpenAI embedding response entry at index ${a} is missing a numeric embedding vector`);return[...c]})}let r=t.embedding;if(Q(r))return[[...r]];let n=t.embeddings;if(Array.isArray(n)&&n.length>0)return n.map((o,i)=>{if(!Q(o))throw new Error(`Ollama embedding response entry at index ${i} is missing a numeric embedding vector`);return[...o]});throw new Error("Ollama embedding response must include embedding or embeddings vectors")}async function Dr(e,t,r={}){let n=q(r.timeout_ms,"Embedding request"),o=H(r.fetcher,"Embedding request"),i=kr(t),s=Mi(i),a=Pi(e,s.uniqueInputs),c=await Te({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:n,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),d=zi(e,c);if(d.length!==s.uniqueInputs.length)throw new Error(`Embedding response cardinality mismatch: expected ${s.uniqueInputs.length} vector(s), received ${d.length}`);return s.originalToUniqueIndex.map(u=>[...d[u]])}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="61c0153b-8fa5-5c26-aa88-ca9807f2d160")}catch{}})();var xe=["title","description","tags","status","type","priority","assignee","parent","goal","value","why_now","risk","confidence","estimated_minutes","acceptance_criteria","resolution","expected_result","actual_result","body","comments","notes","learnings","reminders","events","dependencies","plan"];function ct(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...xe];let r=new Set(xe),n=Array.from(new Set(t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0&&r.has(o))));return n.length>0?n:[...xe]}var Fi=8e3,dt=3200,Y="...[semantic corpus truncated]",$i="search_embedding_corpus_max_characters_invalid:using_provider_default";function D(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function Vi(e){return(e.reminders??[]).map(t=>D([t.at,t.text]))}function Ui(e){return(e.events??[]).map(t=>D([t.start_at,t.end_at,t.title,t.description,t.location,t.all_day===!0?"all day":void 0,t.timezone,t.recurrence?.freq,t.recurrence?.interval,t.recurrence?.count,t.recurrence?.until,t.recurrence?.by_weekday?.join(" "),t.recurrence?.by_month_day?.join(" "),t.recurrence?.exdates?.join(" ")]))}function ji(e,t){e.push(t.title,t.body,t.status,t.owner,t.evidence,t.blocked_reason,t.superseded_by);for(let r of t.linked_items??[])e.push(`${r.kind} ${r.id}`,r.note);for(let r of t.files??[])e.push(r.path,r.note);for(let r of t.tests??[])e.push(r.command,r.path,r.note);for(let r of t.docs??[])e.push(r.path,r.note)}function qi(e,t){for(let r of t.plan_decisions??[])e.push(r.decision,r.rationale,r.evidence);for(let r of t.plan_discoveries??[])e.push(r.text);for(let r of t.plan_validation??[])e.push(r.text,r.command,r.expected)}function Ou(e){let t=[];t.push(e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context);for(let r of e.plan_steps??[])ji(t,r);return qi(t,e),t.filter(r=>typeof r=="string"&&r.length>0).join(" ")}function Hi(e){let t=(e.plan_steps??[]).map(s=>D([s.order,s.id,s.title,s.body,s.status,s.owner,s.evidence,s.blocked_reason,s.superseded_by,(s.linked_items??[]).map(a=>D([a.kind,a.id,a.note])).join(" "),(s.files??[]).map(a=>D([a.path,a.note])).join(" "),(s.tests??[]).map(a=>D([a.command,a.path,a.note])).join(" "),(s.docs??[]).map(a=>D([a.path,a.note])).join(" ")])),r=(e.plan_decisions??[]).map(s=>D([s.decision,s.rationale,s.evidence,s.step_id])),n=(e.plan_discoveries??[]).map(s=>D([s.text,s.step_id])),o=(e.plan_validation??[]).map(s=>D([s.text,s.command,s.expected]));if([e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context,...t,...r,...n,...o].some(s=>s!==void 0))return{mode:e.plan_mode,scope:e.plan_scope,harness:e.plan_harness,resume_context:e.plan_resume_context,steps:t,decisions:r,discoveries:n,validation:o}}function k(e){return typeof e=="string"&&e.trim().length>0}var Yi={title:e=>e.metadata.title,description:e=>e.metadata.description,tags:e=>e.metadata.tags,status:e=>e.metadata.status,type:e=>e.metadata.type,priority:e=>typeof e.metadata.priority=="number"?e.metadata.priority:void 0,assignee:e=>k(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>k(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>k(e.metadata.goal)?e.metadata.goal:void 0,value:e=>k(e.metadata.value)?e.metadata.value:void 0,why_now:e=>k(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>k(e.metadata.risk)?e.metadata.risk:void 0,confidence:e=>e.metadata.confidence!==void 0&&e.metadata.confidence!==null?e.metadata.confidence:void 0,estimated_minutes:e=>typeof e.metadata.estimated_minutes=="number"?e.metadata.estimated_minutes:void 0,acceptance_criteria:e=>k(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>k(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>k(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>k(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>(e.metadata.comments??[]).map(t=>t.text),notes:e=>(e.metadata.notes??[]).map(t=>t.text),learnings:e=>(e.metadata.learnings??[]).map(t=>t.text),reminders:e=>Vi(e.metadata),events:e=>Ui(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>Hi(e.metadata)};function Mr(e,t={}){let r=t.fields??xe,n={};for(let o of r){let i=Yi[o];if(!i)continue;let s=i(e);s!==void 0&&(n[o]=s)}return n}function Bi(e){return e?.trim().toLowerCase()==="ollama"?dt:Fi}function te(e,t){let r=Bi(e),n=rr(t);return n!==null?{maxCharacters:n,warning:null}:{maxCharacters:r,warning:t==null?null:$i}}function ut(e,t={}){let r=JSON.stringify(Mr(e,{fields:t.fields})),n=te(t.providerName,t.maxCharacters).maxCharacters;if(r.length<=n)return r;if(n<=Y.length)return Y.slice(0,n);let o=Math.max(0,n-Y.length);return`${r.slice(0,o)}${Y}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c518b97-bc75-5e3f-91e8-d6779d565558")}catch{}})();function Wi(e,t){let r=e.search.embedding_batch_size,n=e.search.embedding_timeout_ms,o=e.search.scanner_max_batch_retries,i=Number.isFinite(r)&&r>0?Math.floor(r):1,s=Number.isFinite(n)&&n>0?Math.floor(n):3e4,a=Number.isFinite(o)&&o>=0?Math.floor(o):0;return{batchSize:i,timeoutMs:s,maxRetries:a,maxBatchInputCharacters:Number.POSITIVE_INFINITY,maxInputCharacters:t}}function Gi(e,t,r){let n=[],o=[],i=0;for(let s of e){let a=o.length>=t,c=o.length>0&&Number.isFinite(r)&&i+s.length>r;(a||c)&&(n.push(o),o=[],i=0),o.push(s),i+=s.length}return n.push(o),n}function Ki(e,t){return e.name!=="ollama"?t:{...t,maxBatchInputCharacters:dt}}function Qi(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let r=Math.max(0,t-Y.length);return`${e.slice(0,r)}${Y}`.slice(0,t)}function Or(e){let t=b(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function Ji(e,t,r,n,o,i){let s=`Embedding batch ${t} failed after ${o} attempt(s): ${b(i)}`,a=`provider=${e.name} model=${e.model} batch_size=${r} timeout_ms=${n}`;return Or(i)?`${s} (${a}; guidance=check provider availability or lower search.embedding_batch_size, raise search.embedding_timeout_ms, or run keyword search while semantic indexing catches up)`:`${s} (${a})`}async function lt(e,t,r,n,o,i){let s=null;for(let a=0;a<=o;a+=1)try{let c=await Dr(e,t,{timeout_ms:n});return a>0&&i.push(`search_embedding_batch_retry_succeeded:batch=${r}:attempt=${a+1}:size=${t.length}`),c}catch(c){if(s=c,Or(c)&&t.length>1){let d=Math.ceil(t.length/2),u=t.slice(0,d),l=t.slice(d);return i.push(`search_embedding_batch_split_after_timeout:batch=${r}:size=${t.length}:parts=${u.length}|${l.length}`),[...await lt(e,u,`${r}.1`,n,o,i),...await lt(e,l,`${r}.2`,n,o,i)]}if(a<o){let d=Math.min(1e3*2**a,8e3);await new Promise(u=>setTimeout(u,d))}}throw new Error(Ji(e,r,t.length,n,o+1,s))}async function ft(e,t,r,n={}){if(r.length===0)return{vectors:[],warnings:[]};let o=[],i=te(e.name,t.search.embedding_corpus_max_characters);i.warning&&o.push(i.warning);let s=Ki(e,Wi(t,i.maxCharacters)),a=0,c=r.map(f=>{let m=Qi(f,s.maxInputCharacters);return m.length<f.length&&(a+=1),m});a>0&&o.push(`search_embedding_input_truncated:count=${a}:max_characters=${s.maxInputCharacters}`);let d=Gi(c,s.batchSize,s.maxBatchInputCharacters),u=[],l=0;for(let f=0;f<d.length;f+=1){let m=d[f];n.onProgress?.({batch_index:f+1,batch_total:d.length,batch_size:m.length,completed_inputs:l,total_inputs:c.length,phase:"start"}),u.push(...await lt(e,m,String(f+1),s.timeoutMs,s.maxRetries,o)),l+=m.length,n.onProgress?.({batch_index:f+1,batch_total:d.length,batch_size:m.length,completed_inputs:l,total_inputs:c.length,phase:"complete"})}return{vectors:u,warnings:o}}import{mkdir as Xi,readFile as Zi,stat as _t,unlink as es}from"node:fs/promises";import{basename as Pr,dirname as mt,isAbsolute as ts,join as rs,resolve as ht}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]="7bac9506-dcad-5e52-848b-3e2631d4936c")}catch{}})();var gt="pm_items",ns=/[^a-zA-Z0-9_-]/g,os=128,is=".pm-cli-local-vectors",pt=1,B=new Map;function fe(e){return(w(e.collection_name)??gt).replaceAll(ns,"_").slice(0,os)}function Ie(e){if(!Q(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function Fr(e){if(!Number.isFinite(e)||e<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(e)}function ss(e){let t=e.result;if(!Array.isArray(t))throw new TypeError("Qdrant query response must include a result array");let r=t.map((n,o)=>{let i=n.id,s=typeof i=="number"?String(i):i,a=w(s);if(!a)throw new Error(`Qdrant query response entry at index ${o} is missing a non-empty id`);let c=n.score;if(typeof c!="number"||!Number.isFinite(c))throw new TypeError(`Qdrant query response entry at index ${o} is missing a finite numeric score`);let d=n.payload;if(d!==void 0&&(typeof d!="object"||d===null||Array.isArray(d)))throw new Error(`Qdrant query response entry at index ${o} must provide payload as an object when set`);return{id:a,score:c,...d?{payload:d}:{}}});return r.sort((n,o)=>n.score!==o.score?o.score-n.score:n.id.localeCompare(o.id)),r}function yt(e){let t=w(e.result?.status);if(t)return{status:t};let r=w(e.status);if(r)return{status:r};throw new Error("Qdrant upsert response must include status metadata")}async function le(e,t,r,n,o){return await Te({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:r,fetcher:n,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function as(e){let t=w(e.vector_store?.qdrant?.url);if(!t)return null;let r=w(e.vector_store?.collection_name),n=w(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...r&&r!==gt?{collection_name:r}:{},...n?{api_key:n}:{}}}function cs(e){let t=ht(e),r=mt(t);return Pr(t)==="pm"&&Pr(r)===".agents"?mt(r):t}function ds(e,t){return!t||ts(e)?e:ht(cs(t),e)}function us(e,t){let r=w(e.vector_store?.lancedb?.path);if(!r)return null;let n=w(e.vector_store?.collection_name);return{name:"lancedb",path:ds(r,t),...n&&n!==gt?{collection_name:n}:{}}}function ls(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector upsert records must include at least one entry");return e.map((t,r)=>{let n=w(t.id);if(!n)throw new Error(`Vector upsert record at index ${r} is missing a non-empty id`);let o=Ie(t.vector),i=t.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`Vector upsert record at index ${r} must provide payload as an object when set`);return{id:n,vector:o,...i?{payload:i}:{}}})}function fs(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector delete ids must include at least one entry");let t=e.map((n,o)=>{let i=w(n);if(!i)throw new Error(`Vector delete id at index ${o} is missing a non-empty value`);return i}).sort((n,o)=>n.localeCompare(o)),r=[];for(let n of t)r.at(-1)!==n&&r.push(n);return r}function ms(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function ps(e){return e.replace(/\/points\?wait=true$/,"")}function Ae(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function ve(e,t){return re(e,t)}function re(e,t){return rs(ht(e),is,`${t}.json`)}function Et(e,t){return typeof e=="object"&&e!==null&&e.code===t}function _s(e,t,r){let n=w(e.id);if(!n)throw new Error(`LanceDB local snapshot '${r}' record at index ${t} is missing a non-empty id`);let o=Ie(e.vector),i=e.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`LanceDB local snapshot '${r}' record '${n}' must provide payload as an object when set`);return{id:n,vector:o,...i?{payload:i}:{}}}function hs(e,t,r){let n;try{n=JSON.parse(r)}catch(c){throw new Error(`LanceDB local snapshot at '${e}' is not valid JSON: ${b(c)}`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`LanceDB local snapshot at '${e}' must be a JSON object`);if(n.version!==pt)throw new Error(`LanceDB local snapshot at '${e}' must include version=${pt}`);let i=w(n.table);if(!i)throw new Error(`LanceDB local snapshot at '${e}' must include a non-empty table value`);if(i!==t)throw new Error(`LanceDB local snapshot at '${e}' table mismatch: expected '${t}', received '${i}'`);let s=n.records;if(!Array.isArray(s))throw new TypeError(`LanceDB local snapshot at '${e}' must include a records array`);let a=new Map;for(let c=0;c<s.length;c+=1){let d=_s(s[c],c,e);a.set(d.id,d)}return a}async function gs(e){try{let t=await _t(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!Et(t,"ENOENT"))throw t;return null}}function ys(e,t){if(!t)return null;if(t.mtimeMs===null&&t.size===null&&t.records.size===0)return t.records;let r=new Map;return B.set(e,{records:r,mtimeMs:null,size:null}),r}function Es(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function wt(e,t){let r=ve(e,t),n=re(e,t),o=await gs(n),i=B.get(r);if(!o){let a=ys(r,i);if(a)return a}if(Es(i,o))return i.records;let s=new Map;try{let a=await Zi(n,"utf8");s=hs(n,t,a)}catch(a){if(!Et(a,"ENOENT"))throw a}return B.set(r,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function ws(e){let t=[...e.values()];return t.sort((r,n)=>r.id.localeCompare(n.id)),t.map(r=>({id:r.id,vector:[...r.vector],...r.payload?{payload:r.payload}:{}}))}async function $r(e){try{await es(e)}catch(t){if(!Et(t,"ENOENT"))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${b(t)}`)}}async function Vr(e,t,r){let n=re(e,t);if(r.size===0){await $r(n);return}let o=mt(n);try{await Xi(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${b(s)}`)}let i=`${JSON.stringify({version:pt,table:t,records:ws(r)})}
6
6
  `;try{await S(n,i)}catch(s){throw new Error(`LanceDB local snapshot write failed at '${n}': ${b(s)}`)}}async function bs(e,t){let r=ve(e,t),n=re(e,t);await $r(n),B.delete(r)}function zr(e){let t=0;for(let r=0;r<e.length;r+=1)t+=e[r]*e[r];return Math.sqrt(t)}function Ts(e,t){let r=0;for(let i=0;i<e.length;i+=1)r+=e[i]*t[i];let n=zr(e),o=zr(t);return n===0||o===0?0:r/(n*o)}function Ce(e,t){let r=as(e),n=us(e,t),o=[r,n].filter(c=>c!==null),i=w(e.vector_store?.adapter),s=i?i.toLowerCase():null;return{active:(s?o.find(c=>c.name===s):void 0)??o[0]??null,available:o}}function Le(e){let t=fe(e);if(e.name==="qdrant"){let o=ce(e.url),i=encodeURIComponent(t);return{store:"qdrant",query_target:`${o}/collections/${i}/points/search`,upsert_target:`${o}/collections/${i}/points?wait=true`}}let r=encodeURIComponent(e.path),n=encodeURIComponent(t);return{store:"lancedb",query_target:`lancedb://${r}#${n}`,upsert_target:`lancedb://${r}#${n}`}}function Ss(e,t,r){let n=Le(e),o=Ie(t),i=Fr(r);return e.name==="qdrant"?{target:n,method:"POST",headers:Ae(e),body:{vector:o,limit:i,with_payload:!0}}:{target:n,method:"LOCAL",headers:{},body:{table:fe(e),vector:o,limit:i}}}function xs(e,t){let r=Le(e),n=ls(t);return e.name==="qdrant"?{target:r,method:"POST",headers:Ae(e),body:{points:n}}:{target:r,method:"LOCAL",headers:{},body:{table:fe(e),records:n}}}function Is(e,t){let r=Le(e),n=fs(t);return e.name==="qdrant"?{target:r,method:"POST",headers:Ae(e),body:{points:n}}:{target:r,method:"LOCAL",headers:{},body:{table:fe(e),ids:n}}}async function Bu(e,t,r,n={}){let o=Ss(e,t,r);if(o.method==="LOCAL"){let c=e,d=o.body,u=await wt(c.path,d.table);if(u.size===0)return[];let l=Ie(d.vector),f=Fr(d.limit),m=[],g=0;for(let _ of u.values()){if(_.vector.length!==l.length){g++;continue}m.push({id:_.id,score:Ts(l,_.vector),..._.payload?{payload:_.payload}:{}})}return g>0&&n.warnings&&n.warnings.push(`vector_dimension_mismatch:${g} records skipped (expected ${l.length} dimensions)`),m.sort((_,y)=>_.score!==y.score?y.score-_.score:_.id.localeCompare(y.id)),m.slice(0,f)}let i=q(n.timeout_ms,"Vector request"),s=H(n.fetcher,"Vector request"),a=await le(o.target.query_target,{method:"POST",headers:o.headers,body:o.body},i,s,"query");return ss(a)}async function bt(e,t,r={}){let n=xs(e,t);if(n.method==="LOCAL"){let a=e,c=n.body,d=ve(a.path,c.table),u=await wt(a.path,c.table);for(let m of c.records)u.set(m.id,m);await Vr(a.path,c.table,u);let l=re(a.path,c.table),f=await _t(l);return B.set(d,{records:u,mtimeMs:f.mtimeMs,size:f.size}),{status:"ok"}}let o=q(r.timeout_ms,"Vector request"),i=H(r.fetcher,"Vector request"),s=await le(n.target.upsert_target,{method:"POST",headers:n.headers,body:n.body},o,i,"upsert");return yt(s)}async function Ne(e,t,r={}){let n=Is(e,t);if(n.method==="LOCAL"){let a=e,c=n.body,d=ve(a.path,c.table),u=await wt(a.path,c.table);if(u.size===0)return{status:"ok"};for(let l of c.ids)u.delete(l);if(await Vr(a.path,c.table,u),u.size===0)B.delete(d);else{let l=re(a.path,c.table),f=await _t(l);B.set(d,{records:u,mtimeMs:f.mtimeMs,size:f.size})}return{status:"ok"}}let o=q(r.timeout_ms,"Vector request"),i=H(r.fetcher,"Vector request"),s=await le(ms(n.target.upsert_target),{method:"POST",headers:n.headers,body:n.body},o,i,"delete");return yt(s)}async function Ur(e,t=[],r={},n){if(e.name==="lancedb")return await bs(e.path,fe(e)),{status:"ok"};if(n!==void 0){if(!Number.isInteger(n)||n<=0)throw new Error("Vector reset dimension must be a positive integer when provided");let i=Le(e),s=ps(i.upsert_target),a=q(r.timeout_ms,"Vector request"),c=H(r.fetcher,"Vector request"),d=Ae(e);try{await le(s,{method:"DELETE",headers:d,body:{}},a,c,"delete")}catch(l){if(!b(l).includes("failed with status 404"))throw l}let u=await le(s,{method:"PUT",headers:d,body:{vectors:{size:n,distance:"Cosine"}}},a,c,"upsert");return yt(u)}let o=t.map(i=>i.trim()).filter(i=>i.length>0);return o.length===0?{status:"ok"}:await Ne(e,o,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]="4b3ad5fc-0f86-5f20-a23b-19d447cb0973")}catch{}})();function Re(e,t){let r=w(e),n=w(t);return!r||!n?null:{provider:r,model:n}}function jr(e){if(e==null)return null;if(typeof e!="object"||Array.isArray(e))throw new Error("Vectorization embedding metadata must be an object when set");let t=Re(e.provider,e.model),r=e.vector_dimension;if(!t||typeof r!="number"||!Number.isInteger(r)||r<=0)throw new Error("Vectorization embedding metadata must include provider, model, and positive vector_dimension");return{...t,vector_dimension:r}}function Tt(e,t){if(!Number.isInteger(t)||t<=0)throw new Error("Vectorization embedding metadata requires a positive vector dimension");return{provider:e.provider,model:e.model,vector_dimension:t}}function St(e,t){return!e||e.provider!==t.provider||e.model!==t.model}function xt(e,t){return!!(e&&e.vector_dimension!==t)}function It(e,t){if(e.length===0)throw new Error(`${t} returned no vectors`);let n=e[0].length;if(!Number.isInteger(n)||n<=0)throw new Error(`${t} returned an empty vector`);for(let o=1;o<e.length;o+=1)if(e[o]?.length!==n)throw new Error(`${t} returned mixed vector dimensions`);return n}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]="7939a590-3662-5c66-99aa-3835a0dbaecc")}catch{}})();var As=["index/manifest.json","search/embeddings.jsonl"],Hr="search/vectorization-status.json";function vs(e,t){return`search_cache_invalidation_failed:${e}:${String(t)}`}function ne(e){return[...new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function Yr(e){return typeof e=="string"&&e.trim().length>0&&Number.isFinite(Date.parse(e))}function Br(e){let t=new Map;for(let[r,n]of Object.entries(e)){let o=r.trim();o.length===0||!Yr(n)||t.set(o,n)}return Object.fromEntries([...t.entries()].sort((r,n)=>r[0].localeCompare(n[0])))}async function Wr(e){let t=At.join(e,Hr),r=await v(t);if(r===null||r.trim().length===0)return{entries:{},embedding:null,warnings:[]};let n;try{n=JSON.parse(r)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}if(typeof n!="object"||n===null||n.version!==1||!Array.isArray(n.items))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let o=new Map;for(let s of n.items){if(typeof s!="object"||s===null)return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let a=s.id,c=s.updated_at;if(typeof a!="string"||a.trim().length===0||!Yr(c))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};o.set(a.trim(),c)}let i=null;try{i=jr(n.embedding)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}return{entries:Object.fromEntries([...o.entries()].sort((s,a)=>s[0].localeCompare(a[0]))),embedding:i,warnings:[]}}async function Gr(e,t,r){let n=Br(t),o=At.join(e,Hr),i=`${JSON.stringify({version:1,generated_at:L(),...r?{embedding:r}:{},items:Object.entries(n).map(([s,a])=>({id:s,updated_at:a}))},null,2)}
7
- `;await S(o,i)}function Cs(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Ls(e){let t=Re(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function me(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function Ns(e,t,r){if(!r.settings&&!await z(ge(e)))return me(t,"search_semantic_refresh_skipped:settings_not_initialized");let n;try{if(r.settings)n=r.settings;else{let a=await X(e),c=a.warnings.find(d=>d.startsWith("settings_read_"));if(c)return me(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);n=a.settings}}catch(a){return me(t,`search_semantic_refresh_skipped:settings_read_failed:${b(a)}`)}let o=r.apply_runtime_defaults?ee(n).settings:n,i=Se(o).active;if(!i)return me(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=Ce(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:me(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function Rs(e,t,r,n,o,i){let s=[],a=new Set,c=new Set,d=[];for(let u of n){let l=await tt(e,u,t,r,o);if(!l){c.add(u);continue}try{let f=await rt(l,{schema:i});d.push({id:f.document.metadata.id,document:f.document})}catch(f){a.add(l.id),s.push(`search_semantic_refresh_item_read_failed:${l.id}:${b(f)}`)}}return d.sort((u,l)=>u.id.localeCompare(l.id)),{documents:d,missingIds:ne(c),skippedIds:ne(a),warnings:s}}async function Ds(e,t,r){let n=te(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=ct(e),i=r.map(a=>ut(a.document,{providerName:t.name,maxCharacters:n,fields:o})),s=await ft(t,e,i);return{vectors:s.vectors,vector_dimension:It(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function ks(e,t,r){return await bt(e,t.map((n,o)=>({id:n.id,vector:r[o],payload:Cs(n.document.metadata)}))),{refreshed:t.map(n=>n.id),skipped:[],warnings:[]}}async function Ms(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await Ne(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(r){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${b(r)}`]}}}async function Os(e){let t=[],r=[];for(let n of As){let o=At.join(e,n);try{if(!await z(o))continue;await ae(o),t.push(n)}catch(i){r.push(vs(n,i))}}return{invalidated:t,warnings:r}}async function qr(e,t,r={}){let n=ne(t);if(n.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await Ns(e,n,r);if(!("settings"in o))return o;let i=He(o.settings,Ge()),s=await Rs(e,o.settings.id_prefix,o.settings.item_format,n,i.type_to_folder,o.settings.schema),a=s.documents.length>0||s.missingIds.length>0?await Wr(e):{entries:{},embedding:null,warnings:[]},c=Ls(o.provider),d=a.entries,u={refreshed:[],skipped:[],warnings:[]},l=a.embedding;if(s.documents.length>0)if(a.embedding&&St(a.embedding,c))u={refreshed:[],skipped:s.documents.map(y=>y.id),warnings:["search_semantic_refresh_requires_reindex:embedding_identity_changed"]};else try{let y=await Ds(o.settings,o.provider,s.documents);if(xt(a.embedding,y.vector_dimension))u={refreshed:[],skipped:s.documents.map(E=>E.id),warnings:[...y.warnings,"search_semantic_refresh_requires_reindex:vector_dimension_changed"]};else{l=Tt(c,y.vector_dimension);let E=await ks(o.vectorStore,s.documents,y.vectors);u={refreshed:E.refreshed,skipped:E.skipped,warnings:[...y.warnings,...E.warnings]}}}catch(y){u={refreshed:[],skipped:s.documents.map(E=>E.id),warnings:[`search_semantic_refresh_failed:${b(y)}`]}}let f=await Ms(o.vectorStore,s.missingIds),m=new Set(u.refreshed),g=Object.fromEntries(s.documents.filter(y=>m.has(y.id)).map(y=>[y.id,y.document.metadata.updated_at])),_=[];if(Object.keys(g).length>0||s.missingIds.length>0){let y={...d,...Br(g)};for(let E of s.missingIds)delete y[E];try{await Gr(e,y,l)}catch(E){_.push(`search_vectorization_status_ledger_write_failed:${b(E)}`)}_.push(...a.warnings)}return{refreshed:ne([...u.refreshed,...f.refreshed]),skipped:ne([...s.skippedIds,...u.skipped,...f.skipped]),warnings:[...s.warnings,...u.warnings,...f.warnings,..._]}}function Ps(e,t){let r=t?ee(e).settings:e;return!!(Se(r).active&&Ce(r).active)}async function zs(e,t,r={}){let n=await Os(e),o=ne(t);if(o.length===0)return{invalidated:n.invalidated,refreshed:[],skipped:[],warnings:n.warnings};if(!await z(ge(e))){let c=await qr(e,o);return{invalidated:n.invalidated,refreshed:c.refreshed,skipped:c.skipped,warnings:[...n.warnings,...c.warnings]}}let i;try{let c=await X(e),d=c.warnings.find(u=>u.startsWith("settings_read_"));if(d)return{invalidated:n.invalidated,refreshed:[],skipped:o,warnings:[...n.warnings,`search_semantic_refresh_skipped:settings_read_failed:${d}`]};i=c.settings}catch(c){return{invalidated:n.invalidated,refreshed:[],skipped:o,warnings:[...n.warnings,`search_semantic_refresh_skipped:settings_read_failed:${b(c)}`]}}if(i.search.mutation_refresh_policy==="cache_only")return{invalidated:n.invalidated,refreshed:[],skipped:o,warnings:n.warnings};let s=i.search.mutation_refresh_policy==="semantic_auto";if(r.background&&Ps(i,s))return await Lr(e,o),{invalidated:n.invalidated,refreshed:[],skipped:[],warnings:[...n.warnings,"search_semantic_refresh_scheduled_background"],scheduled:!0};let a=await qr(e,o,{settings:i,apply_runtime_defaults:s});return{invalidated:n.invalidated,refreshed:a.refreshed,skipped:a.skipped,warnings:[...n.warnings,...a.warnings]}}import{createRequire as Fs}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8eb48648-6e55-5710-990e-6471c7cdcde0")}catch{}})();var Kr=new Set(["1","true","yes","on"]);function $s(){return!!(Kr.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||Kr.has((process.env.PM_TELEMETRY_DISABLED??"").trim().toLowerCase())||process.env.VITEST||process.env.VITEST_WORKER_ID)}var en=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,Vs=new RegExp(`\\b(${en.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu"),Us=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,js=/file:\/\/\/?[^\s"'`),;]+/giu,qs=/\b[A-Za-z]:\\[^\s"'`),;]+/g,Hs=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,Ys=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i;var Bs=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function Qr(e){let t=e.trim();return t.length===0?!1:t.startsWith("/")||t.startsWith("file://")||/^[A-Za-z]:\\/.test(t)||t.startsWith("\\\\")?!0:t.includes("/home/")}function M(e,t){if(t&&Ys.test(t)&&Qr(e))return"[scrubbed_path]";let r=e.replaceAll(Vs,(n,o)=>`${o}=[scrubbed]`).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(Hs,"[scrubbed_ip]").replaceAll(js,"[scrubbed_path]").replaceAll(qs,"[scrubbed_path]").replaceAll(Us,(n,o)=>`${o}[scrubbed_path]`);return Qr(r)?"[scrubbed_path]":r}function U(e){let t={};for(let[r,n]of Object.entries(e))en.test(r)?t[r]="[scrubbed]":typeof n=="string"?t[r]=M(n,r):Array.isArray(n)?t[r]=n.map(o=>typeof o=="string"?M(o,r):o&&typeof o=="object"?U(o):o):n&&typeof n=="object"?t[r]=U(n):t[r]=n;return t}function Ws(e){for(let r of["filename","absPath","abs_path","module"]){let n=e[r];typeof n=="string"&&(e[r]=M(n,r))}let t=e.context_line;typeof t=="string"&&(e.context_line=M(t,"context_line"));for(let r of["pre_context","post_context"]){let n=e[r];Array.isArray(n)&&(e[r]=n.map(o=>typeof o=="string"?M(o,r):o))}e.vars&&typeof e.vars=="object"&&(e.vars=U(e.vars)),e.data&&typeof e.data=="object"&&(e.data=U(e.data))}var Gs=Fs(import.meta.url),Ks=()=>Gs("@sentry/node"),vt,Jr=!1,Qs=Ks,Js="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function Ct(e){return/^\s*PmCliError:/.test(e)}function Lt(e){let t=e.trim().toLowerCase();return t.length===0?!1:Bs.some(r=>t.includes(r))}function Xs(e){return e.logger!=="console"?!1:typeof e.message=="string"&&Lt(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(t=>typeof t.value=="string"&&Lt(t.value))}function Zs(e){if(e.logger!=="console")return!1;let t=r=>typeof r=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(r);return t(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(r=>t(r.value))}function ea(e){return!!(e.exception?.values?.some(t=>t.type==="PmCliError")||e.exception?.values?.some(t=>typeof t.value=="string"&&Ct(t.value))||e.logger==="console"&&typeof e.message=="string"&&Ct(e.message))}function tn(e){return e.category==="console"&&typeof e.message=="string"&&Ct(e.message)}function rn(e){return e.category==="console"&&typeof e.message=="string"&&Lt(e.message)}function ta(){return qe(import.meta.url,["../../.."])??"0.0.0"}function ra(){let e=process.env.SENTRY_ENVIRONMENT?.trim();return e&&e.length>0?e:process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test"?"test":process.env.CI?"ci":"production"}var Xr=.2;function na(){let e=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!e)return Xr;let t=Number(e);return!Number.isFinite(t)||t<0||t>1?Xr:t}function oa(e){if(e.exception?.values){for(let t of e.exception.values)if(t.value&&(t.value=M(t.value,"value")),t.stacktrace?.frames)for(let r of t.stacktrace.frames)Ws(r)}}function nn(e){if(e.breadcrumbs)for(let t of e.breadcrumbs)t.message&&(t.message=M(t.message)),t.data&&typeof t.data=="object"&&(t.data=U(t.data))}function on(e){if(e.contexts)for(let[t,r]of Object.entries(e.contexts))r&&typeof r=="object"&&(e.contexts[t]=U(r))}function Zr(e,t){let r=e,n=r[t];n&&typeof n=="object"&&(r[t]=U(n))}var ia=e=>{if(ea(e)||Xs(e))return null;Zs(e)&&(e.level="warning",e.tags={...e.tags,"pm.diagnostic_class":"node_runtime_warning"}),e.message&&(e.message=M(e.message,"message")),e.transaction&&(e.transaction=M(e.transaction,"transaction")),oa(e),nn(e),Zr(e,"extra"),on(e);for(let t of["request","user","tags"])Zr(e,t);return e},sa=e=>(e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(t=>!tn(t)&&!rn(t)),nn(e)),on(e),e),aa=e=>tn(e)||rn(e)?null:(e.message&&(e.message=M(e.message,"message")),e.data&&typeof e.data=="object"&&(e.data=U(e.data)),e);async function ca(){if(Jr)return vt;if(Jr=!0,$s())return;let e=Qs();vt=e;let t=process.env.SENTRY_DSN?.trim()||Js,r=ta();return e.init({dsn:t,release:`pm-cli@${r}`,environment:ra(),tracesSampleRate:na(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,sendDefaultPii:!1,serverName:void 0,integrations:[e.extraErrorDataIntegration({depth:4}),e.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":r,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend:ia,beforeSendTransaction:sa,beforeBreadcrumb:aa}),e}function W(){return vt}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e896db69-ed90-53f1-a227-e3d061b3bc8d")}catch{}})();var da=new Set(["init","config","completion","completion-statuses","completion-tags","completion-types"]),ua=new Set(["list","list-all","list-open","list-in-progress","list-blocked","list-closed","list-canceled","list-draft","search","get","context","calendar","history","activity","aggregate","deps","contracts","stats"]),la=new Set(["create","update","update-many","close-many","append","close","delete","restore","claim","release","comments","notes","learnings","files","docs","start-task","pause-task","close-task"]),fa=new Set(["test","test-all","test-runs","test-verify","trace-test","test-ping"]),ma=new Set(["health","validate","normalize","reindex","gc","telemetry","extension-doctor"]);function pa(e){return e.trim().replaceAll(/\s+/g," ").toLowerCase()}function sn(e){let t=e?.trim().toLowerCase();return t&&t.length>0?t:void 0}var _a=[{code:"unknown_command",matches:e=>e.includes("unknown command")},{code:"unknown_option",matches:e=>e.includes("unknown option")},{code:"missing_required_option",matches:e=>e.includes("missing required options")||e.includes("missing required option")},{code:"missing_required_argument",matches:e=>e.includes("missing required argument")},{code:"no_update_fields",matches:e=>e.includes("no update flags provided")},{code:"ownership_conflict",matches:e=>e.includes("is assigned to")&&e.includes("use --force")},{code:"lock_conflict",matches:e=>e.includes("is locked")},{code:"terminal_state_conflict",matches:e=>e.includes("already terminal")&&e.includes("use --force")},{code:"tracker_not_initialized",matches:e=>e.includes("tracker is not initialized")},{code:"item_not_found",matches:e=>e.includes(" not found")},{code:"close_through_update",matches:e=>e.includes('use "pm close <id> <text>" to close an item')||e.includes("invalid --status value")&&e.includes('"closed"')},{code:"invalid_argument_value",matches:e=>e.startsWith("invalid ")||e.includes(" must be ")||e.includes(" requires ")},{code:"invalid_command_usage",matches:e=>e.includes("either as positional")&&e.includes("not both")}],ha=new Map([[p.USAGE,"invalid_command_usage"],[p.NOT_FOUND,"item_not_found"],[p.CONFLICT,"lock_conflict"],[p.DEPENDENCY_FAILED,"dependency_failed"]]);function oe(e){let t=pa(e),r=t.length>0?t.split(" "):["<unknown>"],n=r[0],o=r[r.length-1],i="other";return da.has(n)?i="setup":ua.has(n)?i="query":la.has(n)?i="mutation":fa.has(n)?i="testing":n==="extension"?i="extension":ma.has(n)&&(i="diagnostics"),{command_path:t.length>0?t:"<unknown>",command_root:n,command_leaf:o,command_depth:r.length,command_family:i}}function Nt(e){if(e.ok)return;let t=sn(e.errorCode);if(t)return t;let r=(e.errorMessage??"").trim().toLowerCase();for(let o of _a)if(o.matches(r))return o.code;let n=Number.isFinite(e.exitCode)?Math.max(0,Math.trunc(e.exitCode)):void 0;return n!==void 0?ha.get(n)??"command_failed":"command_failed"}function ie(e){if(e.ok)return"success";let t=sn(e.errorCode);return t==="unknown_command"?"nonexistent_command":t==="unknown_option"?"invalid_option":t==="missing_required_option"?"missing_required_option":t==="missing_required_argument"?"missing_required_argument":t==="health_findings"?"health_findings":t==="validation_findings"?"validation_findings":e.errorCategory==="usage"?"invalid_usage":e.errorCategory==="validation"?"validation_failed":e.errorCategory==="conflict"?"conflict":e.errorCategory==="runtime"?"runtime_failed":"unknown_failed"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48cce5c1-5cca-53cc-8991-f97669251a72")}catch{}})();var se;function j(e,t,r){if(r===void 0)return;let n=e;typeof n.setAttribute=="function"&&n.setAttribute(t,r)}function De(e,t,r){typeof r=="string"&&r.trim().length>0&&e.setTag(t,r)}function ga(e,t,r){e.setTag("pm.ok",t),e.setTag("pm.command_ok",t),typeof r?.exit_code=="number"&&(e.setTag("pm.exit_code",String(r.exit_code)),e.setTag("pm.command_exit_code",String(r.exit_code))),De(e,"pm.error_code",r?.error_code),De(e,"pm.error_category",r?.error_category),De(e,"pm.command_resolution",r?.command_resolution),De(e,"pm.resolution_stage",r?.resolution_stage)}function ya(e,t,r,n){j(e,"pm.ok",t),j(e,"pm.command_ok",t),j(e,"pm.exit_code",r),j(e,"pm.command_exit_code",r),j(e,"pm.error_code",n?.error_code),j(e,"pm.error_category",n?.error_category),j(e,"pm.command_resolution",n?.command_resolution),j(e,"pm.resolution_stage",n?.resolution_stage)}function Ea(e,t,r,n){let o=W();if(!o)return;let i=oe(e);o.setTag("pm.command",e),o.setTag("pm.command_root",i.command_root),o.setTag("pm.command_family",i.command_family),typeof n?.source_context=="string"&&n.source_context.trim().length>0&&o.setTag("pm.source_context",n.source_context);let s=t.map(a=>a.startsWith("--")?a.split("=")[0]:a);o.setContext("pm.command",{name:e,root:i.command_root,leaf:i.command_leaf,family:i.command_family,args:s,option_keys:Object.keys(r).sort(),source_context:n?.source_context,source_context_source:n?.source_context_source}),o.addBreadcrumb({category:"pm.command",message:`pm ${e}`,level:"info",data:{args:s,command_root:i.command_root,command_family:i.command_family,source_context:n?.source_context}})}function wa(e){let t=W();t&&(se=t.startInactiveSpan({op:"pm.command",name:`pm ${e}`,forceTransaction:!0}))}function ba(e,t,r){if(!se)return;let n=e?"true":"false",o=typeof r?.exit_code=="number"?String(r.exit_code):void 0,i=W();i&&ga(i,n,r),ya(se,n,o,r),se.setStatus(e?{code:1}:{code:2,message:t??"command_failed"}),se.end(),se=void 0}function Ta(e){if(!xa(e))return;let t=W();if(t)if(e instanceof Error){let r={};"exitCode"in e&&typeof e.exitCode=="number"&&(r.exit_code=e.exitCode),"context"in e&&typeof e.context=="object"&&(r.error_context=e.context),t.captureException(e,{extra:r})}else t.captureException(new Error(String(e)))}function Sa(e){let t=W();if(!t)return;let r=e.command_resolution??ie({ok:!1,errorCode:e.error_code,errorCategory:e.error_category}),n=e.resolution_stage??"unknown",o={"pm.command":e.command,"pm.error_code":e.error_code,"pm.error_category":e.error_category,"pm.exit_code":e.exit_code,"pm.error_message":e.error_message,"pm.command_resolution":r,"pm.resolution_stage":n,"pm.source_context":e.source_context??""},i=t.logger;if(i&&typeof i.warn=="function"){i.warn("pm_cli_usage_error",o);return}t.captureMessage(`pm_cli_usage_error:${e.error_code}`,{level:"warning",tags:{"pm.command":e.command,"pm.error_code":e.error_code,"pm.error_category":e.error_category,"pm.exit_code":String(e.exit_code),"pm.command_resolution":r,"pm.resolution_stage":n,"pm.source_context":e.source_context??"unknown"},extra:o})}function xa(e){if(e instanceof h||e instanceof Error&&e.name==="AbortError"&&/(?:ctrl\+c|sigint|user[- ]initiated)/i.test(e.message))return!1;if(typeof e=="object"&&e!==null&&"exitCode"in e&&typeof e.exitCode=="number"){if(e instanceof Error&&e.name==="CommandError")return!1;let t=Math.trunc(e.exitCode);return!new Set([p.SUCCESS,p.USAGE,p.NOT_FOUND,p.CONFLICT]).has(t)}return!0}async function Ia(e=3e3){let t=W();if(t)try{await t.flush(e)}catch{}}import{promises as an}from"node:fs";import cn 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]="611f01b6-0c72-5ea2-a44f-78877c69706c")}catch{}})();var Aa="session.json";function dn(e){return cn.join(or(e),Aa)}async function Rt(e){try{let t=await an.readFile(dn(e),"utf8"),r=JSON.parse(t);if(r===null||typeof r!="object"||Array.isArray(r))return{};let n=r.focused_item;return typeof n=="string"&&n.trim().length>0?{focused_item:n}:{}}catch{return{}}}async function un(e,t){let r=dn(e);await an.mkdir(cn.dirname(r),{recursive:!0}),await S(r,JSON.stringify(t))}async function va(e){return(await Rt(e)).focused_item}async function Ca(e,t){let r=await Rt(e);await un(e,{...r,focused_item:t})}async function La(e){let r={...await Rt(e)};delete r.focused_item,await un(e,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]="7775a1f2-5167-5853-a2c5-a44d46f8e80e")}catch{}})();var Na=/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/,Ra=/\bnpm_[A-Za-z0-9]{36}\b/,Da=/\bxox[baprs]-(?=[A-Za-z0-9-]{20,80}\b)(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]{20,80}\b/,ka=/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/,Ma=/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/,ln=/\b(?:token|secret|password|passwd|api[_-]?key)\s*[:=]\s*["']?([A-Za-z0-9+/=_-]{24,})/gi,Oa=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],kt=new Map(Oa.map(e=>[e.action,e]));function Pa(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let r=0;for(let n of t.values()){let o=n/e.length;r-=o*Math.log2(o)}return r}function Dt(e,t="$",r=new WeakSet){return typeof e=="string"?[{path:t,value:e}]:typeof e!="object"||e===null?[]:r.has(e)?[]:(r.add(e),Array.isArray(e)?e.flatMap((n,o)=>Dt(n,`${t}[${o}]`,r)):Object.entries(e).flatMap(([n,o])=>Dt(o,`${t}.${n}`,r)))}function fn(e){let t=[];for(let r of Dt(e)){Na.test(r.value)&&t.push({rule:"github_token",path:r.path}),Ra.test(r.value)&&t.push({rule:"npm_token",path:r.path}),Da.test(r.value)&&t.push({rule:"slack_token",path:r.path}),ka.test(r.value)&&t.push({rule:"private_key",path:r.path}),Ma.test(r.value)&&t.push({rule:"aws_access_key",path:r.path}),ln.lastIndex=0;for(let n of r.value.matchAll(ln)){let o=n[1];if(Pa(o)>=3.5){t.push({rule:"high_entropy_assignment",path:r.path});break}}}return t.filter((r,n,o)=>o.findIndex(i=>i.rule===r.rule&&i.path===r.path)===n)}function za(e){let t=e.author.trim()||"unknown";if(e.settings.require_attributed_author&&t.toLowerCase()==="unknown")throw new h("Mutation author is required by workspace policy.",p.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(e.settings.secret_guard==="off")return{author:t,findings:[],warnings:[],override_applied:!1};let r;try{r=fn(e.payload)}catch{return{author:t,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(r.length===0)return{author:t,findings:r,warnings:[],override_applied:!1};let n=[...new Set(r.map(o=>o.rule))].sort().join(",");if(e.settings.secret_guard==="block"&&e.force!==!0)throw new h(`Mutation blocked by secret guard (${n}). No detected value was logged.`,p.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author:t,findings:r,warnings:[`secret_guard_detected:${r.length}:rules=${n}`,...e.settings.secret_guard==="block"&&e.force===!0?["secret_guard_force_override"]:[]],override_applied:e.settings.secret_guard==="block"&&e.force===!0}}function Fa(e){return kt.has(e.trim().toLowerCase())}function $a(){return[...kt.keys()].sort((e,t)=>e.localeCompare(t))}function Nl(e){return kt.get(e.trim().toLowerCase())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64312ac7-5a99-5a21-b99f-2bdef1b54a06")}catch{}})();var Va=/\b[a-z][a-z0-9]*-\d+(?:-[a-z0-9]+)*\b/giu;function Mt(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function pn(e){return[...new Set(Mt(e).match(/[\p{L}\p{N}]+/gu)??[])]}function mn(e){let t=Mt(e);return{normalized:t,tokens:pn(t),issueCodes:[...new Set(t.match(Va)?.map(r=>r.toLowerCase())??[])]}}function _n(e,t){let r=new Set(e),n=new Set(t),o=new Set([...r,...n]);if(o.size===0)return 1;let i=0;for(let s of r)n.has(s)&&(i+=1);return i/o.size}function Ua(e,t){return ja(mn(e),mn(t))}function ja(e,t){if(e.normalized===t.normalized)return{score:1,reason:"exact_title"};let r=new Set(e.issueCodes);return t.issueCodes.some(n=>r.has(n))?{score:.99,reason:"issue_code"}:{score:_n(e.tokens,t.tokens),reason:"title_token_jaccard"}}import qa 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]="376bb9d2-e202-57e7-86c8-d70a7d3fa7ab")}catch{}})();function ke(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Ha(e,t){return[e.updated_at,t].map(n=>({value:n,time:Date.parse(n??"")})).filter(n=>typeof n.value=="string"&&Number.isFinite(n.time)).sort((n,o)=>o.time-n.time)[0]?.value??e.updated_at}function hn(e,t){let r=Math.max(1,Math.trunc(t.threshold_hours)),n=(t.now??new Date).getTime(),o=ke(t.in_progress_status),i=[];for(let s of e){if(ke(String(s.status))!==o||(s.assignee?.trim().length??0)>0)continue;let a=Ha(s,t.last_history_activity?.(s)),c=Date.parse(a);if(!Number.isFinite(c))continue;let d=Math.max(0,Math.floor((n-c)/36e5));d>=r&&i.push({id:s.id,last_activity_at:a,age_hours:d})}return i.sort((s,a)=>a.age_hours-s.age_hours||s.id.localeCompare(a.id)),{threshold_hours:r,count:i.length,items:i,remediation:"Claim active work with `pm claim <id>` or return abandoned work to open with `pm update <id> --status open`."}}async function Ya(e,t,r){let n=new Map;return await Promise.all(t.filter(o=>ke(String(o.status))===ke(r.in_progress_status)&&(o.assignee?.trim().length??0)===0).map(async o=>{let i;try{i=await cr(qa.join(e,"history",`${o.id}.jsonl`),o.id)}catch{return}let s=i.map(a=>a.ts).filter(a=>Number.isFinite(Date.parse(a))).sort((a,c)=>Date.parse(c)-Date.parse(a))[0];s&&n.set(o.id,s)})),hn(t,{...r,last_history_activity:o=>n.get(o.id)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c43dd9f2-78ac-5c22-970a-0016a06b87b3")}catch{}})();var Ba=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"}),Wa=/&(?:lt|gt|quot|#39|amp);/g;function Ga(e){return typeof e!="string"||!e.includes("&lt;")&&!e.includes("&gt;")?e:e.replace(Wa,t=>Ba[t])}function Ka(e){return Ot(e,new WeakMap)}function Ot(e,t){if(typeof e=="string")return Ga(e);if(Array.isArray(e)){if(t.has(e))return t.get(e);let r=[];t.set(e,r);for(let n of e)r.push(Ot(n,t));return r}if(e!==null&&typeof e=="object"){if(!Qa(e))return e;if(t.has(e))return t.get(e);let r=e,n=Object.create(Object.getPrototypeOf(e));t.set(e,n);for(let[o,i]of Object.entries(r))Object.defineProperty(n,o,{value:Ot(i,t),enumerable:!0,writable:!0,configurable:!0});return n}return e}function Qa(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===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]="0ce743d1-917a-5c96-b038-c95e3922bc48")}catch{}})();function Ja(e){let t=null;return()=>(t??=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]="868dfae8-2575-5d5f-8425-c7e68aefdc84")}catch{}})();function gn(e){return e.split(/[\s,|]+/).map(t=>t.trim()).filter(t=>t.startsWith("--"))}function Xa(e){return gn(e)[0]??null}function Za(e,t){let r=Xa(t);if(r===null)return!1;let n=o=>o.slice(2).replaceAll("-","_");return gn(e).some(o=>!o.slice(2).includes("-")||r===o?!1:n(r)===n(o))}import yn from"node:fs/promises";import Me from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4baf0ef3-2412-51cf-9ade-18b5c6e610d1")}catch{}})();function ec(e){return"json_markdown"}function En(e,t){return Me.relative(e,t).replaceAll("\\","/")}function tc(e){return String(e).replaceAll(/[^a-zA-Z0-9._-]+/g,"_").slice(0,120)}async function rc(e,t,r="item_format:migrate",n=je,o){if(t!=="toon")throw new Error("Only toon item-format migration targets are supported. Markdown item files are legacy read-only input.");let i=new Set,s=new Set,a=[],c=0,d=ec(t),u=Object.entries(n);for(let[l,f]of u){let m=Me.join(e,f),g=[];try{g=await yn.readdir(m)}catch{continue}let _=new Map;for(let E of g){let I=Me.join(m,E),A=nr(I);if(!A)continue;let F=Me.extname(E),$=E.slice(0,E.length-F.length).trim();if($.length===0)continue;let K=_.get($)??{};K[A]=I,_.set($,K)}let y=[..._.keys()].sort((E,I)=>E.localeCompare(I));for(let E of y){let I=_.get(E);c+=1;let A=I[d];if(!A)continue;let F=I[t]??A,$=F===I[t]?t:d;try{let K=await yn.readFile(F,"utf8"),mo=Qe(K,{format:$,schema:o,onWarning:po=>a.push(`item_format_migration_parse_warning:${E}:${po}`)}),Ve=Ye(e,l,E,t,n),tr=Je(mo,{format:t,schema:o});await v(Ve)!==tr&&(await S(Ve,tr),a.push(...await ye({path:Ve,scope:"project",op:r})),i.add(E)),await ae(A),s.add(En(e,A)),a.push(...await ye({path:A,scope:"project",op:`${r}:remove`})),i.add(E)}catch(K){a.push(`item_format_migration_skipped:${En(e,F)}:${tc(K)}`)}}}return{target_format:t,scanned:c,migrated:[...i].sort((l,f)=>l.localeCompare(f)),removed:[...s].sort((l,f)=>l.localeCompare(f)),warnings: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]="f280c1df-b134-57c3-91f6-cbf5a37e6e31")}catch{}})();var nc=new Set(["completed","superseded"]);function oc(e){return e!==void 0&&nc.has(e)}function ic(e){if(e.type.trim().toLowerCase()!=="plan")return!1;let t=e.plan_steps??[];return t.length>0&&t.every(r=>r.status==="completed")}import sc from"node:readline/promises";import{stdin as ac,stdout as wn}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6783b122-a1a8-5f86-9ac5-2c3e811622ed")}catch{}})();var cc="PM_TELEMETRY_PROMPT",bn=new Set(["0","false","no","off"]),dc=new Set(["init","completion","completion-statuses","completion-tags","completion-types"]);function uc(e){return typeof e!="string"?!1:bn.has(e.trim().toLowerCase())}function lc(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t.length===0?!1:!bn.has(t)}function fc(e,t){if(t.json===!0||t.quiet===!0||process.stdin.isTTY!==!0||process.stdout.isTTY!==!0||uc(process.env[cc])||lc(process.env.CI))return!0;let r=e.trim().toLowerCase();return r.length===0?!0:dc.has(r)}function mc(e){let t=e.trim().toLowerCase();return!(t==="n"||t==="no")}async function pc(e){let r=`pm telemetry helps improve reliability and usage diagnostics.
7
+ `;await S(o,i)}function Cs(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Ls(e){let t=Re(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function me(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function Ns(e,t,r){if(!r.settings&&!await z(ge(e)))return me(t,"search_semantic_refresh_skipped:settings_not_initialized");let n;try{if(r.settings)n=r.settings;else{let a=await X(e),c=a.warnings.find(d=>d.startsWith("settings_read_"));if(c)return me(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);n=a.settings}}catch(a){return me(t,`search_semantic_refresh_skipped:settings_read_failed:${b(a)}`)}let o=r.apply_runtime_defaults?ee(n).settings:n,i=Se(o).active;if(!i)return me(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=Ce(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:me(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function Rs(e,t,r,n,o,i){let s=[],a=new Set,c=new Set,d=[];for(let u of n){let l=await tt(e,u,t,r,o);if(!l){c.add(u);continue}try{let f=await rt(l,{schema:i});d.push({id:f.document.metadata.id,document:f.document})}catch(f){a.add(l.id),s.push(`search_semantic_refresh_item_read_failed:${l.id}:${b(f)}`)}}return d.sort((u,l)=>u.id.localeCompare(l.id)),{documents:d,missingIds:ne(c),skippedIds:ne(a),warnings:s}}async function ks(e,t,r){let n=te(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=ct(e),i=r.map(a=>ut(a.document,{providerName:t.name,maxCharacters:n,fields:o})),s=await ft(t,e,i);return{vectors:s.vectors,vector_dimension:It(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function Ds(e,t,r){return await bt(e,t.map((n,o)=>({id:n.id,vector:r[o],payload:Cs(n.document.metadata)}))),{refreshed:t.map(n=>n.id),skipped:[],warnings:[]}}async function Ms(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await Ne(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(r){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${b(r)}`]}}}async function Os(e){let t=[],r=[];for(let n of As){let o=At.join(e,n);try{if(!await z(o))continue;await ae(o),t.push(n)}catch(i){r.push(vs(n,i))}}return{invalidated:t,warnings:r}}async function qr(e,t,r={}){let n=ne(t);if(n.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await Ns(e,n,r);if(!("settings"in o))return o;let i=He(o.settings,Ge()),s=await Rs(e,o.settings.id_prefix,o.settings.item_format,n,i.type_to_folder,o.settings.schema),a=s.documents.length>0||s.missingIds.length>0?await Wr(e):{entries:{},embedding:null,warnings:[]},c=Ls(o.provider),d=a.entries,u={refreshed:[],skipped:[],warnings:[]},l=a.embedding;if(s.documents.length>0)if(a.embedding&&St(a.embedding,c))u={refreshed:[],skipped:s.documents.map(y=>y.id),warnings:["search_semantic_refresh_requires_reindex:embedding_identity_changed"]};else try{let y=await ks(o.settings,o.provider,s.documents);if(xt(a.embedding,y.vector_dimension))u={refreshed:[],skipped:s.documents.map(E=>E.id),warnings:[...y.warnings,"search_semantic_refresh_requires_reindex:vector_dimension_changed"]};else{l=Tt(c,y.vector_dimension);let E=await Ds(o.vectorStore,s.documents,y.vectors);u={refreshed:E.refreshed,skipped:E.skipped,warnings:[...y.warnings,...E.warnings]}}}catch(y){u={refreshed:[],skipped:s.documents.map(E=>E.id),warnings:[`search_semantic_refresh_failed:${b(y)}`]}}let f=await Ms(o.vectorStore,s.missingIds),m=new Set(u.refreshed),g=Object.fromEntries(s.documents.filter(y=>m.has(y.id)).map(y=>[y.id,y.document.metadata.updated_at])),_=[];if(Object.keys(g).length>0||s.missingIds.length>0){let y={...d,...Br(g)};for(let E of s.missingIds)delete y[E];try{await Gr(e,y,l)}catch(E){_.push(`search_vectorization_status_ledger_write_failed:${b(E)}`)}_.push(...a.warnings)}return{refreshed:ne([...u.refreshed,...f.refreshed]),skipped:ne([...s.skippedIds,...u.skipped,...f.skipped]),warnings:[...s.warnings,...u.warnings,...f.warnings,..._]}}function Ps(e,t){let r=t?ee(e).settings:e;return!!(Se(r).active&&Ce(r).active)}async function zs(e,t,r={}){let n=await Os(e),o=ne(t);if(o.length===0)return{invalidated:n.invalidated,refreshed:[],skipped:[],warnings:n.warnings};if(!await z(ge(e))){let c=await qr(e,o);return{invalidated:n.invalidated,refreshed:c.refreshed,skipped:c.skipped,warnings:[...n.warnings,...c.warnings]}}let i;try{let c=await X(e),d=c.warnings.find(u=>u.startsWith("settings_read_"));if(d)return{invalidated:n.invalidated,refreshed:[],skipped:o,warnings:[...n.warnings,`search_semantic_refresh_skipped:settings_read_failed:${d}`]};i=c.settings}catch(c){return{invalidated:n.invalidated,refreshed:[],skipped:o,warnings:[...n.warnings,`search_semantic_refresh_skipped:settings_read_failed:${b(c)}`]}}if(i.search.mutation_refresh_policy==="cache_only")return{invalidated:n.invalidated,refreshed:[],skipped:o,warnings:n.warnings};let s=i.search.mutation_refresh_policy==="semantic_auto";if(r.background&&Ps(i,s))return await Lr(e,o),{invalidated:n.invalidated,refreshed:[],skipped:[],warnings:[...n.warnings,"search_semantic_refresh_scheduled_background"],scheduled:!0};let a=await qr(e,o,{settings:i,apply_runtime_defaults:s});return{invalidated:n.invalidated,refreshed:a.refreshed,skipped:a.skipped,warnings:[...n.warnings,...a.warnings]}}import{createRequire as Fs}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8eb48648-6e55-5710-990e-6471c7cdcde0")}catch{}})();var Kr=new Set(["1","true","yes","on"]);function $s(){return!!(Kr.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||Kr.has((process.env.PM_TELEMETRY_DISABLED??"").trim().toLowerCase())||process.env.VITEST||process.env.VITEST_WORKER_ID)}var en=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,Vs=new RegExp(`\\b(${en.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu"),Us=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,js=/file:\/\/\/?[^\s"'`),;]+/giu,qs=/\b[A-Za-z]:\\[^\s"'`),;]+/g,Hs=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,Ys=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i;var Bs=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function Qr(e){let t=e.trim();return t.length===0?!1:t.startsWith("/")||t.startsWith("file://")||/^[A-Za-z]:\\/.test(t)||t.startsWith("\\\\")?!0:t.includes("/home/")}function M(e,t){if(t&&Ys.test(t)&&Qr(e))return"[scrubbed_path]";let r=e.replaceAll(Vs,(n,o)=>`${o}=[scrubbed]`).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(Hs,"[scrubbed_ip]").replaceAll(js,"[scrubbed_path]").replaceAll(qs,"[scrubbed_path]").replaceAll(Us,(n,o)=>`${o}[scrubbed_path]`);return Qr(r)?"[scrubbed_path]":r}function U(e){let t={};for(let[r,n]of Object.entries(e))en.test(r)?t[r]="[scrubbed]":typeof n=="string"?t[r]=M(n,r):Array.isArray(n)?t[r]=n.map(o=>typeof o=="string"?M(o,r):o&&typeof o=="object"?U(o):o):n&&typeof n=="object"?t[r]=U(n):t[r]=n;return t}function Ws(e){for(let r of["filename","absPath","abs_path","module"]){let n=e[r];typeof n=="string"&&(e[r]=M(n,r))}let t=e.context_line;typeof t=="string"&&(e.context_line=M(t,"context_line"));for(let r of["pre_context","post_context"]){let n=e[r];Array.isArray(n)&&(e[r]=n.map(o=>typeof o=="string"?M(o,r):o))}e.vars&&typeof e.vars=="object"&&(e.vars=U(e.vars)),e.data&&typeof e.data=="object"&&(e.data=U(e.data))}var Gs=Fs(import.meta.url),Ks=()=>Gs("@sentry/node"),vt,Jr=!1,Qs=Ks,Js="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function Ct(e){return/^\s*PmCliError:/.test(e)}function Lt(e){let t=e.trim().toLowerCase();return t.length===0?!1:Bs.some(r=>t.includes(r))}function Xs(e){return e.logger!=="console"?!1:typeof e.message=="string"&&Lt(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(t=>typeof t.value=="string"&&Lt(t.value))}function Zs(e){if(e.logger!=="console")return!1;let t=r=>typeof r=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(r);return t(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(r=>t(r.value))}function ea(e){return!!(e.exception?.values?.some(t=>t.type==="PmCliError")||e.exception?.values?.some(t=>typeof t.value=="string"&&Ct(t.value))||e.logger==="console"&&typeof e.message=="string"&&Ct(e.message))}function tn(e){return e.category==="console"&&typeof e.message=="string"&&Ct(e.message)}function rn(e){return e.category==="console"&&typeof e.message=="string"&&Lt(e.message)}function ta(){return qe(import.meta.url,["../../.."])??"0.0.0"}function ra(){let e=process.env.SENTRY_ENVIRONMENT?.trim();return e&&e.length>0?e:process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test"?"test":process.env.CI?"ci":"production"}var Xr=.2;function na(){let e=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!e)return Xr;let t=Number(e);return!Number.isFinite(t)||t<0||t>1?Xr:t}function oa(e){if(e.exception?.values){for(let t of e.exception.values)if(t.value&&(t.value=M(t.value,"value")),t.stacktrace?.frames)for(let r of t.stacktrace.frames)Ws(r)}}function nn(e){if(e.breadcrumbs)for(let t of e.breadcrumbs)t.message&&(t.message=M(t.message)),t.data&&typeof t.data=="object"&&(t.data=U(t.data))}function on(e){if(e.contexts)for(let[t,r]of Object.entries(e.contexts))r&&typeof r=="object"&&(e.contexts[t]=U(r))}function Zr(e,t){let r=e,n=r[t];n&&typeof n=="object"&&(r[t]=U(n))}var ia=e=>{if(ea(e)||Xs(e))return null;Zs(e)&&(e.level="warning",e.tags={...e.tags,"pm.diagnostic_class":"node_runtime_warning"}),e.message&&(e.message=M(e.message,"message")),e.transaction&&(e.transaction=M(e.transaction,"transaction")),oa(e),nn(e),Zr(e,"extra"),on(e);for(let t of["request","user","tags"])Zr(e,t);return e},sa=e=>(e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(t=>!tn(t)&&!rn(t)),nn(e)),on(e),e),aa=e=>tn(e)||rn(e)?null:(e.message&&(e.message=M(e.message,"message")),e.data&&typeof e.data=="object"&&(e.data=U(e.data)),e);async function ca(){if(Jr)return vt;if(Jr=!0,$s())return;let e=Qs();vt=e;let t=process.env.SENTRY_DSN?.trim()||Js,r=ta();return e.init({dsn:t,release:`pm-cli@${r}`,environment:ra(),tracesSampleRate:na(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,sendDefaultPii:!1,serverName:void 0,integrations:[e.extraErrorDataIntegration({depth:4}),e.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":r,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend:ia,beforeSendTransaction:sa,beforeBreadcrumb:aa}),e}function W(){return vt}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e896db69-ed90-53f1-a227-e3d061b3bc8d")}catch{}})();var da=new Set(["init","config","completion","completion-statuses","completion-tags","completion-types"]),ua=new Set(["list","list-all","list-open","list-in-progress","list-blocked","list-closed","list-canceled","list-draft","search","get","context","calendar","history","activity","aggregate","deps","contracts","stats"]),la=new Set(["create","update","update-many","close-many","append","close","delete","restore","claim","release","comments","notes","learnings","files","docs","start-task","pause-task","close-task"]),fa=new Set(["test","test-all","test-runs","test-verify","trace-test","test-ping"]),ma=new Set(["health","validate","normalize","reindex","gc","telemetry","extension-doctor"]);function pa(e){return e.trim().replaceAll(/\s+/g," ").toLowerCase()}function sn(e){let t=e?.trim().toLowerCase();return t&&t.length>0?t:void 0}var _a=[{code:"unknown_command",matches:e=>e.includes("unknown command")},{code:"unknown_option",matches:e=>e.includes("unknown option")},{code:"missing_required_option",matches:e=>e.includes("missing required options")||e.includes("missing required option")},{code:"missing_required_argument",matches:e=>e.includes("missing required argument")},{code:"no_update_fields",matches:e=>e.includes("no update flags provided")},{code:"ownership_conflict",matches:e=>e.includes("is assigned to")&&e.includes("use --force")},{code:"lock_conflict",matches:e=>e.includes("is locked")},{code:"terminal_state_conflict",matches:e=>e.includes("already terminal")&&e.includes("use --force")},{code:"tracker_not_initialized",matches:e=>e.includes("tracker is not initialized")},{code:"item_not_found",matches:e=>e.includes(" not found")},{code:"close_through_update",matches:e=>e.includes('use "pm close <id> <text>" to close an item')||e.includes("invalid --status value")&&e.includes('"closed"')},{code:"invalid_argument_value",matches:e=>e.startsWith("invalid ")||e.includes(" must be ")||e.includes(" requires ")},{code:"invalid_command_usage",matches:e=>e.includes("either as positional")&&e.includes("not both")}],ha=new Map([[p.USAGE,"invalid_command_usage"],[p.NOT_FOUND,"item_not_found"],[p.CONFLICT,"lock_conflict"],[p.DEPENDENCY_FAILED,"dependency_failed"]]);function oe(e){let t=pa(e),r=t.length>0?t.split(" "):["<unknown>"],n=r[0],o=r[r.length-1],i="other";return da.has(n)?i="setup":ua.has(n)?i="query":la.has(n)?i="mutation":fa.has(n)?i="testing":n==="extension"?i="extension":ma.has(n)&&(i="diagnostics"),{command_path:t.length>0?t:"<unknown>",command_root:n,command_leaf:o,command_depth:r.length,command_family:i}}function Nt(e){if(e.ok)return;let t=sn(e.errorCode);if(t)return t;let r=(e.errorMessage??"").trim().toLowerCase();for(let o of _a)if(o.matches(r))return o.code;let n=Number.isFinite(e.exitCode)?Math.max(0,Math.trunc(e.exitCode)):void 0;return n!==void 0?ha.get(n)??"command_failed":"command_failed"}function ie(e){if(e.ok)return"success";let t=sn(e.errorCode);return t==="unknown_command"?"nonexistent_command":t==="unknown_option"?"invalid_option":t==="missing_required_option"?"missing_required_option":t==="missing_required_argument"?"missing_required_argument":t==="health_findings"?"health_findings":t==="validation_findings"?"validation_findings":e.errorCategory==="usage"?"invalid_usage":e.errorCategory==="validation"?"validation_failed":e.errorCategory==="conflict"?"conflict":e.errorCategory==="runtime"?"runtime_failed":"unknown_failed"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48cce5c1-5cca-53cc-8991-f97669251a72")}catch{}})();var se;function j(e,t,r){if(r===void 0)return;let n=e;typeof n.setAttribute=="function"&&n.setAttribute(t,r)}function ke(e,t,r){typeof r=="string"&&r.trim().length>0&&e.setTag(t,r)}function ga(e,t,r){e.setTag("pm.ok",t),e.setTag("pm.command_ok",t),typeof r?.exit_code=="number"&&(e.setTag("pm.exit_code",String(r.exit_code)),e.setTag("pm.command_exit_code",String(r.exit_code))),ke(e,"pm.error_code",r?.error_code),ke(e,"pm.error_category",r?.error_category),ke(e,"pm.command_resolution",r?.command_resolution),ke(e,"pm.resolution_stage",r?.resolution_stage)}function ya(e,t,r,n){j(e,"pm.ok",t),j(e,"pm.command_ok",t),j(e,"pm.exit_code",r),j(e,"pm.command_exit_code",r),j(e,"pm.error_code",n?.error_code),j(e,"pm.error_category",n?.error_category),j(e,"pm.command_resolution",n?.command_resolution),j(e,"pm.resolution_stage",n?.resolution_stage)}function Ea(e,t,r,n){let o=W();if(!o)return;let i=oe(e);o.setTag("pm.command",e),o.setTag("pm.command_root",i.command_root),o.setTag("pm.command_family",i.command_family),typeof n?.source_context=="string"&&n.source_context.trim().length>0&&o.setTag("pm.source_context",n.source_context);let s=t.map(a=>a.startsWith("--")?a.split("=")[0]:a);o.setContext("pm.command",{name:e,root:i.command_root,leaf:i.command_leaf,family:i.command_family,args:s,option_keys:Object.keys(r).sort(),source_context:n?.source_context,source_context_source:n?.source_context_source}),o.addBreadcrumb({category:"pm.command",message:`pm ${e}`,level:"info",data:{args:s,command_root:i.command_root,command_family:i.command_family,source_context:n?.source_context}})}function wa(e){let t=W();t&&(se=t.startInactiveSpan({op:"pm.command",name:`pm ${e}`,forceTransaction:!0}))}function ba(e,t,r){if(!se)return;let n=e?"true":"false",o=typeof r?.exit_code=="number"?String(r.exit_code):void 0,i=W();i&&ga(i,n,r),ya(se,n,o,r),se.setStatus(e?{code:1}:{code:2,message:t??"command_failed"}),se.end(),se=void 0}function Ta(e){if(!xa(e))return;let t=W();if(t)if(e instanceof Error){let r={};"exitCode"in e&&typeof e.exitCode=="number"&&(r.exit_code=e.exitCode),"context"in e&&typeof e.context=="object"&&(r.error_context=e.context),t.captureException(e,{extra:r})}else t.captureException(new Error(String(e)))}function Sa(e){let t=W();if(!t)return;let r=e.command_resolution??ie({ok:!1,errorCode:e.error_code,errorCategory:e.error_category}),n=e.resolution_stage??"unknown",o={"pm.command":e.command,"pm.error_code":e.error_code,"pm.error_category":e.error_category,"pm.exit_code":e.exit_code,"pm.error_message":e.error_message,"pm.command_resolution":r,"pm.resolution_stage":n,"pm.source_context":e.source_context??""},i=t.logger;if(i&&typeof i.warn=="function"){i.warn("pm_cli_usage_error",o);return}t.captureMessage(`pm_cli_usage_error:${e.error_code}`,{level:"warning",tags:{"pm.command":e.command,"pm.error_code":e.error_code,"pm.error_category":e.error_category,"pm.exit_code":String(e.exit_code),"pm.command_resolution":r,"pm.resolution_stage":n,"pm.source_context":e.source_context??"unknown"},extra:o})}function xa(e){if(e instanceof h||e instanceof Error&&e.name==="AbortError"&&/(?:ctrl\+c|sigint|user[- ]initiated)/i.test(e.message))return!1;if(typeof e=="object"&&e!==null&&"exitCode"in e&&typeof e.exitCode=="number"){if(e instanceof Error&&e.name==="CommandError")return!1;let t=Math.trunc(e.exitCode);return!new Set([p.SUCCESS,p.USAGE,p.NOT_FOUND,p.CONFLICT]).has(t)}return!0}async function Ia(e=3e3){let t=W();if(t)try{await t.flush(e)}catch{}}import{promises as an}from"node:fs";import cn 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]="611f01b6-0c72-5ea2-a44f-78877c69706c")}catch{}})();var Aa="session.json";function dn(e){return cn.join(or(e),Aa)}async function Rt(e){try{let t=await an.readFile(dn(e),"utf8"),r=JSON.parse(t);if(r===null||typeof r!="object"||Array.isArray(r))return{};let n=r.focused_item;return typeof n=="string"&&n.trim().length>0?{focused_item:n}:{}}catch{return{}}}async function un(e,t){let r=dn(e);await an.mkdir(cn.dirname(r),{recursive:!0}),await S(r,JSON.stringify(t))}async function va(e){return(await Rt(e)).focused_item}async function Ca(e,t){let r=await Rt(e);await un(e,{...r,focused_item:t})}async function La(e){let r={...await Rt(e)};delete r.focused_item,await un(e,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]="7775a1f2-5167-5853-a2c5-a44d46f8e80e")}catch{}})();var Na=/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/,Ra=/\bnpm_[A-Za-z0-9]{36}\b/,ka=/\bxox[baprs]-(?=[A-Za-z0-9-]{20,80}\b)(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]{20,80}\b/,Da=/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/,Ma=/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/,ln=/\b(?:token|secret|password|passwd|api[_-]?key)\s*[:=]\s*["']?([A-Za-z0-9+/=_-]{24,})/gi,Oa=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],Dt=new Map(Oa.map(e=>[e.action,e]));function Pa(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let r=0;for(let n of t.values()){let o=n/e.length;r-=o*Math.log2(o)}return r}function kt(e,t="$",r=new WeakSet){return typeof e=="string"?[{path:t,value:e}]:typeof e!="object"||e===null?[]:r.has(e)?[]:(r.add(e),Array.isArray(e)?e.flatMap((n,o)=>kt(n,`${t}[${o}]`,r)):Object.entries(e).flatMap(([n,o])=>kt(o,`${t}.${n}`,r)))}function fn(e){let t=[];for(let r of kt(e)){Na.test(r.value)&&t.push({rule:"github_token",path:r.path}),Ra.test(r.value)&&t.push({rule:"npm_token",path:r.path}),ka.test(r.value)&&t.push({rule:"slack_token",path:r.path}),Da.test(r.value)&&t.push({rule:"private_key",path:r.path}),Ma.test(r.value)&&t.push({rule:"aws_access_key",path:r.path}),ln.lastIndex=0;for(let n of r.value.matchAll(ln)){let o=n[1];if(Pa(o)>=3.5){t.push({rule:"high_entropy_assignment",path:r.path});break}}}return t.filter((r,n,o)=>o.findIndex(i=>i.rule===r.rule&&i.path===r.path)===n)}function za(e){let t=e.author.trim()||"unknown";if(e.settings.require_attributed_author&&t.toLowerCase()==="unknown")throw new h("Mutation author is required by workspace policy.",p.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(e.settings.secret_guard==="off")return{author:t,findings:[],warnings:[],override_applied:!1};let r;try{r=fn(e.payload)}catch{return{author:t,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(r.length===0)return{author:t,findings:r,warnings:[],override_applied:!1};let n=[...new Set(r.map(o=>o.rule))].sort().join(",");if(e.settings.secret_guard==="block"&&e.force!==!0)throw new h(`Mutation blocked by secret guard (${n}). No detected value was logged.`,p.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author:t,findings:r,warnings:[`secret_guard_detected:${r.length}:rules=${n}`,...e.settings.secret_guard==="block"&&e.force===!0?["secret_guard_force_override"]:[]],override_applied:e.settings.secret_guard==="block"&&e.force===!0}}function Fa(e){return Dt.has(e.trim().toLowerCase())}function $a(){return[...Dt.keys()].sort((e,t)=>e.localeCompare(t))}function Nl(e){return Dt.get(e.trim().toLowerCase())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64312ac7-5a99-5a21-b99f-2bdef1b54a06")}catch{}})();var Va=/\b[a-z][a-z0-9]*-\d+(?:-[a-z0-9]+)*\b/giu;function Mt(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function pn(e){return[...new Set(Mt(e).match(/[\p{L}\p{N}]+/gu)??[])]}function mn(e){let t=Mt(e);return{normalized:t,tokens:pn(t),issueCodes:[...new Set(t.match(Va)?.map(r=>r.toLowerCase())??[])]}}function _n(e,t){let r=new Set(e),n=new Set(t),o=new Set([...r,...n]);if(o.size===0)return 1;let i=0;for(let s of r)n.has(s)&&(i+=1);return i/o.size}function Ua(e,t){return ja(mn(e),mn(t))}function ja(e,t){if(e.normalized===t.normalized)return{score:1,reason:"exact_title"};let r=new Set(e.issueCodes);return t.issueCodes.some(n=>r.has(n))?{score:.99,reason:"issue_code"}:{score:_n(e.tokens,t.tokens),reason:"title_token_jaccard"}}import qa 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]="376bb9d2-e202-57e7-86c8-d70a7d3fa7ab")}catch{}})();function De(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Ha(e,t){return[e.updated_at,t].map(n=>({value:n,time:Date.parse(n??"")})).filter(n=>typeof n.value=="string"&&Number.isFinite(n.time)).sort((n,o)=>o.time-n.time)[0]?.value??e.updated_at}function hn(e,t){let r=Math.max(1,Math.trunc(t.threshold_hours)),n=(t.now??new Date).getTime(),o=De(t.in_progress_status),i=[];for(let s of e){if(De(String(s.status))!==o||(s.assignee?.trim().length??0)>0)continue;let a=Ha(s,t.last_history_activity?.(s)),c=Date.parse(a);if(!Number.isFinite(c))continue;let d=Math.max(0,Math.floor((n-c)/36e5));d>=r&&i.push({id:s.id,last_activity_at:a,age_hours:d})}return i.sort((s,a)=>a.age_hours-s.age_hours||s.id.localeCompare(a.id)),{threshold_hours:r,count:i.length,items:i,remediation:"Claim active work with `pm claim <id>` or return abandoned work to open with `pm update <id> --status open`."}}async function Ya(e,t,r){let n=new Map;return await Promise.all(t.filter(o=>De(String(o.status))===De(r.in_progress_status)&&(o.assignee?.trim().length??0)===0).map(async o=>{let i;try{i=await cr(qa.join(e,"history",`${o.id}.jsonl`),o.id)}catch{return}let s=i.map(a=>a.ts).filter(a=>Number.isFinite(Date.parse(a))).sort((a,c)=>Date.parse(c)-Date.parse(a))[0];s&&n.set(o.id,s)})),hn(t,{...r,last_history_activity:o=>n.get(o.id)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c43dd9f2-78ac-5c22-970a-0016a06b87b3")}catch{}})();var Ba=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"}),Wa=/&(?:lt|gt|quot|#39|amp);/g;function Ga(e){return typeof e!="string"||!e.includes("&lt;")&&!e.includes("&gt;")?e:e.replace(Wa,t=>Ba[t])}function Ka(e){return Ot(e,new WeakMap)}function Ot(e,t){if(typeof e=="string")return Ga(e);if(Array.isArray(e)){if(t.has(e))return t.get(e);let r=[];t.set(e,r);for(let n of e)r.push(Ot(n,t));return r}if(e!==null&&typeof e=="object"){if(!Qa(e))return e;if(t.has(e))return t.get(e);let r=e,n=Object.create(Object.getPrototypeOf(e));t.set(e,n);for(let[o,i]of Object.entries(r))Object.defineProperty(n,o,{value:Ot(i,t),enumerable:!0,writable:!0,configurable:!0});return n}return e}function Qa(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===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]="0ce743d1-917a-5c96-b038-c95e3922bc48")}catch{}})();function Ja(e){let t=null;return()=>(t??=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]="868dfae8-2575-5d5f-8425-c7e68aefdc84")}catch{}})();function gn(e){return e.split(/[\s,|]+/).map(t=>t.trim()).filter(t=>t.startsWith("--"))}function Xa(e){return gn(e)[0]??null}function Za(e,t){let r=Xa(t);if(r===null)return!1;let n=o=>o.slice(2).replaceAll("-","_");return gn(e).some(o=>!o.slice(2).includes("-")||r===o?!1:n(r)===n(o))}import yn from"node:fs/promises";import Me from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4baf0ef3-2412-51cf-9ade-18b5c6e610d1")}catch{}})();function ec(e){return"json_markdown"}function En(e,t){return Me.relative(e,t).replaceAll("\\","/")}function tc(e){return String(e).replaceAll(/[^a-zA-Z0-9._-]+/g,"_").slice(0,120)}async function rc(e,t,r="item_format:migrate",n=je,o){if(t!=="toon")throw new Error("Only toon item-format migration targets are supported. Markdown item files are legacy read-only input.");let i=new Set,s=new Set,a=[],c=0,d=ec(t),u=Object.entries(n);for(let[l,f]of u){let m=Me.join(e,f),g=[];try{g=await yn.readdir(m)}catch{continue}let _=new Map;for(let E of g){let I=Me.join(m,E),A=nr(I);if(!A)continue;let F=Me.extname(E),$=E.slice(0,E.length-F.length).trim();if($.length===0)continue;let K=_.get($)??{};K[A]=I,_.set($,K)}let y=[..._.keys()].sort((E,I)=>E.localeCompare(I));for(let E of y){let I=_.get(E);c+=1;let A=I[d];if(!A)continue;let F=I[t]??A,$=F===I[t]?t:d;try{let K=await yn.readFile(F,"utf8"),mo=Qe(K,{format:$,schema:o,onWarning:po=>a.push(`item_format_migration_parse_warning:${E}:${po}`)}),Ve=Ye(e,l,E,t,n),tr=Je(mo,{format:t,schema:o});await v(Ve)!==tr&&(await S(Ve,tr),a.push(...await ye({path:Ve,scope:"project",op:r})),i.add(E)),await ae(A),s.add(En(e,A)),a.push(...await ye({path:A,scope:"project",op:`${r}:remove`})),i.add(E)}catch(K){a.push(`item_format_migration_skipped:${En(e,F)}:${tc(K)}`)}}}return{target_format:t,scanned:c,migrated:[...i].sort((l,f)=>l.localeCompare(f)),removed:[...s].sort((l,f)=>l.localeCompare(f)),warnings: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]="f280c1df-b134-57c3-91f6-cbf5a37e6e31")}catch{}})();var nc=new Set(["completed","superseded"]);function oc(e){return e!==void 0&&nc.has(e)}function ic(e){if(e.type.trim().toLowerCase()!=="plan")return!1;let t=e.plan_steps??[];return t.length>0&&t.every(r=>r.status==="completed")}import sc from"node:readline/promises";import{stdin as ac,stdout as wn}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6783b122-a1a8-5f86-9ac5-2c3e811622ed")}catch{}})();var cc="PM_TELEMETRY_PROMPT",bn=new Set(["0","false","no","off"]),dc=new Set(["init","completion","completion-statuses","completion-tags","completion-types"]);function uc(e){return typeof e!="string"?!1:bn.has(e.trim().toLowerCase())}function lc(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t.length===0?!1:!bn.has(t)}function fc(e,t){if(t.json===!0||t.quiet===!0||process.stdin.isTTY!==!0||process.stdout.isTTY!==!0||uc(process.env[cc])||lc(process.env.CI))return!0;let r=e.trim().toLowerCase();return r.length===0?!0:dc.has(r)}function mc(e){let t=e.trim().toLowerCase();return!(t==="n"||t==="no")}async function pc(e){let r=`pm telemetry helps improve reliability and usage diagnostics.
8
8
  It is enabled by default and can be changed anytime via:
9
9
  pm config global set telemetry-tracking --policy disabled
10
10
  Enable telemetry now? [${e?"Y/n":"y/N"}] `,n=sc.createInterface({input:ac,output:wn});try{let o=await n.question(r);return o.trim().length===0?e:mc(o)}finally{n.close()}}async function _c(e,t){if(!fc(e,t))try{let r=J(process.cwd()),n=await V(r);if(n.telemetry.first_run_prompt_completed)return;let o=await pc(n.telemetry.enabled);n.telemetry.enabled=o,n.telemetry.first_run_prompt_completed=!0,await ue(r,n,"telemetry:first_run_prompt"),wn.write(`Telemetry ${o?"enabled":"disabled"} for this CLI install. Update any time with pm config global set telemetry-tracking --policy ${o?"disabled":"enabled"}.
11
- `)}catch{}}import P from"node:crypto";import{spawn as hc}from"node:child_process";import{mkdirSync as Pt,rmSync as gc,statSync as Nn}from"node:fs";import{mkdir as zt,readdir as yc,rm as qt,stat as Rn}from"node:fs/promises";import Ht from"node:os";import C from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fea9d81b-3deb-51f4-9ec3-76396ae1307d")}catch{}})();var Ec=C.join("runtime","telemetry","events.jsonl"),wc=C.join("runtime","telemetry","state.json"),bc=C.join("runtime","telemetry","otel-spans.jsonl"),Tc=8,Tn=500,Pe=1,Sn=1,Sc=100,xc=36e5,Ic=3e4,Dn=5e3,Ac=864e5,ze=65536,kn=6,Mn=20,On=15,vc=8192,Pn=[25,50,100,200],Cc=3600*1e3,zn=6e4,Lc=6e4,Nc="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",Rc="OTEL_EXPORTER_OTLP_ENDPOINT",Dc="OTEL_SERVICE_NAME",kc="PM_TELEMETRY_DISABLED",Mc="PM_NO_TELEMETRY",xn=new Set(["1","true","yes","on"]),Oc="PM_TELEMETRY_OTEL_DISABLED",Pc=new Set(["1","true","yes","on"]),zc="PM_TELEMETRY_INLINE_FLUSH",Fn="PM_TELEMETRY_FLUSH_CHILD",Fc="PM_TELEMETRY_SOURCE_CONTEXT",$c=["user","automation","test","dogfood"],In=Promise.resolve(),An=Promise.resolve();var Vc=new Set($c),Uc=new Set(["1","true","yes","on"]),Fe=P.randomUUID(),jc=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],qc=new Set(["literal","literals","regex","regexes","replacement","replacements"]),$n="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",Hc=new RegExp(`\\b(${$n})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),Yc=new RegExp(`(--${$n})(=|\\s+)([^\\s,;]+)`,"giu"),Bc=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,Wc=/bearer\s+[a-z0-9._=-]+/giu,Gc=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function pe(e){return C.join(e,Ec)}function $e(e){return C.join(e,bc)}function Kc(e){return C.dirname(pe(e))}function Vn(e){return C.join(e,wc)}function Yt(e){return C.join(e,"runtime","telemetry","flush.lock")}function Un(e){return C.join(e,"runtime","telemetry","flush.spawn.lock")}function Qc(){return C.join(de(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function Jc(){if($t(process.env[zc])||$t(process.env[Fn]))return!0;let e=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||e==="test"}async function Xc(e){let t=await v(Vn(e));if(!t||t.trim().length===0)return{};try{let r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)?{}:r}catch{return{}}}async function O(e,t){try{let n={...await Xc(e),...t},o=Object.fromEntries(Object.entries(n).filter(([,i])=>i!==void 0).sort((i,s)=>i[0].localeCompare(s[0])));await S(Vn(e),`${JSON.stringify(o,null,2)}
12
- `)}catch{}}function Ft(e){let t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),r=t.split("_").filter(n=>n.length>0);return qc.has(t)||jc.some(n=>t===n||t.endsWith(`_${n}`)||r.includes(n))}function jn(e){return e.replaceAll(Hc,(r,n,o)=>`${n}${o}[redacted]`).replaceAll(Yc,(r,n,o)=>`${n}${o}[redacted]`)}function qn(e){return e.replaceAll(Bc,(t,r)=>`${r}[redacted_path]`)}function Hn(e){let t=e>=65&&e<=90,r=e>=97&&e<=122,n=e>=48&&e<=57;return t||r||n}function Yn(e){if(!e)return!1;let t=e.charCodeAt(0);return Hn(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function Bn(e){if(!e)return!1;let t=e.charCodeAt(0);return Hn(t)?!0:e==="."||e==="-"}function Zc(e){let t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@")||t===e.length-1)return!1;let r=e.slice(0,t),n=e.slice(t+1),o=n.lastIndexOf(".");if(o<=0||o===n.length-1||n.length-(o+1)<2)return!1;for(let i of r)if(!Yn(i))return!1;for(let i of n)if(!Bn(i))return!1;return!0}function ed(e){let t="",r=0;for(;r<e.length;){let n=e.indexOf("@",r);if(n<0){t+=e.slice(r);break}let o=n-1;for(;o>=r&&Yn(e[o]);)o-=1;o+=1;let i=n+1;for(;i<e.length&&Bn(e[i]);)i+=1;let s=e.slice(o,i);if(Zc(s)){t+=e.slice(r,o),t+="[redacted_email]",r=i;continue}t+=e.slice(r,n+1),r=n+1}return t}function Wn(e){return ed(e).replaceAll(Wc,"bearer [redacted_token]").replaceAll(Gc,"[redacted_ip]")}function td(e){let t=Wn(e),r=jn(t),n=qn(r),o=n.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":n.length>512?`${n.slice(0,509)}...`:n}function rd(e){let t=Wn(e),r=jn(t),n=qn(r),o=n.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":n.length>2048?`${n.slice(0,2045)}...`:n}function T(e,t="redacted"){return t==="max"?rd(e):td(e)}function G(e,t,r="redacted",n=0){if(t&&Ft(t))return"[redacted]";if(e==null)return e;if(typeof e=="string")return T(e,r);if(typeof e=="number"||typeof e=="boolean")return e;if(n>=kn)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,Mn).map(o=>G(o,void 0,r,n+1));if(typeof e=="object"){let o=e,i={};for(let[s,a]of Object.entries(o))i[s]=G(a,s,r,n+1);return i}return String(e)}function Gn(e,t="redacted"){let r=[],n=!1;for(let o of e){let i=T(o,t);if(n){r.push("[redacted]"),n=!1;continue}if(i.startsWith("--")){let s=i.slice(2),a=s.indexOf("=");if(a>=0){let c=s.slice(0,a),d=s.slice(a+1);Ft(c)?r.push(`--${c}=[redacted]`):r.push(`--${c}=${T(d,t)}`);continue}if(Ft(s)){r.push(`--${s}`),n=!0;continue}}r.push(i)}return r}function Kn(e){let t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function $t(e){return Uc.has((e??"").trim().toLowerCase())}function Qn(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function Bt(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Wt(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Jn(e){if(!e.ok)return typeof e.errorCategory=="string"&&e.errorCategory.trim().length>0?e.errorCategory:typeof e.errorCode=="string"&&e.errorCode.trim().length>0?he(e.errorCode):"unknown"}function Xn(e){let t=(process.env[Fc]??"").trim().toLowerCase();if(Vc.has(t))return{source_context:t,source_context_source:"env_override"};let r=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||r==="test")return{source_context:"test",source_context_source:"inferred"};let n=process.stdin.isTTY!==!0||process.stdout.isTTY!==!0,o=$t(process.env.CI),i=e.json===!0||e.quiet===!0;return n||o||i?{source_context:"automation",source_context_source:"inferred"}:{source_context:"user",source_context_source:"inferred"}}function x(e,t){return P.createHash("sha256").update(`${e}:${t}`).digest("hex")}function Gt(e,t){let r=(Xe()??"").trim(),n=ar({env:process.env,argv:process.argv}),o=n.harness!==void 0||n.model!==void 0;return e==="minimal"?{has_author_context:r.length>0,has_agent_context:o}:{...r.length>0?{author_context_hash:x(t,r)}:{},...n.harness?{agent_harness_hash:x(t,n.harness)}:{},...n.model?{agent_model_hash:x(t,n.model)}:{},...n.model_source?{agent_model_source:n.model_source}:{}}}function Vt(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=kn)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,Mn).map(r=>Vt(r,t+1));if(typeof e=="object"){let r=e,n={},o=Object.keys(r).sort((i,s)=>i.localeCompare(s));for(let i of o)n[i]=Vt(r[i],t+1);return n}return String(e)}function Ut(e,t){return x(e,JSON.stringify(Vt(t)))}function Zn(e,t){return{hashes:t.map(r=>x(e,r)),digest:x(e,t.join("\0"))}}function eo(e,t,r,n){let o=T(typeof n=="string"?n:"","redacted"),i=typeof r=="string"&&r.length>0?r:"unknown_error",s=`${t}\0${i}\0${o}`;return x(e,s)}function Kt(){return xn.has((process.env[kc]??"").trim().toLowerCase())||xn.has((process.env[Mc]??"").trim().toLowerCase())}function nd(){if(Pc.has((process.env[Oc]??"").trim().toLowerCase()))return null;let e=(process.env[Nc]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}let t=(process.env[Rc]??"").trim();if(t.length===0)return null;try{let r=new URL(t),n=r.pathname.replace(/\/+$/,"");return n.endsWith("/v1/traces")||(r.pathname=`${n.length===0?"":n}/v1/traces`),r.toString()}catch{return null}}function vn(e){let t=Date.parse(e),r=Number.isNaN(t)?Date.now():t;return`${BigInt(r)*1000000n}`}function N(e,t){return{key:e,value:{stringValue:t}}}function od(e,t){return{key:e,value:{boolValue:t}}}function Cn(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function id(e,t,r,n){if(typeof e.otel_traces_endpoint!="string"||e.otel_traces_endpoint.trim().length===0||typeof e.otel_trace_id!="string"||e.otel_trace_id.length===0||typeof e.otel_span_id!="string"||e.otel_span_id.length===0)return null;let o=T((process.env[Dc]??"").trim()),i=o.length>0?o:"pm-cli",s=Wt(t.exit_code,t.ok),a=Bt(t.error_code),c=Jn({ok:t.ok,errorCode:a,errorCategory:t.error_category}),d=[N("pm.command",T(e.command)),N("pm.version",e.pm_version),N("pm.source_context",e.source_context),N("pm.source_context_source",e.source_context_source),N("pm.installation_id",e.installation_id),N("pm.session_id",Fe),N("pm.pm_root_hash",e.pm_root_hash),N("pm.cwd_hash",e.cwd_hash),od("pm.ok",t.ok),Cn("pm.exit_code",s),Cn("pm.duration_ms",n)];typeof a=="string"&&d.push(N("pm.error_code",a)),typeof c=="string"&&d.push(N("pm.error_category",c)),typeof t.error=="string"&&t.error.trim().length>0&&d.push(N("pm.error",T(t.error)));let u={resourceSpans:[{resource:{attributes:[N("service.name",i)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:e.otel_trace_id,spanId:e.otel_span_id,name:`pm.command.${T(e.command)}`,kind:1,startTimeUnixNano:vn(e.started_at),endTimeUnixNano:vn(r),attributes:d,status:{code:t.ok?1:2,message:t.ok?"":T(typeof t.error=="string"?t.error:"command_failed")}}]}]}]};return{endpoint:e.otel_traces_endpoint,payload:u}}function sd(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:T(e,t)};if(typeof e=="number"||typeof e=="boolean")return{type:typeof e,value:e};if(Array.isArray(e))return{type:"array",length:e.length,sample:e.slice(0,5).map(r=>G(r,void 0,t))};if(typeof e=="object"){let r=e,n=Object.keys(r).sort((s,a)=>s.localeCompare(a)),o={},i=0;for(let s of n.slice(0,25)){let a=G(r[s],s,t),c=JSON.stringify(a).length;if(i+c>vc){o[s]="[preview_truncated]";break}i+=c,o[s]=a}return{type:"object",key_count:n.length,keys_preview:n.slice(0,50),preview:o}}return{type:typeof e,value:String(e)}}function ad(e){let{captureLevel:t,context:r,pmVersion:n,sourceContext:o,pmRootHash:i,cwdHash:s,installationId:a}=e,c=oe(r.command),d=Zn(a,r.args),u=x(a,`${r.command}\0${r.args.join("\0")}`),l=Ut(a,r.options),f=Ut(a,r.global),m=Gt(t,a);return t==="minimal"?{capture_level:t,pm_version:n,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,command_args_digest:d.digest,command_invocation_digest:u,command_options_digest:l,global_options_digest:f,...m}:{pm_version:n,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,...m,command_args:Gn(r.args,t),command_args_hashes:d.hashes,command_args_digest:d.digest,command_invocation_digest:u,command_options:G(r.options,void 0,t),command_options_digest:l,global_options:G(r.global,void 0,t),global_options_digest:f,pm_root_hash:i,cwd_hash:s,capture_level:t,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:x(a,Ht.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function cd(e){let{captureLevel:t,pmVersion:r,sourceContext:n,outcome:o,durationMs:i,startedAt:s,command:a,installationId:c,commandTaxonomy:d,exitCode:u,errorCode:l,errorCategory:f,commandResolution:m,resolutionStage:g}=e,_=o.ok===!1?eo(c,a,l,o.error):void 0,y=Gt(t,c);return t==="minimal"?{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:d,command_resolution:m,resolution_stage:g,ok:o.ok,exit_code:u,error_code:l,error_category:f,error:o.error?T(o.error,"redacted"):void 0,error_fingerprint:_,duration_ms:i,...y}:{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:d,command_resolution:m,resolution_stage:g,...y,ok:o.ok,exit_code:u,error_code:l,error_category:f,error:o.error?T(o.error,t):void 0,error_fingerprint:_,duration_ms:i,started_at:s,result_summary:sd(o.result,t)}}function dd(e){let{captureLevel:t,pmVersion:r,sourceContext:n,command:o,commandTaxonomy:i,commandResolution:s,resolutionStage:a,args:c,options:d,pmRootHash:u,cwdHash:l,installationId:f,errorCode:m,errorMessage:g,errorCategory:_,exitCode:y}=e,E=Zn(f,c),I=x(f,o),A=Ut(f,d),F=eo(f,o,m,g),$=Gt(t,f);return t==="minimal"?{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,attempted_command_digest:I,attempted_args_digest:E.digest,attempted_options_digest:A,error_code:m,error_category:_,exit_code:y,error:T(g,"redacted"),error_fingerprint:F,...$}:{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,...$,attempted_command:T(o,t),attempted_command_digest:I,attempted_args:Gn(c,t),attempted_args_hashes:E.hashes,attempted_args_digest:E.digest,attempted_options:G(d,void 0,t),attempted_options_digest:A,error_code:m,error_category:_,exit_code:y,error:T(g,t),error_fingerprint:F,pm_root_hash:u,cwd_hash:l,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:x(f,Ht.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function Qt(e){let t=await V(e),r=!1;return t.telemetry.installation_id.trim().length===0&&(t.telemetry.installation_id=P.randomUUID(),r=!0),r&&await ue(e,t,"telemetry:install_id"),{installationId:t.telemetry.installation_id,endpoint:t.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(t.telemetry.retention_days))}}async function Jt(e,t){let n=JSON.stringify({client_schema_version:Sn,event:t,attempts:0});if(n.length>ze){let o={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:n.length}}};n=JSON.stringify({client_schema_version:Sn,event:o,attempts:0})}await _e(async()=>{await Ue(pe(e),n)})}function to(e){let t=[];for(let r of e.split(`
11
+ `)}catch{}}import P from"node:crypto";import{spawn as hc}from"node:child_process";import{mkdirSync as Pt,rmSync as gc,statSync as Nn}from"node:fs";import{mkdir as zt,readdir as yc,rm as qt,stat as Rn}from"node:fs/promises";import Ht from"node:os";import C from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fea9d81b-3deb-51f4-9ec3-76396ae1307d")}catch{}})();var Ec=C.join("runtime","telemetry","events.jsonl"),wc=C.join("runtime","telemetry","state.json"),bc=C.join("runtime","telemetry","otel-spans.jsonl"),Tc=8,Tn=500,Pe=1,Sn=1,Sc=100,xc=36e5,Ic=3e4,kn=5e3,Ac=864e5,ze=65536,Dn=6,Mn=20,On=15,vc=8192,Pn=[25,50,100,200],Cc=3600*1e3,zn=6e4,Lc=6e4,Nc="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",Rc="OTEL_EXPORTER_OTLP_ENDPOINT",kc="OTEL_SERVICE_NAME",Dc="PM_TELEMETRY_DISABLED",Mc="PM_NO_TELEMETRY",xn=new Set(["1","true","yes","on"]),Oc="PM_TELEMETRY_OTEL_DISABLED",Pc=new Set(["1","true","yes","on"]),zc="PM_TELEMETRY_INLINE_FLUSH",Fn="PM_TELEMETRY_FLUSH_CHILD",Fc="PM_TELEMETRY_SOURCE_CONTEXT",$c=["user","automation","test","dogfood"],In=Promise.resolve(),An=Promise.resolve();var Vc=new Set($c),Uc=new Set(["1","true","yes","on"]),Fe=P.randomUUID(),jc=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],qc=new Set(["literal","literals","regex","regexes","replacement","replacements"]),$n="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",Hc=new RegExp(`\\b(${$n})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),Yc=new RegExp(`(--${$n})(=|\\s+)([^\\s,;]+)`,"giu"),Bc=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,Wc=/bearer\s+[a-z0-9._=-]+/giu,Gc=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function pe(e){return C.join(e,Ec)}function $e(e){return C.join(e,bc)}function Kc(e){return C.dirname(pe(e))}function Vn(e){return C.join(e,wc)}function Yt(e){return C.join(e,"runtime","telemetry","flush.lock")}function Un(e){return C.join(e,"runtime","telemetry","flush.spawn.lock")}function Qc(){return C.join(de(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function Jc(){if($t(process.env[zc])||$t(process.env[Fn]))return!0;let e=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||e==="test"}async function Xc(e){let t=await v(Vn(e));if(!t||t.trim().length===0)return{};try{let r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)?{}:r}catch{return{}}}async function O(e,t){try{let n={...await Xc(e),...t},o=Object.fromEntries(Object.entries(n).filter(([,i])=>i!==void 0).sort((i,s)=>i[0].localeCompare(s[0])));await S(Vn(e),`${JSON.stringify(o,null,2)}
12
+ `)}catch{}}function Ft(e){let t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),r=t.split("_").filter(n=>n.length>0);return qc.has(t)||jc.some(n=>t===n||t.endsWith(`_${n}`)||r.includes(n))}function jn(e){return e.replaceAll(Hc,(r,n,o)=>`${n}${o}[redacted]`).replaceAll(Yc,(r,n,o)=>`${n}${o}[redacted]`)}function qn(e){return e.replaceAll(Bc,(t,r)=>`${r}[redacted_path]`)}function Hn(e){let t=e>=65&&e<=90,r=e>=97&&e<=122,n=e>=48&&e<=57;return t||r||n}function Yn(e){if(!e)return!1;let t=e.charCodeAt(0);return Hn(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function Bn(e){if(!e)return!1;let t=e.charCodeAt(0);return Hn(t)?!0:e==="."||e==="-"}function Zc(e){let t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@")||t===e.length-1)return!1;let r=e.slice(0,t),n=e.slice(t+1),o=n.lastIndexOf(".");if(o<=0||o===n.length-1||n.length-(o+1)<2)return!1;for(let i of r)if(!Yn(i))return!1;for(let i of n)if(!Bn(i))return!1;return!0}function ed(e){let t="",r=0;for(;r<e.length;){let n=e.indexOf("@",r);if(n<0){t+=e.slice(r);break}let o=n-1;for(;o>=r&&Yn(e[o]);)o-=1;o+=1;let i=n+1;for(;i<e.length&&Bn(e[i]);)i+=1;let s=e.slice(o,i);if(Zc(s)){t+=e.slice(r,o),t+="[redacted_email]",r=i;continue}t+=e.slice(r,n+1),r=n+1}return t}function Wn(e){return ed(e).replaceAll(Wc,"bearer [redacted_token]").replaceAll(Gc,"[redacted_ip]")}function td(e){let t=Wn(e),r=jn(t),n=qn(r),o=n.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":n.length>512?`${n.slice(0,509)}...`:n}function rd(e){let t=Wn(e),r=jn(t),n=qn(r),o=n.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":n.length>2048?`${n.slice(0,2045)}...`:n}function T(e,t="redacted"){return t==="max"?rd(e):td(e)}function G(e,t,r="redacted",n=0){if(t&&Ft(t))return"[redacted]";if(e==null)return e;if(typeof e=="string")return T(e,r);if(typeof e=="number"||typeof e=="boolean")return e;if(n>=Dn)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,Mn).map(o=>G(o,void 0,r,n+1));if(typeof e=="object"){let o=e,i={};for(let[s,a]of Object.entries(o))i[s]=G(a,s,r,n+1);return i}return String(e)}function Gn(e,t="redacted"){let r=[],n=!1;for(let o of e){let i=T(o,t);if(n){r.push("[redacted]"),n=!1;continue}if(i.startsWith("--")){let s=i.slice(2),a=s.indexOf("=");if(a>=0){let c=s.slice(0,a),d=s.slice(a+1);Ft(c)?r.push(`--${c}=[redacted]`):r.push(`--${c}=${T(d,t)}`);continue}if(Ft(s)){r.push(`--${s}`),n=!0;continue}}r.push(i)}return r}function Kn(e){let t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function $t(e){return Uc.has((e??"").trim().toLowerCase())}function Qn(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function Bt(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Wt(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Jn(e){if(!e.ok)return typeof e.errorCategory=="string"&&e.errorCategory.trim().length>0?e.errorCategory:typeof e.errorCode=="string"&&e.errorCode.trim().length>0?he(e.errorCode):"unknown"}function Xn(e){let t=(process.env[Fc]??"").trim().toLowerCase();if(Vc.has(t))return{source_context:t,source_context_source:"env_override"};let r=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||r==="test")return{source_context:"test",source_context_source:"inferred"};let n=process.stdin.isTTY!==!0||process.stdout.isTTY!==!0,o=$t(process.env.CI),i=e.json===!0||e.quiet===!0;return n||o||i?{source_context:"automation",source_context_source:"inferred"}:{source_context:"user",source_context_source:"inferred"}}function x(e,t){return P.createHash("sha256").update(`${e}:${t}`).digest("hex")}function Gt(e,t){let r=(Xe()??"").trim(),n=ar({env:process.env,argv:process.argv}),o=n.harness!==void 0||n.model!==void 0;return e==="minimal"?{has_author_context:r.length>0,has_agent_context:o}:{...r.length>0?{author_context_hash:x(t,r)}:{},...n.harness?{agent_harness_hash:x(t,n.harness)}:{},...n.model?{agent_model_hash:x(t,n.model)}:{},...n.model_source?{agent_model_source:n.model_source}:{}}}function Vt(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=Dn)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,Mn).map(r=>Vt(r,t+1));if(typeof e=="object"){let r=e,n={},o=Object.keys(r).sort((i,s)=>i.localeCompare(s));for(let i of o)n[i]=Vt(r[i],t+1);return n}return String(e)}function Ut(e,t){return x(e,JSON.stringify(Vt(t)))}function Zn(e,t){return{hashes:t.map(r=>x(e,r)),digest:x(e,t.join("\0"))}}function eo(e,t,r,n){let o=T(typeof n=="string"?n:"","redacted"),i=typeof r=="string"&&r.length>0?r:"unknown_error",s=`${t}\0${i}\0${o}`;return x(e,s)}function Kt(){return xn.has((process.env[Dc]??"").trim().toLowerCase())||xn.has((process.env[Mc]??"").trim().toLowerCase())}function nd(){if(Pc.has((process.env[Oc]??"").trim().toLowerCase()))return null;let e=(process.env[Nc]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}let t=(process.env[Rc]??"").trim();if(t.length===0)return null;try{let r=new URL(t),n=r.pathname.replace(/\/+$/,"");return n.endsWith("/v1/traces")||(r.pathname=`${n.length===0?"":n}/v1/traces`),r.toString()}catch{return null}}function vn(e){let t=Date.parse(e),r=Number.isNaN(t)?Date.now():t;return`${BigInt(r)*1000000n}`}function N(e,t){return{key:e,value:{stringValue:t}}}function od(e,t){return{key:e,value:{boolValue:t}}}function Cn(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function id(e,t,r,n){if(typeof e.otel_traces_endpoint!="string"||e.otel_traces_endpoint.trim().length===0||typeof e.otel_trace_id!="string"||e.otel_trace_id.length===0||typeof e.otel_span_id!="string"||e.otel_span_id.length===0)return null;let o=T((process.env[kc]??"").trim()),i=o.length>0?o:"pm-cli",s=Wt(t.exit_code,t.ok),a=Bt(t.error_code),c=Jn({ok:t.ok,errorCode:a,errorCategory:t.error_category}),d=[N("pm.command",T(e.command)),N("pm.version",e.pm_version),N("pm.source_context",e.source_context),N("pm.source_context_source",e.source_context_source),N("pm.installation_id",e.installation_id),N("pm.session_id",Fe),N("pm.pm_root_hash",e.pm_root_hash),N("pm.cwd_hash",e.cwd_hash),od("pm.ok",t.ok),Cn("pm.exit_code",s),Cn("pm.duration_ms",n)];typeof a=="string"&&d.push(N("pm.error_code",a)),typeof c=="string"&&d.push(N("pm.error_category",c)),typeof t.error=="string"&&t.error.trim().length>0&&d.push(N("pm.error",T(t.error)));let u={resourceSpans:[{resource:{attributes:[N("service.name",i)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:e.otel_trace_id,spanId:e.otel_span_id,name:`pm.command.${T(e.command)}`,kind:1,startTimeUnixNano:vn(e.started_at),endTimeUnixNano:vn(r),attributes:d,status:{code:t.ok?1:2,message:t.ok?"":T(typeof t.error=="string"?t.error:"command_failed")}}]}]}]};return{endpoint:e.otel_traces_endpoint,payload:u}}function sd(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:T(e,t)};if(typeof e=="number"||typeof e=="boolean")return{type:typeof e,value:e};if(Array.isArray(e))return{type:"array",length:e.length,sample:e.slice(0,5).map(r=>G(r,void 0,t))};if(typeof e=="object"){let r=e,n=Object.keys(r).sort((s,a)=>s.localeCompare(a)),o={},i=0;for(let s of n.slice(0,25)){let a=G(r[s],s,t),c=JSON.stringify(a).length;if(i+c>vc){o[s]="[preview_truncated]";break}i+=c,o[s]=a}return{type:"object",key_count:n.length,keys_preview:n.slice(0,50),preview:o}}return{type:typeof e,value:String(e)}}function ad(e){let{captureLevel:t,context:r,pmVersion:n,sourceContext:o,pmRootHash:i,cwdHash:s,installationId:a}=e,c=oe(r.command),d=Zn(a,r.args),u=x(a,`${r.command}\0${r.args.join("\0")}`),l=Ut(a,r.options),f=Ut(a,r.global),m=Gt(t,a);return t==="minimal"?{capture_level:t,pm_version:n,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,command_args_digest:d.digest,command_invocation_digest:u,command_options_digest:l,global_options_digest:f,...m}:{pm_version:n,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,...m,command_args:Gn(r.args,t),command_args_hashes:d.hashes,command_args_digest:d.digest,command_invocation_digest:u,command_options:G(r.options,void 0,t),command_options_digest:l,global_options:G(r.global,void 0,t),global_options_digest:f,pm_root_hash:i,cwd_hash:s,capture_level:t,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:x(a,Ht.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function cd(e){let{captureLevel:t,pmVersion:r,sourceContext:n,outcome:o,durationMs:i,startedAt:s,command:a,installationId:c,commandTaxonomy:d,exitCode:u,errorCode:l,errorCategory:f,commandResolution:m,resolutionStage:g}=e,_=o.ok===!1?eo(c,a,l,o.error):void 0,y=Gt(t,c);return t==="minimal"?{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:d,command_resolution:m,resolution_stage:g,ok:o.ok,exit_code:u,error_code:l,error_category:f,error:o.error?T(o.error,"redacted"):void 0,error_fingerprint:_,duration_ms:i,...y}:{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:d,command_resolution:m,resolution_stage:g,...y,ok:o.ok,exit_code:u,error_code:l,error_category:f,error:o.error?T(o.error,t):void 0,error_fingerprint:_,duration_ms:i,started_at:s,result_summary:sd(o.result,t)}}function dd(e){let{captureLevel:t,pmVersion:r,sourceContext:n,command:o,commandTaxonomy:i,commandResolution:s,resolutionStage:a,args:c,options:d,pmRootHash:u,cwdHash:l,installationId:f,errorCode:m,errorMessage:g,errorCategory:_,exitCode:y}=e,E=Zn(f,c),I=x(f,o),A=Ut(f,d),F=eo(f,o,m,g),$=Gt(t,f);return t==="minimal"?{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,attempted_command_digest:I,attempted_args_digest:E.digest,attempted_options_digest:A,error_code:m,error_category:_,exit_code:y,error:T(g,"redacted"),error_fingerprint:F,...$}:{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,...$,attempted_command:T(o,t),attempted_command_digest:I,attempted_args:Gn(c,t),attempted_args_hashes:E.hashes,attempted_args_digest:E.digest,attempted_options:G(d,void 0,t),attempted_options_digest:A,error_code:m,error_category:_,exit_code:y,error:T(g,t),error_fingerprint:F,pm_root_hash:u,cwd_hash:l,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:x(f,Ht.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function Qt(e){let t=await V(e),r=!1;return t.telemetry.installation_id.trim().length===0&&(t.telemetry.installation_id=P.randomUUID(),r=!0),r&&await ue(e,t,"telemetry:install_id"),{installationId:t.telemetry.installation_id,endpoint:t.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(t.telemetry.retention_days))}}async function Jt(e,t){let n=JSON.stringify({client_schema_version:Sn,event:t,attempts:0});if(n.length>ze){let o={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:n.length}}};n=JSON.stringify({client_schema_version:Sn,event:o,attempts:0})}await _e(async()=>{await Ue(pe(e),n)})}function to(e){let t=[];for(let r of e.split(`
13
13
  `)){let n=r.trim();if(n.length!==0)try{let o=JSON.parse(n);o&&typeof o=="object"&&o.event&&typeof o.event=="object"&&typeof o.attempts=="number"&&(o.client_schema_version===void 0||typeof o.client_schema_version=="number"&&Number.isFinite(o.client_schema_version))&&t.push(o)}catch{}}return t}function ro(e){let t=Math.min(Ic*2**Math.max(e-1,0),xc);return new Date(Date.now()+t).toISOString()}function no(e){if(typeof e!="string"||e.trim().length===0)return!0;let t=Date.parse(e);return Number.isNaN(t)?!0:t<=Date.now()}function ud(e){return no(e.next_attempt_after)}function oo(e){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*Ac}function ld(e,t){let r=e.event?.occurred_at;if(typeof r!="string"||r.trim().length===0)return!1;let n=Date.parse(r);return Number.isNaN(n)?!1:n<t}function Xt(e,t){let r=oo(t),n=[],o=0;for(let i of e){if(JSON.stringify(i).length>ze||ld(i,r)||i.attempts>=On){o+=1;continue}n.push(i)}return{entries:n,prunedCount:o}}async function Oe(e,t){let r=t.map(o=>JSON.stringify(o)).join(`
14
14
  `),n=r.length>0?`${r}
15
15
  `:"";for(let o=0;;o+=1)try{await S(pe(e),n);return}catch(i){let s=Pn[o];if(s===void 0||!io(i))throw i;await so(s)}}function io(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function so(e){return new Promise(t=>{setTimeout(t,e)})}async function fd(e,t){let r={id:P.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:L(),attempts:0},n=JSON.stringify(r);n.length>ze||await _e(async()=>{await Ue($e(e),n)})}function md(e){let t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return P.createHash("sha256").update(t).digest("hex").slice(0,32)}function ao(e){let t=[];for(let r of e.split(`
16
16
  `)){let n=r.trim();if(n.length!==0)try{let o=JSON.parse(n);o&&typeof o=="object"&&typeof o.endpoint=="string"&&o.endpoint.trim().length>0&&"payload"in o&&typeof o.attempts=="number"&&Number.isFinite(o.attempts)&&((typeof o.id!="string"||o.id.length===0)&&(o.id=md(o)),t.push(o))}catch{}}return t}function pd(e,t){if(typeof e.enqueued_at!="string"||e.enqueued_at.trim().length===0)return!1;let r=Date.parse(e.enqueued_at);return Number.isNaN(r)?!1:r<t}function co(e,t){let r=oo(t),n=[],o=0;for(let i of e){if(JSON.stringify(i).length>ze||pd(i,r)||i.attempts>=On){o+=1;continue}n.push(i)}if(n.length>Tn){let i=n.length-Tn;return o+=i,{entries:n.slice(i),prunedCount:o}}return{entries:n,prunedCount:o}}async function _d(e,t){let r=t.map(o=>JSON.stringify(o)).join(`
17
17
  `),n=r.length>0?`${r}
18
- `:"";for(let o=0;;o+=1)try{await S($e(e),n);return}catch(i){let s=Pn[o];if(s===void 0||!io(i))throw i;await so(s)}}async function Ln(e,t,r,n){return _e(async()=>{let o=await v($e(e)),i=o===null?[]:ao(o),s=[];for(let c of i){if(r.has(c.id))continue;let d=n.get(c.id);s.push(d?{...c,attempts:d.attempts,next_attempt_after:d.next_attempt_after}:c)}let{entries:a}=co(s,t);return await _d(e,a),a.length})}async function hd(e,t){let r=await v($e(e));if(r===null||r.trim().length===0){await O(e,{pending_otel_spans:0});return}let n=ao(r),{entries:o,prunedCount:i}=co(n,t),s=o.filter(g=>no(g.next_attempt_after)).slice(0,Tc);if(s.length===0){let g=i>0?await Ln(e,t,new Set,new Map):o.length;await O(e,{pending_otel_spans:g});return}let a=L(),c=new Set,d=new Map,u=0,l;await Promise.all(s.map(async g=>{try{let _=await fetch(g.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(g.payload),signal:AbortSignal.timeout(Dn)});if(!_.ok)throw new Error(`local_otel_export_http_${_.status}`);c.add(g.id),u+=1}catch(_){l=_ instanceof Error?T(_.message,"redacted"):"local_otel_export_failed";let y=g.attempts+1;d.set(g.id,{attempts:y,next_attempt_after:ro(y)})}}));let f=await Ln(e,t,c,d),m={pending_otel_spans:f,last_otel_attempt_at:a};u>0&&(m.last_otel_success_at=a),l!==void 0?(m.last_otel_failure_at=a,m.last_otel_failure_error=l):f===0&&(m.last_otel_failure_at=void 0,m.last_otel_failure_error=void 0),await O(e,m)}async function uo(e,t,r){try{await wd(e,t,r)}catch{}try{await hd(e,r)}catch{}}async function gd(e,t=Cc){try{let r=Kc(e),n=await yc(r,{withFileTypes:!0}),o=Date.now()-Math.max(0,t);await Promise.all(n.filter(i=>i.isFile()&&/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(i.name)).map(async i=>{let s=C.join(r,i.name);(await Rn(s)).mtimeMs<o&&await qt(s,{force:!0})}))}catch{}}async function _e(e){let t=An.catch(()=>{}).then(e);return An=t.catch(()=>{}),t}async function Zt(e){let t=await v(pe(e));return t===null||t.trim().length===0?[]:to(t)}async function yd(e,t,r){return _e(async()=>{let n=await Zt(e),{entries:o}=Xt(n,r),i=o.filter(s=>!t.has(s.event.event_id));return await Oe(e,i),i})}async function Ed(e,t,r,n){return _e(async()=>{let o=await Zt(e),{entries:i}=Xt(o,n),s=i.map(a=>{if(!t.has(a.event.event_id))return a;let c=a.attempts+1;return{...a,attempts:c,last_attempt_at:r,next_attempt_after:ro(c)}});return await Oe(e,s),s})}async function wd(e,t,r){await gd(e);let n=t.trim();if(n.length===0)return;let o=await v(pe(e));if(o===null||o.trim().length===0){await O(e,{endpoint:n,queue_entries:0});return}let i=to(o);if(i.length===0){await O(e,{endpoint:n,queue_entries:0});return}let{entries:s,prunedCount:a}=Xt(i,r);if(s.length===0){await Oe(e,[]),await O(e,{endpoint:n,queue_entries:0});return}let c=s.filter(m=>ud(m)).slice(0,Sc);if(c.length===0){a>0&&await Oe(e,s),await O(e,{endpoint:n,queue_entries:s.length});return}let d=new Set(c.map(m=>m.event.event_id)),u=L(),l={"content-type":"application/json"},f=process.env.PM_TELEMETRY_INGEST_KEY?.trim();f&&(l["x-pm-telemetry-key"]=f);try{let m=await fetch(n,{method:"POST",headers:l,body:JSON.stringify({schema_version:Pe,events:c.map(g=>g.event)}),signal:AbortSignal.timeout(Dn)});if(!m.ok)throw new Error(`telemetry_flush_http_${m.status}`)}catch(m){let g=await Ed(e,d,u,r),_=m instanceof Error?T(m.message,"redacted"):"telemetry_flush_failed";await O(e,{endpoint:n,queue_entries:g.length,last_attempted_flush_at:u,last_failed_flush_at:u,last_failed_flush_error:_});return}try{let m=await yd(e,d,r);await O(e,{endpoint:n,queue_entries:m.length,last_attempted_flush_at:u,last_successful_flush_at:u,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(m){let g=m instanceof Error?T(m.message,"redacted"):"telemetry_flush_failed",_=await Zt(e).catch(()=>s);await O(e,{endpoint:n,queue_entries:_.length,last_attempted_flush_at:u,last_failed_flush_at:u,last_failed_flush_error:g})}}async function bd(e){let t=Yt(e);await zt(C.dirname(t),{recursive:!0});try{return await zt(t),!0}catch(r){if(typeof r!="object"||r===null||!("code"in r)||r.code!=="EEXIST")throw r}try{let r=await Rn(t);return Date.now()-r.mtimeMs<zn?!1:(await qt(t,{recursive:!0,force:!0}),await zt(t),!0)}catch{return!1}}function Td(e,t){try{return Date.now()-Nn(e).mtimeMs<t}catch{return!1}}function lo(e){try{gc(e,{recursive:!0,force:!0})}catch{}}function fo(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function Sd(e){try{return Pt(e),!0}catch(t){let r=fo(t);if(r==="EEXIST"||r!=="ENOENT")return!1}try{return Pt(C.dirname(e),{recursive:!0}),Pt(e),!0}catch{return!1}}function xd(e){if(Td(Yt(e),zn))return!1;let t=Un(e);try{if(Date.now()-Nn(t).mtimeMs<Lc)return!1;lo(t)}catch(r){if(fo(r)!=="ENOENT")return!1}return Sd(t)}function jt(e){lo(Un(e))}async function Id(e,t,r){let n=await bd(e);if(jt(e),!!n)try{await uo(e,t,r)}finally{try{await qt(Yt(e),{recursive:!0,force:!0})}catch{}}}function er(e,t,r){if(Jc()){let n=In,o=uo(e,t,r);In=Promise.allSettled([n,o]).then(()=>{});return}try{if(!xd(e))return;let o=hc(process.execPath,[Qc()],{detached:!0,stdio:"ignore",cwd:Ht.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[Fn]:"1"}});o.on("error",()=>{jt(e)}),o.unref()}catch{jt(e)}}async function pf(e=J(process.cwd())){if(!Kt())try{if(!(await V(e)).telemetry.enabled)return;let{endpoint:r,retentionDays:n}=await Qt(e);await Id(e,r,n)}catch{}}async function Ad(e){if(Kt()||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=J(process.cwd()),r=await V(t);if(!r.telemetry.enabled)return null;let n=Kn(r.telemetry.capture_level),{installationId:o,endpoint:i,retentionDays:s}=await Qt(t),a=Qn(e.pm_version),c=Xn(e.global),d=x(o,e.pm_root),u=x(o,process.cwd()),l=nd(),f=L(),m={schema_version:Pe,event_id:P.randomUUID(),event_type:"command_start",occurred_at:f,installation_id:o,session_id:Fe,command:e.command,payload:ad({captureLevel:n,context:e,pmVersion:a,sourceContext:c,pmRootHash:d,cwdHash:u,installationId:o})};await Jt(t,m),er(t,i,s);let g=oe(e.command);return{started_at:f,started_at_ms:Date.now(),command:e.command,command_taxonomy:g,pm_version:a,source_context:c.source_context,source_context_source:c.source_context_source,installation_id:o,pm_root_hash:d,cwd_hash:u,endpoint:i,retention_days:s,global_pm_root:t,capture_level:n,otel_traces_endpoint:l??void 0,otel_trace_id:l?P.randomBytes(16).toString("hex"):void 0,otel_span_id:l?P.randomBytes(8).toString("hex"):void 0}}catch{return null}}async function vd(e,t){if(e)try{let r=L(),n=Math.max(0,Date.now()-e.started_at_ms),o=Bt(Nt({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),i=Jn({ok:t.ok,errorCode:o,errorCategory:t.error_category}),s=Wt(t.exit_code,t.ok),a=t.command_resolution??ie({ok:t.ok,errorCode:o,errorCategory:i}),c=t.resolution_stage??"execute",d={schema_version:Pe,event_id:P.randomUUID(),event_type:"command_finish",occurred_at:r,installation_id:e.installation_id,session_id:Fe,command:e.command,payload:cd({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:n,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:s,errorCode:o,errorCategory:i,commandResolution:a,resolutionStage:c})};await Jt(e.global_pm_root,d);let u=id(e,{...t,exit_code:s,error_code:o,error_category:i},r,n);u&&await fd(e.global_pm_root,u),er(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function Cd(e){if(!Kt())try{let t=J(process.cwd()),r=await V(t);if(!r.telemetry.enabled)return;let n=Kn(r.telemetry.capture_level),{installationId:o,endpoint:i,retentionDays:s}=await Qt(t),a=Qn(e.pm_version),c=Xn(e.global),d=x(o,e.pm_root),u=x(o,process.cwd()),l=L(),f=Bt(Nt({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),m=e.error_category??he(f),g=Wt(e.exit_code,!1),_=e.command.trim().length>0?e.command:"<unknown>",y=oe(_),E=e.command_resolution??ie({ok:!1,errorCode:f,errorCategory:m}),I=e.resolution_stage??"unknown",A={schema_version:Pe,event_id:P.randomUUID(),event_type:"command_error",occurred_at:l,installation_id:o,session_id:Fe,command:T(_,"redacted"),payload:dd({captureLevel:n,pmVersion:a,sourceContext:c,command:_,commandTaxonomy:y,commandResolution:E,resolutionStage:I,args:e.args,options:e.options,pmRootHash:d,cwdHash:u,installationId:o,errorCode:f,errorCategory:m,exitCode:g,errorMessage:e.error_message})};await Jt(t,A),er(t,i,s)}catch{}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="89efaf82-c9cb-560d-b1ca-5a676b4b979c")}catch{}})();export{yo as a,Eo as b,bo as c,To as d,So as e,xo as f,Fd as g,vo as h,Wd as i,Lo as j,fr as k,No as l,Ro as m,Mo as n,eu as o,zo as p,su as q,Uo as r,qo as s,Ho as t,Yo as u,Bo as v,Wo as w,ee as x,Sr as y,Ti as z,Au as A,Du as B,Se as C,kr as D,ct as E,Vi as F,Ui as G,Ou as H,Mr as I,te as J,ut as K,ft as L,Ce as M,Bu as N,bt as O,Ne as P,Ur as Q,Re as R,Tt as S,St as T,xt as U,It as V,Wr as W,Gr as X,qr as Y,zs as Z,ca as _,ie as $,Ea as aa,wa as ba,ba as ca,Ta as da,Sa as ea,Ia as fa,va as ga,Ca as ha,La as ia,Oa as ja,fn as ka,za as la,Fa as ma,$a as na,Nl as oa,Mt as pa,pn as qa,mn as ra,_n as sa,Ua as ta,ja as ua,hn as va,Ya as wa,Ka as xa,Ja as ya,Za as za,rc as Aa,oc as Ba,ic as Ca,_c as Da,Pe as Ea,On as Fa,$c as Ga,pf as Ha,Ad as Ia,vd as Ja,Cd as Ka};
19
- //# sourceMappingURL=chunk-MDTH7SAE.js.map
18
+ `:"";for(let o=0;;o+=1)try{await S($e(e),n);return}catch(i){let s=Pn[o];if(s===void 0||!io(i))throw i;await so(s)}}async function Ln(e,t,r,n){return _e(async()=>{let o=await v($e(e)),i=o===null?[]:ao(o),s=[];for(let c of i){if(r.has(c.id))continue;let d=n.get(c.id);s.push(d?{...c,attempts:d.attempts,next_attempt_after:d.next_attempt_after}:c)}let{entries:a}=co(s,t);return await _d(e,a),a.length})}async function hd(e,t){let r=await v($e(e));if(r===null||r.trim().length===0){await O(e,{pending_otel_spans:0});return}let n=ao(r),{entries:o,prunedCount:i}=co(n,t),s=o.filter(g=>no(g.next_attempt_after)).slice(0,Tc);if(s.length===0){let g=i>0?await Ln(e,t,new Set,new Map):o.length;await O(e,{pending_otel_spans:g});return}let a=L(),c=new Set,d=new Map,u=0,l;await Promise.all(s.map(async g=>{try{let _=await fetch(g.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(g.payload),signal:AbortSignal.timeout(kn)});if(!_.ok)throw new Error(`local_otel_export_http_${_.status}`);c.add(g.id),u+=1}catch(_){l=_ instanceof Error?T(_.message,"redacted"):"local_otel_export_failed";let y=g.attempts+1;d.set(g.id,{attempts:y,next_attempt_after:ro(y)})}}));let f=await Ln(e,t,c,d),m={pending_otel_spans:f,last_otel_attempt_at:a};u>0&&(m.last_otel_success_at=a),l!==void 0?(m.last_otel_failure_at=a,m.last_otel_failure_error=l):f===0&&(m.last_otel_failure_at=void 0,m.last_otel_failure_error=void 0),await O(e,m)}async function uo(e,t,r){try{await wd(e,t,r)}catch{}try{await hd(e,r)}catch{}}async function gd(e,t=Cc){try{let r=Kc(e),n=await yc(r,{withFileTypes:!0}),o=Date.now()-Math.max(0,t);await Promise.all(n.filter(i=>i.isFile()&&/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(i.name)).map(async i=>{let s=C.join(r,i.name);(await Rn(s)).mtimeMs<o&&await qt(s,{force:!0})}))}catch{}}async function _e(e){let t=An.catch(()=>{}).then(e);return An=t.catch(()=>{}),t}async function Zt(e){let t=await v(pe(e));return t===null||t.trim().length===0?[]:to(t)}async function yd(e,t,r){return _e(async()=>{let n=await Zt(e),{entries:o}=Xt(n,r),i=o.filter(s=>!t.has(s.event.event_id));return await Oe(e,i),i})}async function Ed(e,t,r,n){return _e(async()=>{let o=await Zt(e),{entries:i}=Xt(o,n),s=i.map(a=>{if(!t.has(a.event.event_id))return a;let c=a.attempts+1;return{...a,attempts:c,last_attempt_at:r,next_attempt_after:ro(c)}});return await Oe(e,s),s})}async function wd(e,t,r){await gd(e);let n=t.trim();if(n.length===0)return;let o=await v(pe(e));if(o===null||o.trim().length===0){await O(e,{endpoint:n,queue_entries:0});return}let i=to(o);if(i.length===0){await O(e,{endpoint:n,queue_entries:0});return}let{entries:s,prunedCount:a}=Xt(i,r);if(s.length===0){await Oe(e,[]),await O(e,{endpoint:n,queue_entries:0});return}let c=s.filter(m=>ud(m)).slice(0,Sc);if(c.length===0){a>0&&await Oe(e,s),await O(e,{endpoint:n,queue_entries:s.length});return}let d=new Set(c.map(m=>m.event.event_id)),u=L(),l={"content-type":"application/json"},f=process.env.PM_TELEMETRY_INGEST_KEY?.trim();f&&(l["x-pm-telemetry-key"]=f);try{let m=await fetch(n,{method:"POST",headers:l,body:JSON.stringify({schema_version:Pe,events:c.map(g=>g.event)}),signal:AbortSignal.timeout(kn)});if(!m.ok)throw new Error(`telemetry_flush_http_${m.status}`)}catch(m){let g=await Ed(e,d,u,r),_=m instanceof Error?T(m.message,"redacted"):"telemetry_flush_failed";await O(e,{endpoint:n,queue_entries:g.length,last_attempted_flush_at:u,last_failed_flush_at:u,last_failed_flush_error:_});return}try{let m=await yd(e,d,r);await O(e,{endpoint:n,queue_entries:m.length,last_attempted_flush_at:u,last_successful_flush_at:u,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(m){let g=m instanceof Error?T(m.message,"redacted"):"telemetry_flush_failed",_=await Zt(e).catch(()=>s);await O(e,{endpoint:n,queue_entries:_.length,last_attempted_flush_at:u,last_failed_flush_at:u,last_failed_flush_error:g})}}async function bd(e){let t=Yt(e);await zt(C.dirname(t),{recursive:!0});try{return await zt(t),!0}catch(r){if(typeof r!="object"||r===null||!("code"in r)||r.code!=="EEXIST")throw r}try{let r=await Rn(t);return Date.now()-r.mtimeMs<zn?!1:(await qt(t,{recursive:!0,force:!0}),await zt(t),!0)}catch{return!1}}function Td(e,t){try{return Date.now()-Nn(e).mtimeMs<t}catch{return!1}}function lo(e){try{gc(e,{recursive:!0,force:!0})}catch{}}function fo(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function Sd(e){try{return Pt(e),!0}catch(t){let r=fo(t);if(r==="EEXIST"||r!=="ENOENT")return!1}try{return Pt(C.dirname(e),{recursive:!0}),Pt(e),!0}catch{return!1}}function xd(e){if(Td(Yt(e),zn))return!1;let t=Un(e);try{if(Date.now()-Nn(t).mtimeMs<Lc)return!1;lo(t)}catch(r){if(fo(r)!=="ENOENT")return!1}return Sd(t)}function jt(e){lo(Un(e))}async function Id(e,t,r){let n=await bd(e);if(jt(e),!!n)try{await uo(e,t,r)}finally{try{await qt(Yt(e),{recursive:!0,force:!0})}catch{}}}function er(e,t,r){if(Jc()){let n=In,o=uo(e,t,r);In=Promise.allSettled([n,o]).then(()=>{});return}try{if(!xd(e))return;let o=hc(process.execPath,[Qc()],{detached:!0,stdio:"ignore",cwd:Ht.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[Fn]:"1"}});o.on("error",()=>{jt(e)}),o.unref()}catch{jt(e)}}async function pf(e=J(process.cwd())){if(!Kt())try{if(!(await V(e)).telemetry.enabled)return;let{endpoint:r,retentionDays:n}=await Qt(e);await Id(e,r,n)}catch{}}async function Ad(e){if(Kt()||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=J(process.cwd()),r=await V(t);if(!r.telemetry.enabled)return null;let n=Kn(r.telemetry.capture_level),{installationId:o,endpoint:i,retentionDays:s}=await Qt(t),a=Qn(e.pm_version),c=Xn(e.global),d=x(o,e.pm_root),u=x(o,process.cwd()),l=nd(),f=L(),m={schema_version:Pe,event_id:P.randomUUID(),event_type:"command_start",occurred_at:f,installation_id:o,session_id:Fe,command:e.command,payload:ad({captureLevel:n,context:e,pmVersion:a,sourceContext:c,pmRootHash:d,cwdHash:u,installationId:o})};await Jt(t,m),er(t,i,s);let g=oe(e.command);return{started_at:f,started_at_ms:Date.now(),command:e.command,command_taxonomy:g,pm_version:a,source_context:c.source_context,source_context_source:c.source_context_source,installation_id:o,pm_root_hash:d,cwd_hash:u,endpoint:i,retention_days:s,global_pm_root:t,capture_level:n,otel_traces_endpoint:l??void 0,otel_trace_id:l?P.randomBytes(16).toString("hex"):void 0,otel_span_id:l?P.randomBytes(8).toString("hex"):void 0}}catch{return null}}async function vd(e,t){if(e)try{let r=L(),n=Math.max(0,Date.now()-e.started_at_ms),o=Bt(Nt({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),i=Jn({ok:t.ok,errorCode:o,errorCategory:t.error_category}),s=Wt(t.exit_code,t.ok),a=t.command_resolution??ie({ok:t.ok,errorCode:o,errorCategory:i}),c=t.resolution_stage??"execute",d={schema_version:Pe,event_id:P.randomUUID(),event_type:"command_finish",occurred_at:r,installation_id:e.installation_id,session_id:Fe,command:e.command,payload:cd({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:n,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:s,errorCode:o,errorCategory:i,commandResolution:a,resolutionStage:c})};await Jt(e.global_pm_root,d);let u=id(e,{...t,exit_code:s,error_code:o,error_category:i},r,n);u&&await fd(e.global_pm_root,u),er(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function Cd(e){if(!Kt())try{let t=J(process.cwd()),r=await V(t);if(!r.telemetry.enabled)return;let n=Kn(r.telemetry.capture_level),{installationId:o,endpoint:i,retentionDays:s}=await Qt(t),a=Qn(e.pm_version),c=Xn(e.global),d=x(o,e.pm_root),u=x(o,process.cwd()),l=L(),f=Bt(Nt({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),m=e.error_category??he(f),g=Wt(e.exit_code,!1),_=e.command.trim().length>0?e.command:"<unknown>",y=oe(_),E=e.command_resolution??ie({ok:!1,errorCode:f,errorCategory:m}),I=e.resolution_stage??"unknown",A={schema_version:Pe,event_id:P.randomUUID(),event_type:"command_error",occurred_at:l,installation_id:o,session_id:Fe,command:T(_,"redacted"),payload:dd({captureLevel:n,pmVersion:a,sourceContext:c,command:_,commandTaxonomy:y,commandResolution:E,resolutionStage:I,args:e.args,options:e.options,pmRootHash:d,cwdHash:u,installationId:o,errorCode:f,errorCategory:m,exitCode:g,errorMessage:e.error_message})};await Jt(t,A),er(t,i,s)}catch{}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="febc7f96-1757-5c07-8d99-ed5fce742afa")}catch{}})();export{yo as a,Eo as b,bo as c,To as d,So as e,xo as f,Fd as g,vo as h,Wd as i,Lo as j,fr as k,No as l,Ro as m,Mo as n,eu as o,zo as p,su as q,Uo as r,qo as s,Ho as t,Yo as u,Bo as v,Wo as w,ee as x,Sr as y,Ti as z,Au as A,ku as B,Se as C,Dr as D,ct as E,Vi as F,Ui as G,Ou as H,Mr as I,te as J,ut as K,ft as L,Ce as M,Bu as N,bt as O,Ne as P,Ur as Q,Re as R,Tt as S,St as T,xt as U,It as V,Wr as W,Gr as X,qr as Y,zs as Z,ca as _,ie as $,Ea as aa,wa as ba,ba as ca,Ta as da,Sa as ea,Ia as fa,va as ga,Ca as ha,La as ia,Oa as ja,fn as ka,za as la,Fa as ma,$a as na,Nl as oa,Mt as pa,pn as qa,mn as ra,_n as sa,Ua as ta,ja as ua,hn as va,Ya as wa,Ka as xa,Ja as ya,Za as za,rc as Aa,oc as Ba,ic as Ca,_c as Da,Pe as Ea,On as Fa,$c as Ga,pf as Ha,Ad as Ia,vd as Ja,Cd as Ka};
19
+ //# sourceMappingURL=chunk-NG6OXIBR.js.map
@@ -1,8 +1,8 @@
1
- import{A as a,C as l}from"./chunk-HS7OVAUN.js";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="d5003dd5-f208-5734-9711-dff935d8c851")}catch{}})();var d="-",h=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function S(t){let e=t.trim();if(e==="")return[];let o=(_(e)??e.split(",")).map(i=>i.trim()).filter(Boolean).map(i=>i.toLowerCase());return Array.from(new Set(o)).sort((i,r)=>i.localeCompare(r))}function y(t){if(!Array.isArray(t)||t.length===0)return[];let e=[];for(let n of t)if(typeof n=="string")for(let o of S(n))e.push(o);return Array.from(new Set(e)).sort((n,o)=>n.localeCompare(o))}function w(t){return Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function U(t){return typeof t!="string"?[]:t.split(";").map(e=>e.trim()).filter(Boolean)}function z(t,e,n){let o=t.map(c=>c.trim()).filter(Boolean);for(let c of e??[]){let s=c.trim();if(s.includes(";"))throw new l('Acceptance criteria added with --add-ac cannot contain ";" because semicolons delimit stored criteria',a.USAGE,{code:"acceptance_criteria_semicolon_forbidden",required:"Pass one semicolon-free criterion per --add-ac value",why:"A semicolon inside one criterion would be re-read as multiple criteria",nextSteps:["Split the text into repeated --add-ac values, or replace the semicolon with punctuation that is not the storage delimiter"]});s.length>0&&!o.includes(s)&&o.push(s)}let i=[],r=o;for(let c of n??[]){let s=c.trim();if(s.length!==0){if(!r.includes(s)){i.push(s);continue}r=r.filter(u=>u!==s)}}return{criteria:r,unmatchedRemovals:i}}function G(t,e){let n=w(t);if(!e||e.length===0)return Array.from(new Set(n)).sort((i,r)=>i.localeCompare(r));let o=new Set(n);for(let i of y(e))o.add(i);return Array.from(o).sort((i,r)=>i.localeCompare(r))}function K(t,e){let n=Array.from(new Set(w(t))).sort((i,r)=>i.localeCompare(r));if(!e||e.length===0)return n;let o=new Set(y(e));return o.size===0?n:n.filter(i=>!o.has(i))}function _(t){if(!t.startsWith("["))return null;let e;try{e=JSON.parse(t)}catch{return null}return e.map(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean"?String(o):"").filter(o=>o.length>0)}function m(t){return t.replace(/\r\n/g,`
1
+ import{A as a,C as l}from"./chunk-D4FPS43D.js";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="d5003dd5-f208-5734-9711-dff935d8c851")}catch{}})();var d="-",h=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function S(t){let e=t.trim();if(e==="")return[];let o=(_(e)??e.split(",")).map(i=>i.trim()).filter(Boolean).map(i=>i.toLowerCase());return Array.from(new Set(o)).sort((i,r)=>i.localeCompare(r))}function y(t){if(!Array.isArray(t)||t.length===0)return[];let e=[];for(let n of t)if(typeof n=="string")for(let o of S(n))e.push(o);return Array.from(new Set(e)).sort((n,o)=>n.localeCompare(o))}function w(t){return Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function U(t){return typeof t!="string"?[]:t.split(";").map(e=>e.trim()).filter(Boolean)}function z(t,e,n){let o=t.map(c=>c.trim()).filter(Boolean);for(let c of e??[]){let s=c.trim();if(s.includes(";"))throw new l('Acceptance criteria added with --add-ac cannot contain ";" because semicolons delimit stored criteria',a.USAGE,{code:"acceptance_criteria_semicolon_forbidden",required:"Pass one semicolon-free criterion per --add-ac value",why:"A semicolon inside one criterion would be re-read as multiple criteria",nextSteps:["Split the text into repeated --add-ac values, or replace the semicolon with punctuation that is not the storage delimiter"]});s.length>0&&!o.includes(s)&&o.push(s)}let i=[],r=o;for(let c of n??[]){let s=c.trim();if(s.length!==0){if(!r.includes(s)){i.push(s);continue}r=r.filter(u=>u!==s)}}return{criteria:r,unmatchedRemovals:i}}function G(t,e){let n=w(t);if(!e||e.length===0)return Array.from(new Set(n)).sort((i,r)=>i.localeCompare(r));let o=new Set(n);for(let i of y(e))o.add(i);return Array.from(o).sort((i,r)=>i.localeCompare(r))}function K(t,e){let n=Array.from(new Set(w(t))).sort((i,r)=>i.localeCompare(r));if(!e||e.length===0)return n;let o=new Set(y(e));return o.size===0?n:n.filter(i=>!o.has(i))}function _(t){if(!t.startsWith("["))return null;let e;try{e=JSON.parse(t)}catch{return null}return e.map(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean"?String(o):"").filter(o=>o.length>0)}function m(t){return t.replace(/\r\n/g,`
2
2
  `)}function g(t){let e=m(t).trim();if(!e.startsWith("```"))return t;let n=e.split(`
3
3
  `);return n.length<2||n.at(-1)?.trim()!=="```"?t:n.slice(1,-1).join(`
4
4
  `)}function b(t){let e=[],n="",o=!1,i=!1;for(let r of t){if(i){n+=r,i=!1;continue}if(r==="\\"){n+=r,i=!0;continue}if(r==='"'){o=!o,n+=r;continue}if(r===","&&!o){e.push(n.trim()),n="";continue}n+=r}return n.trim()&&e.push(n.trim()),e}function A(t){let e=t.trim();if(e.startsWith('"')&&e.endsWith('"')){try{let n=JSON.parse(e);if(typeof n=="string")return n}catch{}return e.slice(1,-1).replace(/\\"/g,'"')}return t}function x(t){let e=t.indexOf("="),n=t.indexOf(":"),o=e>0,i=n>0;return o&&i?Math.min(e,n):o?e:i?n:-1}function $(t,e){if((e==="--add"||e==="--add-glob")&&(/[./\\]/.test(t)||/\.[a-z]{1,6}$/i.test(t.trim())))return"For file/doc paths use: path=<file-path>[,scope=project|global]. The scope field is optional and defaults to project (example: path=src/api.ts or path=README.md,scope=project). ";if(e!=="--event")return"";let n=t.toLowerCase(),o=n.includes("recur_")||n.includes("recurrence")?' Recurrence list values must stay in one field and use "|" delimiters (for example recur_by_weekday=mon|wed or recur_by_month_day=1|15).':"",i=n.includes("recur_byweekday")?" Use recur_by_weekday (with underscores) for weekday recurrence filters.":"";return`${o}${i}`}function k(t,e){let n=t.replaceAll(/\s+/g," ").trim(),o=n.length>160?`${n.slice(0,157)}...`:n,i=$(t,e);return`Invalid ${e} value "${o}". Expected key=value entries separated by commas. `+i+`Also accepts markdown-style key/value lines (for example "- path: README.md"). Use ${e} ${d} to read piped stdin input.`}function C(t){let e=g(t).trim();if(e.length===0||!e.includes(`
5
5
  `)&&!e.startsWith("-")&&!e.startsWith("*")&&!e.startsWith("+"))return null;let n={},o,i=m(e).split(`
6
6
  `).map(r=>r.trim()).filter(r=>r.length>0);for(let r of i){let c=r.match(/^(?:[-*+]\s+)?([a-zA-Z0-9_.-]+)\s*(=|:)\s*(.*)$/);if(c){let s=c[1].trim();n[s]=A(c[3].trim()),o=s;continue}if(o&&h.has(o.toLowerCase())){n[o]=`${n[o]}
7
7
  ${r}`;continue}return null}return n}function D(t,e){let n=g(t).trim();if(!n)throw new l(`${e} cannot be empty`,a.USAGE);let o=C(n);if(o)return o;let i={},r,c=b(n);for(let s of c){let u=x(s);if(u>0){let f=s.slice(0,u).trim(),p=A(s.slice(u+1).trim());i[f]=p,r=f;continue}if(r&&h.has(r.toLowerCase())){i[r]=`${i[r]},${s.trim()}`;continue}throw new l(k(t,e),a.USAGE)}return i}var v=/^[A-Za-z]:[\\/]/,T=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function V(t){let e=t.trim();return v.test(e)?!1:T.test(e)}function N(t,e,n){let o=new Set(n.map(r=>r.toLowerCase())),i=Object.keys(t).filter(r=>!o.has(r.toLowerCase()));if(i.length>0)throw new l(`${e} does not recognize key${i.length>1?"s":""} ${i.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${n.join(", ")}.`,a.USAGE);for(let r of Object.keys(t)){let c=r.toLowerCase();if(c!==r){if(Object.hasOwn(t,c))throw new l(`${e} provides key "${r}" more than once after case normalization.`,a.USAGE);t[c]=t[r],delete t[r]}}}async function O(t){if(process.stdin.isTTY===!0)throw new l(`${t} value "${d}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,a.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((e,n)=>{let o="";process.stdin.on("data",i=>{o+=i}),process.stdin.on("end",()=>{e(m(o))}),process.stdin.on("error",i=>{n(i)})})}function P(){let t,e,n=async r=>{if(e&&e!==r)throw new l(`Only one option may use "${d}" stdin token per command invocation. Already used by ${e}.`,a.USAGE);return e=r,t||(t=O(r)),await t};return{resolveValue:async(r,c)=>{if(r!==void 0)return r.trim()!==d?r:await n(c)},resolveList:async(r,c)=>{if(!r)return;let s=r.map((p,E)=>p.trim()===d?E:-1).filter(p=>p>=0);if(s.length===0)return r;if(s.length>1)throw new l(`${c} accepts "${d}" stdin token at most once per command invocation`,a.USAGE);let u=await n(c),f=[...r];return f[s[0]]=u,f}}}function W(t,e){let n=Number(t);if(!Number.isFinite(n))throw new l(`Invalid ${e} value "${t}"`,a.USAGE);return n}function j(t,e){let n=t.trim(),o=Number(n);if(n===""||!Number.isInteger(o)||o<0)throw new l(`Invalid ${e} value "${t}". Expected a non-negative integer.`,a.USAGE);return o}export{S as a,U as b,z as c,G as d,K as e,D as f,V as g,N as h,P as i,W as j,j as k};
8
- //# sourceMappingURL=chunk-R6LSRGPS.js.map
8
+ //# sourceMappingURL=chunk-NYIGHWQY.js.map