@unbrained/pm-cli 2026.11.11 → 2026.11.12

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 (155) hide show
  1. package/.agents/skills/pm-test-audit/SKILL.md +2 -1
  2. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +2 -1
  3. package/.claude-plugin/marketplace.json +1 -1
  4. package/AGENTS.md +2 -2
  5. package/CHANGELOG.md +19 -0
  6. package/CONTRIBUTING.md +1 -1
  7. package/README.md +1 -1
  8. package/dist/cli/register-mutation.js +2 -2
  9. package/dist/cli/register-operations.js +1 -1
  10. package/dist/cli-bundle/bundle-manifest.json +1 -1
  11. package/dist/cli-bundle/chunks/{chunk-FM375BHH.js → chunk-2DUUL53Z.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-5N3JMGXU.js → chunk-2K6GJUW7.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-DIWTFDU7.js → chunk-3DWEBVIK.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-XN2BRWDD.js → chunk-5NGGI7JC.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-NIOOJ3AG.js → chunk-5NY6EQSX.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-XJUYJXHZ.js → chunk-6ESY4Y2B.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-JLQ7O6UV.js → chunk-A7L5IEYV.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-WEAF3OY4.js → chunk-EALO2FPM.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-ZJDYBXMC.js → chunk-FJNHTBJ2.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-GZ52WAY2.js → chunk-FOT5K5OM.js} +36 -36
  21. package/dist/cli-bundle/chunks/{chunk-GOLQYO6M.js → chunk-GDS4DC5A.js} +47 -43
  22. package/dist/cli-bundle/chunks/{chunk-EBAHNZJT.js → chunk-GLPUIQDB.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-SPERPX27.js → chunk-KJL42AN5.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-Z4YEH7VQ.js → chunk-MR3CRLA7.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-QCTA2UFR.js → chunk-OBTU2BHJ.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-ZSL6U53K.js → chunk-OFIXSWJS.js} +2 -2
  27. package/dist/cli-bundle/chunks/chunk-PS2YAPXC.js +9 -0
  28. package/dist/cli-bundle/chunks/{chunk-4RHXGQMK.js → chunk-T4UC3ZKL.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-JESMEJTD.js → chunk-U7MZIX3D.js} +2 -2
  30. package/dist/cli-bundle/chunks/chunk-UTNPDAID.js +31 -0
  31. package/dist/cli-bundle/chunks/{chunk-DV7WBAKQ.js → chunk-UY7Z3ZHQ.js} +2 -2
  32. package/dist/cli-bundle/chunks/{item-revision-LNIHK36Q.js → item-revision-SYJT6TVZ.js} +2 -2
  33. package/dist/cli-bundle/chunks/item-transaction-YXZ27UC6.js +2 -0
  34. package/dist/cli-bundle/chunks/{mutation-admission-WZY22LVH.js → mutation-admission-T57TAVWI.js} +2 -2
  35. package/dist/cli-bundle/chunks/{register-list-query-DYGPLVRL.js → register-list-query-5XZXTPNG.js} +2 -2
  36. package/dist/cli-bundle/chunks/register-mutation-V6WJFL77.js +20 -0
  37. package/dist/cli-bundle/chunks/register-operations-5RAWXY2F.js +2 -0
  38. package/dist/cli-bundle/chunks/{register-setup-G66U2WFV.js → register-setup-HCKCSQWQ.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-M5FZTPFA.js → chunk-5OCUNAQN.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/chunk-AIYJHVKV.js +44 -0
  41. package/dist/cli-bundle/focused-chunks/chunk-BB2GMKRB.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-JYWVRXLD.js → chunk-BHYGUVAU.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-GAXO2UQX.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-VVGXPF4W.js → chunk-GB2N4OM7.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/chunk-IPIFI4NT.js +3 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-KN7RBRRH.js +26 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-3SH3L3DB.js → chunk-LAIN47EJ.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/chunk-RXY6BFRW.js +2 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-NMU3QFAU.js → chunk-SPAEZKVA.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/chunk-TZO6L523.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/{chunk-3A6XMQZJ.js → chunk-VUNX6NBR.js} +53 -53
  52. package/dist/cli-bundle/focused-chunks/{item-revision-B3BIG66B.js → item-revision-PWJNBW3F.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{item-transaction-4JDWOXNB.js → item-transaction-T6HXC3NS.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{mutation-admission-577MXOGD.js → mutation-admission-CLPOLSXZ.js} +2 -2
  55. package/dist/cli-bundle/main.js +2 -2
  56. package/dist/cli-bundle/sdk-authoring.js +1 -1
  57. package/dist/cli-bundle/sdk-contracts.js +2 -2
  58. package/dist/cli-bundle/sdk-core.js +1 -1
  59. package/dist/cli-bundle/sdk-governance.js +1 -1
  60. package/dist/cli-bundle/sdk-merge.js +57 -57
  61. package/dist/cli-bundle/sdk-query.js +1 -1
  62. package/dist/cli-bundle/sdk-runtime.js +1 -1
  63. package/dist/cli-bundle/sdk-testing.js +1 -1
  64. package/dist/cli-bundle/sdk.js +12 -12
  65. package/dist/core/item/parse.d.ts +13 -1
  66. package/dist/core/item/parse.js +4 -4
  67. package/dist/sdk/agent/command-recovery.js +1 -1
  68. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  69. package/dist/sdk/cli-contracts/completeness.js +1 -1
  70. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  71. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  72. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  73. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  74. package/dist/sdk/completion/bash.js +1 -1
  75. package/dist/sdk/completion/fish.js +3 -1
  76. package/dist/sdk/completion/zsh.js +3 -1
  77. package/dist/sdk/docs.d.ts +14 -2
  78. package/dist/sdk/docs.js +1 -1
  79. package/dist/sdk/files.d.ts +14 -2
  80. package/dist/sdk/files.js +1 -1
  81. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  82. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  83. package/dist/sdk/governance/boundary-fixtures.d.ts +25 -0
  84. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  85. package/dist/sdk/governance/defect-recurrence.d.ts +8 -1
  86. package/dist/sdk/governance/defect-recurrence.js +2 -2
  87. package/dist/sdk/guide-topics.js +1 -1
  88. package/dist/sdk/index.d.ts +1 -1
  89. package/dist/sdk/index.js +1 -1
  90. package/dist/sdk/lifecycle/dependency-removal.js +2 -0
  91. package/dist/sdk/lifecycle/start-blockers.d.ts +9 -0
  92. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  93. package/dist/sdk/lifecycle/update.d.ts +10 -4
  94. package/dist/sdk/lifecycle/update.js +2 -2
  95. package/dist/sdk/linked-artifacts.d.ts +73 -3
  96. package/dist/sdk/linked-artifacts.js +2 -2
  97. package/dist/sdk/public-surface.json +1 -1
  98. package/dist/sdk/runtime/actions.js +1 -1
  99. package/dist/sdk/test/command-args.js +1 -1
  100. package/dist/sdk/test/execution.d.ts +15 -3
  101. package/dist/sdk/test/execution.js +2 -2
  102. package/docs/AGENT_GUIDE.md +2 -2
  103. package/docs/AGENT_UX_CONTRACTS.md +7 -1
  104. package/docs/BUILD_AND_RELEASE_ACCEPTANCE.md +1 -1
  105. package/docs/COMMANDS.md +16 -9
  106. package/docs/CORPUS_SHAPES.md +1 -1
  107. package/docs/DEFECT_RECURRENCE.md +20 -1
  108. package/docs/ONBOARDING.md +1 -1
  109. package/docs/README.md +6 -6
  110. package/docs/SDK.md +30 -0
  111. package/docs/SDK_CONTEXT_INTEGRITY.md +2 -0
  112. package/docs/TESTING.md +1 -1
  113. package/docs/generated/FLAG_LEXICON_BUDGETS.md +6 -6
  114. package/marketplace.json +1 -1
  115. package/package.json +8 -1
  116. package/packages/pm-beads/package.json +1 -1
  117. package/packages/pm-calendar/package.json +1 -1
  118. package/packages/pm-command-kit/package.json +1 -1
  119. package/packages/pm-digital-twin/package.json +1 -1
  120. package/packages/pm-governance-audit/package.json +1 -1
  121. package/packages/pm-guide-shell/package.json +1 -1
  122. package/packages/pm-kanban/package.json +1 -1
  123. package/packages/pm-lifecycle-hooks/package.json +1 -1
  124. package/packages/pm-linked-test-adapters/package.json +1 -1
  125. package/packages/pm-search-advanced/package.json +1 -1
  126. package/packages/pm-templates/package.json +1 -1
  127. package/packages/pm-todos/package.json +1 -1
  128. package/packages/pm-vcs/package.json +1 -1
  129. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  130. package/plugins/pm-claude/package.json +1 -1
  131. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  132. package/plugins/pm-codex/package.json +1 -1
  133. package/plugins/pm-codex/plugin.json +1 -1
  134. package/runtime-dependencies.json +1 -1
  135. package/dist/cli-bundle/chunks/chunk-SVVFJPNW.js +0 -9
  136. package/dist/cli-bundle/chunks/chunk-WWW5WHHJ.js +0 -31
  137. package/dist/cli-bundle/chunks/item-transaction-TMUYPSMR.js +0 -2
  138. package/dist/cli-bundle/chunks/register-mutation-MP5JCBAJ.js +0 -20
  139. package/dist/cli-bundle/chunks/register-operations-QEASK3EF.js +0 -2
  140. package/dist/cli-bundle/focused-chunks/chunk-2ZS3I5ZP.js +0 -2
  141. package/dist/cli-bundle/focused-chunks/chunk-33EK522E.js +0 -26
  142. package/dist/cli-bundle/focused-chunks/chunk-6ICHSVEY.js +0 -2
  143. package/dist/cli-bundle/focused-chunks/chunk-6TJXTKZD.js +0 -44
  144. package/dist/cli-bundle/focused-chunks/chunk-DW5S67LO.js +0 -2
  145. package/dist/cli-bundle/focused-chunks/chunk-UCUESVFW.js +0 -2
  146. package/dist/cli-bundle/focused-chunks/chunk-V27M5UQH.js +0 -3
  147. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +0 -167
  148. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +0 -246
  149. package/docs/PR_REVIEW_LOOP.md +0 -96
  150. package/docs/RELEASE_LEDGER_RECONCILIATION.md +0 -148
  151. package/docs/RELEASE_RELIABILITY.md +0 -147
  152. package/docs/RELEASING.md +0 -805
  153. package/docs/performance/corpus-shape-comparison.json +0 -1
  154. package/docs/performance/latest-scale-report.json +0 -1
  155. package/docs/performance/scale-100k-report.json +0 -1
@@ -1,18 +1,18 @@
1
- import{$ as Ti,Ab as Ri,Ai as ht,Ba as lr,Bd as Jt,Ca as ur,Cd as dt,Da as Ci,De as ce,Ea as mr,Ee as ut,Ef as ji,Fa as it,Fd as z,Fe as je,Gb as ki,Gd as Qt,Hc as Di,Hd as Ee,Id as _r,Ii as Sr,Ji as vr,Ka as Gt,Kb as Oi,Lb as $,Mc as Xt,Nd as Zt,Ni as zi,Oa as fr,Oe as $i,Pa as me,Qa as we,Qi as rn,Ra as $e,Ri as Tr,Sa as st,Si as Ir,Ta as te,Ti as Vi,Ud as lt,Vi as yt,Wb as be,X as Si,Y as vi,Ye as Se,Yi as Ue,Ze as wr,Zi as Y,_i as gt,b as nt,ba as ot,c as hi,d as yi,dj as Hi,gb as q,h as gi,hc as ct,ib as Ai,ic as pr,ij as on,je as hr,ke as Li,ki as en,l as wi,lb as Kt,ld as Ni,m as bi,oi as tn,pe as yr,pi as nn,qe as Pi,qf as Fi,qi as pt,ri as Ui,sf as br,t as Ei,ub as xi,ud as fe,ue as gr,vb as E,wf as Er,xb as at,xf as mt,yb as Fe,yd as Mi,yi as _t,zb as S,zf as ft}from"./chunk-PZI6CR24.js";import{A as m,B as Yt,C as p,D as Ii,E as j,G as P,H as C,K as T,L as dr,M as rt,m as ar,u as ee,z as cr}from"./chunk-O4ZLEN4T.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42b217a3-31c0-561a-b7cb-b1a584b2edd5")}catch{}})();var Wd=new Set(["rename-type","rename-field","remap-status",...yi]);function Yd(e,t){if(t&&!Wd.has(e))throw new p(`schema ${e} does not support --dry-run. Preview is supported for rename-type, rename-field, remap-status and workflow-policy actions. Remove --dry-run only when you intend to apply changes.`,m.USAGE,{code:"invalid_argument_value",examples:["pm schema rename-type Spike --to Experiment --dry-run"]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8dd367eb-617e-5645-8f8a-57862f8385f7")}catch{}})();var sn=new WeakSet,Cr=new WeakMap,Bi=new WeakSet;function Ar(e){return Bi.add(e),e}function xr(e){return Bi.has(e)}function wt(e){sn.add(e);for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let r=[...n];Reflect.set(e,t,r),sn.add(r)}return e}function Wi(e,t){return sn.has(e)||t!==void 0&&Cr.get(e)?.has(t)===!0}function Gd(e,t){let n=new Set(t);Cr.set(e,n);for(let r of n){let o=Reflect.get(e,r);if(!Array.isArray(o))continue;let i=[...o];Reflect.set(e,r,i),sn.add(i)}return e}function Yi(e,t){if(xr(e)&&Ar(t),Wi(e))return wt(t);let n=Cr.get(e);return n?Gd(t,n):t}function Fw(e){return Wi(e)?"sdk":"cli"}function qi(e,t){return e==="cli"?`--${t}`:t.replace(/-([a-z])/gu,(n,r)=>r.toUpperCase())}function bt(e){return`Pass unset: ["${e}"] to clear it`}function an(e,t,n=""){return e==="cli"?`--${t} must not be empty${n}`:`${qi("sdk",t)} must not be empty. ${bt(t)}, or omit ${qi("sdk",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]="e35626b8-0818-5b4b-8fc2-57426b51a2d1")}catch{}})();var de="-",Kd=/^[A-Za-z0-9_.-]+$/u,Rr=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 Ki(e,t){if(e.startsWith("```")||e.includes(`
2
- `))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)}function Xi(e){let t=e.trim();if(t==="")return[];let n=(el(t)??t.split(",")).map(r=>r.trim()).filter(Boolean).map(r=>r.toLowerCase());return Array.from(new Set(n)).sort((r,o)=>r.localeCompare(o))}function Ji(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let n of e)if(typeof n=="string")for(let r of Xi(n))t.push(r);return Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r))}function Qi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function Xd(e){return typeof e!="string"?[]:e.split(";").map(t=>t.trim()).filter(Boolean)}function Jd(e,t,n){let r=e.map(s=>s.trim()).filter(Boolean);for(let s of t??[]){let a=s.trim();if(a.includes(";"))throw new p('Acceptance criteria added with --add-ac cannot contain ";" because semicolons delimit stored criteria',m.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"]});a.length>0&&!r.includes(a)&&r.push(a)}let o=[],i=r;for(let s of n??[]){let a=s.trim();if(a.length!==0){if(!i.includes(a)){o.push(a);continue}i=i.filter(c=>c!==a)}}return{criteria:i,unmatchedRemovals:o}}function Qd(e,t){let n=Qi(e);if(!t||t.length===0)return Array.from(new Set(n)).sort((o,i)=>o.localeCompare(i));let r=new Set(n);for(let o of Ji(t))r.add(o);return Array.from(r).sort((o,i)=>o.localeCompare(i))}function Zd(e,t){let n=Array.from(new Set(Qi(e))).sort((o,i)=>o.localeCompare(i));if(!t||t.length===0)return n;let r=new Set(Ji(t));return r.size===0?n:n.filter(o=>!r.has(o))}function el(e){if(!e.startsWith("["))return null;let t;try{t=JSON.parse(e)}catch{return null}return t.map(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):"").filter(n=>n.length>0)}function kr(e){return e.replace(/\r\n/g,`
3
- `)}function Zi(e){let t=kr(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
1
+ import{$ as Ii,Ab as ki,Ai as ht,Ba as lr,Bd as Jt,Ca as ur,Cd as dt,Da as Ai,De as ce,Ea as mr,Ee as ut,Ef as Ui,Fa as it,Fd as z,Fe as je,Gb as Oi,Gd as Qt,Hc as Ni,Hd as Ee,Id as _r,Ii as Sr,Ji as vr,Ka as Gt,Kb as Di,Lb as $,Mc as Xt,Nd as Zt,Ni as Vi,Oa as fr,Oe as Fi,Pa as me,Qa as we,Qi as rn,Ra as $e,Ri as Tr,Sa as st,Si as Ir,Ta as te,Ti as Hi,Ud as lt,Vi as yt,Wb as be,X as vi,Y as Ti,Ye as Se,Yi as Ue,Ze as wr,Zi as Y,_i as gt,b as nt,ba as ot,c as yi,d as gi,dj as qi,gb as q,h as wi,hc as ct,ib as xi,ic as pr,ij as on,je as hr,ke as Pi,ki as en,l as bi,lb as Kt,ld as Mi,m as Ei,oi as tn,pe as yr,pi as nn,qe as $i,qf as ji,qi as pt,ri as zi,sf as br,t as Si,ub as Ri,ud as fe,ue as gr,vb as E,wf as Er,xb as at,xf as mt,yb as Fe,yd as Li,yi as _t,zb as S,zf as ft}from"./chunk-PZI6CR24.js";import{A as m,B as Yt,C as p,D as Ci,E as j,G as P,H as C,K as T,L as dr,M as rt,m as ar,u as ee,z as cr}from"./chunk-O4ZLEN4T.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42b217a3-31c0-561a-b7cb-b1a584b2edd5")}catch{}})();var Xd=new Set(["rename-type","rename-field","remap-status",...gi]);function Jd(e,t){if(t&&!Xd.has(e))throw new p(`schema ${e} does not support --dry-run. Preview is supported for rename-type, rename-field, remap-status and workflow-policy actions. Remove --dry-run only when you intend to apply changes.`,m.USAGE,{code:"invalid_argument_value",examples:["pm schema rename-type Spike --to Experiment --dry-run"]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8dd367eb-617e-5645-8f8a-57862f8385f7")}catch{}})();var sn=new WeakSet,Cr=new WeakMap,Wi=new WeakSet;function Ar(e){return Wi.add(e),e}function xr(e){return Wi.has(e)}function wt(e){sn.add(e);for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let r=[...n];Reflect.set(e,t,r),sn.add(r)}return e}function Yi(e,t){return sn.has(e)||t!==void 0&&Cr.get(e)?.has(t)===!0}function Qd(e,t){let n=new Set(t);Cr.set(e,n);for(let r of n){let o=Reflect.get(e,r);if(!Array.isArray(o))continue;let i=[...o];Reflect.set(e,r,i),sn.add(i)}return e}function Gi(e,t){if(xr(e)&&Ar(t),Yi(e))return wt(t);let n=Cr.get(e);return n?Qd(t,n):t}function Uw(e){return Yi(e)?"sdk":"cli"}function Bi(e,t){return e==="cli"?`--${t}`:t.replace(/-([a-z])/gu,(n,r)=>r.toUpperCase())}function bt(e){return`Pass unset: ["${e}"] to clear it`}function an(e,t,n=""){return e==="cli"?`--${t} must not be empty${n}`:`${Bi("sdk",t)} must not be empty. ${bt(t)}, or omit ${Bi("sdk",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]="f7bc7fa8-c356-5c92-a03d-82275ba47edd")}catch{}})();var de="-",Xi=/^[A-Za-z0-9_.-]+$/u,Rr=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 Ji(e,t){if(e.startsWith("```")||e.includes(`
2
+ `))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)}function Qi(e){let t=e.trim();if(t==="")return[];let n=(rl(t)??t.split(",")).map(r=>r.trim()).filter(Boolean).map(r=>r.toLowerCase());return Array.from(new Set(n)).sort((r,o)=>r.localeCompare(o))}function Zi(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let n of e)if(typeof n=="string")for(let r of Qi(n))t.push(r);return Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r))}function es(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function Zd(e){return typeof e!="string"?[]:e.split(";").map(t=>t.trim()).filter(Boolean)}function el(e,t,n){let r=e.map(s=>s.trim()).filter(Boolean);for(let s of t??[]){let a=s.trim();if(a.includes(";"))throw new p('Acceptance criteria added with --add-ac cannot contain ";" because semicolons delimit stored criteria',m.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"]});a.length>0&&!r.includes(a)&&r.push(a)}let o=[],i=r;for(let s of n??[]){let a=s.trim();if(a.length!==0){if(!i.includes(a)){o.push(a);continue}i=i.filter(c=>c!==a)}}return{criteria:i,unmatchedRemovals:o}}function tl(e,t){let n=es(e);if(!t||t.length===0)return Array.from(new Set(n)).sort((o,i)=>o.localeCompare(i));let r=new Set(n);for(let o of Zi(t))r.add(o);return Array.from(r).sort((o,i)=>o.localeCompare(i))}function nl(e,t){let n=Array.from(new Set(es(e))).sort((o,i)=>o.localeCompare(i));if(!t||t.length===0)return n;let r=new Set(Zi(t));return r.size===0?n:n.filter(o=>!r.has(o))}function rl(e){if(!e.startsWith("["))return null;let t;try{t=JSON.parse(e)}catch{return null}return t.map(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):"").filter(n=>n.length>0)}function kr(e){return e.replace(/\r\n/g,`
3
+ `)}function ts(e){let t=kr(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
4
4
  `);return n.length<2||n.at(-1)?.trim()!=="```"?e:n.slice(1,-1).join(`
5
- `)}function tl(e){let t=[],n="",r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="\\"&&e[o+1]===","){n+=",",o+=1;continue}if(i==="\\"&&e[o+1]!==void 0){n+=`${i}${e[o+1]}`,o+=1;continue}if(i==='"'){r=!r,n+=i;continue}if(i===","&&!r){t.push(n),n="";continue}n+=i}return n.trim()&&t.push(n),t}function es(e){let t=e.trim();if(t.startsWith('"')&&t.endsWith('"')){try{let n=JSON.parse(t);if(typeof n=="string")return n}catch{}return t.slice(1,-1).replace(/\\"/g,'"')}return e}function nl(e){let t=e.indexOf("="),n=e.indexOf(":"),r=t>=0,o=n>=0;return r&&o?Math.min(t,n):r?t:o?n:-1}function rl(e,t){if((t==="--add"||t==="--add-glob")&&(/[./\\]/.test(e)||/\.[a-z]{1,6}$/i.test(e.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(t!=="--event")return"";let n=e.toLowerCase(),r=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).':"",o=n.includes("recur_byweekday")?" Use recur_by_weekday (with underscores) for weekday recurrence filters.":"";return`${r}${o}`}function Gi(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=rl(e,t);return`Invalid ${t} value "${r}". Expected key=value entries separated by commas. `+o+`Also accepts markdown-style key/value lines (for example "- path: README.md"). Use ${t} ${de} to read piped stdin input.`}function ol(e){let t=Zi(e).trim();if(t.length===0||!t.includes(`
6
- `)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=kr(t).split(`
7
- `).map(i=>i.trim()).filter(i=>i.length>0);for(let i of o){let s=i.match(/^(?:[-*+]\s+)?([a-zA-Z0-9_.-]+)\s*(=|:)\s*(.*)$/);if(s){let a=s[1].trim();n[a]=es(s[3].trim()),r=a;continue}if(r&&Rr.has(r.toLowerCase())){n[r]=`${n[r]}
8
- ${i}`;continue}return null}return n}function Or(e,t){let n=Zi(e).trim();if(!n)throw new p(`${t} cannot be empty`,m.USAGE);let r=ol(n);if(r)return r;let o={},i,s=tl(n);for(let a of s){let c=nl(a),d=a.slice(0,Math.max(c,0)).trim();if(d!==""&&i!==void 0&&Rr.has(i.toLowerCase())&&!Kd.test(d)){o[i]=`${o[i]},${a}`;continue}if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new p(Gi(e,t),m.USAGE);let u=es(a.slice(c+1).trim());o[l]=u,i=l;continue}if(i&&Rr.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new p(Gi(e,t),m.USAGE)}return o}var il=/^[A-Za-z]:[\\/]/,sl=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function al(e){let t=e.trim();return il.test(t)?!1:sl.test(t)}function Hw(e,t,n,r){if(!(r||!e.includes(",")))throw new p(`${t} received an ambiguous comma-bearing bare ${n}. Repeat ${t} for multiple values, or quote or escape literal commas in a structured key=<value> entry.`,m.USAGE,{code:"bare_comma_entry_ambiguous",required:`Use one ${t} per bare ${n}, or quote or escape literal commas in a structured key=<value> entry.`})}function cl(e,t,n){let r=new Set(n.map(i=>i.toLowerCase())),o=Object.keys(e).filter(i=>!r.has(i.toLowerCase()));if(o.length>0)throw new p(`${t} does not recognize key${o.length>1?"s":""} ${o.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${n.join(", ")}.`,m.USAGE);for(let i of Object.keys(e)){let s=i.toLowerCase();if(s!==i){if(Object.hasOwn(e,s))throw new p(`${t} provides key "${i}" more than once after case normalization.`,m.USAGE);e[s]=e[i],delete e[i]}}}async function dl(e){if(process.stdin.isTTY===!0)throw new p(`${e} value "${de}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,m.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((t,n)=>{let r="";process.stdin.on("data",o=>{r+=o}),process.stdin.on("end",()=>{t(kr(r))}),process.stdin.on("error",o=>{n(o)})})}var ve=Symbol("all-mutation-stdin-fields"),G=new WeakMap;function qw(e){return xr(e)?e:wt(Et({...e}))}function Et(e){return G.set(e,ve),e}function ll(e,t){let n=G.get(e);return n===ve||G.set(e,new Set([...n??[],...t])),e}function St(e,t){Yi(e,t);let n=G.get(e);return n===void 0||G.set(t,n===ve?n:new Set(n)),t}function Bw(e,t){let n=G.get(e),r=G.get(t);return n===void 0||r===ve?t:n===ve?(G.set(t,n),t):(G.set(t,new Set([...r??[],...n])),t)}function ul(e){return G.get(e)!==ve}function cn(e,t){let n=G.get(e);return n!==ve&&!n?.has(t)}function ml(e){let t;for(let n of e){if(n.resolveToken===!1||n.value===void 0)continue;let r=(Array.isArray(n.value)?n.value:[n.value]).filter(o=>o.trim()===de).length;if(r>1)throw new p(`${n.optionName} accepts "${de}" stdin token at most once per command invocation`,m.USAGE);if(r!==0){if(t!==void 0&&t!==n.optionName)throw new p(`Only one option may use "${de}" stdin token per command invocation. Already used by ${t}.`,m.USAGE);t=n.optionName}}}async function Ww(e,t,n){let r=e,o=[...t,...n];ml(o.map(([a,c])=>({value:r[a],optionName:c,resolveToken:cn(e,a)})));let i=ze(),s={...r};for(let[a,c]of t)s[a]=await i.resolveValue(r[a],c,cn(e,a));for(let[a,c]of n)s[a]=await i.resolveList(r[a],c,cn(e,a));return Et(St(e,s))}function ze(){let e,t,n=async r=>{if(t&&t!==r)throw new p(`Only one option may use "${de}" stdin token per command invocation. Already used by ${t}.`,m.USAGE);return t=r,e||(e=dl(r)),await e};return{resolveValue:async(r,o,i=!0)=>{if(!i)return r;if(r!==void 0)return r.trim()!==de?r:await n(o)},resolveList:async(r,o,i=!0)=>{if(!i)return r;if(!r)return;let s=r.map((d,l)=>d.trim()===de?l:-1).filter(d=>d>=0);if(s.length===0)return r;if(s.length>1)throw new p(`${o} accepts "${de}" stdin token at most once per command invocation`,m.USAGE);let a=await n(o),c=[...r];return c[s[0]]=a,c}}}function fl(e,t){let n=Number(e);if(!Number.isFinite(n))throw new p(`Invalid ${t} value "${e}"`,m.USAGE);return n}function pl(e,t){let n=e.trim(),r=Number(n);if(n===""||!Number.isInteger(r)||r<0)throw new p(`Invalid ${t} value "${e}". Expected a non-negative integer.`,m.USAGE);return 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]="ccb1b39b-3dde-511b-8133-d4747bb6e55e")}catch{}})();function Qw(e){try{return e()}catch(t){throw!(t instanceof p)||t.exitCode!==m.USAGE?t:new p(`${t.message} No changes were made.`,m.USAGE,{...t.context,code:t.code==="linked_test_command_not_executable"?t.code:"invalid_argument_value",reason:"test_option_invalid",changed:!1,required:t.context.required??t.message})}}function _l(e,t){if(e[t]==="'"){let n=e.indexOf("'",t+1);return n<0?void 0:n+1}for(let n=t+1;n<e.length;n+=1){if(e[n]==='"')return n+1;if(e[n]==="\\"){n+=1;continue}if(e[n]==="`"||e.startsWith("$(",n))return}}function hl(e,t){let n=t;for(;n<e.length;){let r=e[n];if(/\s/u.test(r)||";&|".includes(r))return n;if(r==="\\"){n+=2;continue}if(r==="'"||r==='"'){let o=_l(e,n);if(o===void 0)return;n=o;continue}if("<>()`".includes(r))return;n+=1}return n===e.length?n:void 0}function Dr(e,t){let n=t;for(;n<e.length;){if(/\s/u.test(e[n])){n+=1;continue}if(e[n]!=="#")return n;let r=e.indexOf(`
9
- `,n);if(r<0)return e.length;n=r+1}return n}function yl(e,t){let n=Dr(e,t),r=e[n];return r===void 0||!";&|".includes(r)?n:(n+=1,r!==";"&&e[n]===r&&(n+=1),Dr(e,n))}function gl(e){let t=e.trim(),n=Dr(t,0);if(t.length===0)return!1;for(;n<t.length;){if(!/[A-Za-z_]/u.test(t[n]))return!1;let r=n+1;for(;r<t.length&&/[A-Za-z0-9_]/u.test(t[r]);)r+=1;if(t[r]!=="=")return!1;let o=hl(t,r+1);if(o===void 0)return!1;n=yl(t,o)}return!0}function Nr(e){if(!(e===void 0||!gl(e)))throw new p("Linked-test command contains only variable assignments or comments and has no executable command.",m.USAGE,{code:"linked_test_command_not_executable",required:'Supply an actual test command with --add "command=<actual command>" or --add-json. Environment assignments may precede that command.',examples:['pm test <id> --add "command=node --version"'],nextSteps:["Remove any already-stored assignment-only entry with --remove-index, then register the actual test command."]})}function Zw(e){if(Nr(e.command),!(e.pm_context_mode!=="none"||e.workspace_context_mode==="isolated"||e.workspace_context_mode==="snapshot"))throw new p("pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.",m.USAGE,{code:"linked_test_context_invalid",required:"Set workspace_context_mode to isolated or snapshot when pm_context_mode is none.",examples:[q(["test","<id>","--add-json",JSON.stringify({command:e.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}function eb(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}var vt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],wl=new Set(vt);function tb(e){return Ki(e,vt)}function ts(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!wl.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw new p(`${t} provides key "${o}" more than once after case normalization`,m.USAGE);n[s]=i}if(r.length>0)throw new p(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`,m.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new p(`${t} command and cmd must match when both are provided`,m.USAGE);let{cmd:o,...i}=n;return{...i,command:i.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b58016fa-9817-5421-a4a3-78d1b1d22937")}catch{}})();function ns(e){if(!e?.trim())return!1;try{return Nr(e.trim()),!0}catch{return!1}}function bl(e){try{let{command:t,...n}=ts(Or(e,"--add"),"--add");return ns(t)?["--add",e]:["command=<actual command>",...Object.entries(n).map(([r,o])=>`${r}=${JSON.stringify(o)}`)].join(",")}catch{return}}function El(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(vi.has(n)&&n!=="--all")continue;let r=n.split("=",1)[0];if(!Si.has(r)||["--author","--path","--pm-path"].includes(r))return!1;if(!n.includes("=")){let o=e[++t];if(o===void 0||o.startsWith("-"))return!1}}return!0}function Sl(e,t){let n=Ti(t);if(n===void 0)return;let r=Ei(t.slice(n));if((r?.alias??t[n])!==e)return;let o=n+(r?.canonical_argv.length??1),i=t[o],s=t[o+1];if(!(!i||i==="add"||i.startsWith("-"))&&!(!s||s.startsWith("-"))&&El(t.slice(o+2)))return{idIndex:o,value:s}}function vl(e,t){let n=/^[A-Za-z_][A-Za-z0-9_]*=/u.exec(t)?.[0];if(e==="test")return n?["command=","cmd="].includes(n)?bl(t):vt.includes(n.slice(0,-1))?`command=<actual command>,${t}`:void 0:ns(t)?["--add-json",JSON.stringify({command:t})]:"command=<actual command>";if(!(n&&n!=="path="))return["--add",n?t:`path=${JSON.stringify(t)}`]}function Tl(e,t){if(e===void 0||!["files","docs","test"].includes(e))return;let n=Sl(e,t);if(!n)return;let{idIndex:r,value:o}=n,i=t[r],s=vl(e,o);if(s!==void 0)return typeof s=="string"?{itemId:i,value:o,templateArgs:[...t.slice(0,r+1),"--add",s,...t.slice(r+2)]}:{itemId:i,value:o,retryArgs:[...t.slice(0,r+1),...s,...t.slice(r+2)]}}import{readFile as Il}from"node:fs/promises";import rs 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]="7cc00705-c03e-5a18-9bec-af2585939ed8")}catch{}})();function hb(e){if(e!==void 0){if(typeof e!="string")throw new p("--rollback requires a non-empty checkpoint ID string",m.USAGE);return os(e)}}function os(e){let t=e.trim();if(!t)throw new p("--rollback requires a non-empty checkpoint ID",m.USAGE);if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new p("--rollback checkpoint ID must match [a-zA-Z0-9._-]+",m.USAGE);return t}function Cl(e,t){let n=t.replace(/[-:.TZ]/g,"").slice(0,14),r=Math.random().toString(36).slice(2,8);return`${e}-${n}-${r}`}function Al(e,t){return rs.join(e,"checkpoints",t)}function is(e,t,n){return rs.join(Al(e,t),`${n}.json`)}async function xl(e,t,n,r){let o=is(e,t,n),i=`${JSON.stringify(r,null,2)}
10
- `;if(!await xi(o,i)&&await C(o)!==i)throw new p(`Checkpoint ${n} already exists with different contents; use a new checkpoint ID.`,m.CONFLICT);return o}function Rl(e,t){if(!Array.isArray(e.items))throw new p(`Checkpoint ${t} is missing items`,m.GENERIC_FAILURE);return e.items.map(n=>{if(!n||typeof n!="object")throw new p(`Checkpoint ${t} contains an invalid item entry`,m.GENERIC_FAILURE);let r=n;if(typeof r.id!="string"||r.id.trim().length===0)throw new p(`Checkpoint ${t} contains an item entry without ID`,m.GENERIC_FAILURE);if(typeof r.target_updated_at!="string"||r.target_updated_at.trim().length===0)throw new p(`Checkpoint ${t} contains an item entry without target_updated_at`,m.GENERIC_FAILURE);return{id:r.id.trim(),target_updated_at:r.target_updated_at.trim()}})}async function kl(e,t,n,r){let o=os(n),i=is(e,t,o);if(!await j(i))throw new p(`Checkpoint ${o} not found`,m.NOT_FOUND);let s=await Il(i,"utf8"),a;try{a=JSON.parse(s)}catch(l){throw new p(`Checkpoint ${o} contains invalid JSON: ${S(l)}`,m.GENERIC_FAILURE)}if(!a||typeof a!="object")throw new p(`Checkpoint ${o} is invalid`,m.GENERIC_FAILURE);let c=a;if(c.schema_version!==r)throw new p(`Checkpoint ${o} has unsupported schema version. Inspect pm history and use an explicit pm restore only after reviewing later edits.`,m.GENERIC_FAILURE);let d=Rl(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:$(),author:typeof c.author=="string"?c.author:"unknown"}}async function Ol(e,t){let n=[],r=[];for(let o of e)try{let i=await t(o.id,o.target_updated_at);n.push({id:o.id,status:i.skipped?"skipped":"restored",changed_fields:i.changed_fields,warnings:i.warnings}),i.skipped||r.push(o.id)}catch(i){n.push({id:o.id,status:"failed",error:S(i)})}return{rows:n,restored_ids:r,failed_count:n.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]="e23f9ca6-9fa6-566b-9bfb-7cbe6d449a59")}catch{}})();var Eb=[{code:"unknown_lifecycle_action"}];function Dl(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Math.floor(n.length/3);return t.map(o=>({candidate:o,distance:be(n,o.toLowerCase(),r)??Number.POSITIVE_INFINITY})).filter(({distance:o})=>Number.isFinite(o)).sort((o,i)=>o.distance!==i.distance?o.distance-i.distance:o.candidate.localeCompare(i.candidate))[0]?.candidate}function ss(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function Nl(e){let t=e.command_path.trim().replaceAll(/\s+/gu," "),n=e.token.trim(),r=n.length===0?"<empty>":n,o=[...new Set(e.allowed.map(f=>f.trim()))].filter(Boolean).sort((f,_)=>f.localeCompare(_));if(t.length===0||r.length===0||o.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let i=t.split(" "),s=e.trailing_args??[],a=e.display_name??`pm ${t}`,c=e.token_kind??"subcommand",d=e.retry_command?void 0:Dl(r,o),l=ss([...i,r,...s]),u=e.retry_command??(d?ss([...i,d,...s]):void 0);return new p(`Unknown ${a} ${c} "${r}". Allowed: ${o.join(", ")}${e.message_suffix??""}`,e.exit_code??m.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:r,examples:[...u?[u]:[],...e.examples??[],`pm ${t} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:l,allowed_values:o,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4e02447f-3fb0-5f7c-9512-be2b348fd082")}catch{}})();var Te=new Set(ar),dn=Object.freeze({get size(){return Te.size},has(e){return Te.has(e)},entries(){return Te.entries()},keys(){return Te.keys()},values(){return Te.values()},forEach(e,t){Te.forEach(n=>e.call(t,n,n,dn))},[Symbol.iterator](){return Te.values()}});function as(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function cs(e){return typeof e!="string"?null:Di(e)}function Ml(e){try{return structuredClone(e)}catch{return e}}function Ll(e){let t=e.trim(),n=t.indexOf("=");if(n<=0)throw new p(`--field entries must use name=value syntax, received: ${e}`,m.USAGE);let r=t.slice(0,n).trim(),o=t.slice(n+1);return{key:r,value:o}}function Pl(e,t,n){try{let r=JSON.parse(e);if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r}catch{}throw new p(`--field ${t}=... must be valid JSON ${n}`,m.USAGE)}function $l(e,t,n){if(t==="string")return n;if(t==="number"){let r=n.trim();if(r.length===0)throw new p(`--field ${e}=... must be a number`,m.USAGE);let o=Number(r);if(!Number.isFinite(o))throw new p(`--field ${e}=... must be a number`,m.USAGE);return o}if(t==="boolean"){let r=n.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new p(`--field ${e}=... must be one of true|false|1|0|yes|no`,m.USAGE)}return t==="string_array"?n.split(/[\n,|]/u).map(r=>r.trim()).filter(r=>r.length>0):Pl(n,e,t)}function Mr(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=as(r.name),i=cs(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new p(`Extension item field "${o}" is declared with conflicting types: ${s.type}, ${i}`,m.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(o,{name:o,type:i})}return t}function ds(e){if(dn.has(e))throw new p(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...dn].sort((t,n)=>t.localeCompare(n)).join(", ")}.`,m.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function Tt(e){return[...Mr(e).keys()].sort((t,n)=>t.localeCompare(n))}function Fl(e,t,n,r){if(!e||e.length===0)return{};let o=Mr(t),i={};for(let s of e){let{key:a,value:c}=Ll(s),d=o.get(a);if(!d)throw jl(a,o,n,r);ds(d.name),i[d.name]=$l(d.name,d.type,c)}return i}function jl(e,t,n,r){if(dn.has(e)){let s=n?.(e)??{recovery:{provided_fields:[e]},nextSteps:["Core metadata has no generic --field mutation path. Use the owning lifecycle, evidence, or importer API; inspect pm update <id> --help for declared mutation flags."]};return new p(`--field ${e} is a core item field, not an extension field`,m.USAGE,{code:"core_item_field_requires_dedicated_flag",field:e,...s})}let o=r?.(e);if(o!==void 0){let s=o.recovery?.suggested_flags?.[0];return new p(s===void 0?`--field ${e} is a project-schema field, not an extension field`:`--field ${e} is a project-schema field; set it with its declared flag ${s}`,m.USAGE,{code:"project_schema_field_requires_declared_flag",field:e,changed:!1,...o})}let i=[...t.keys()].sort((s,a)=>s.localeCompare(a));return new p(`--field ${e} is not declared by an active extension item-field registration`,m.USAGE,{code:"extension_item_field_unknown",field:e,recovery:{provided_fields:[e]},nextSteps:i.length>0?[`Use one of the declared fields: ${i.join(", ")}`]:["Activate an extension that calls registerItemFields before setting extension fields."]})}function Ul(e,t){return t==="string"?typeof e=="string":t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":t==="array"?Array.isArray(e):t==="string_array"?Array.isArray(e)&&e.every(n=>typeof n=="string"):typeof e=="object"&&e!==null&&!Array.isArray(e)}function zl(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function Vl(e,t,n={}){if(t){Mr(t);for(let r of t.item_fields)for(let o of r.fields){let i=as(o.name);if(!i)continue;ds(i),!(i in e)&&!n.skipDefaultFields?.has(i)&&Object.prototype.hasOwnProperty.call(o,"default")&&(e[i]=Ml(o.default));let s=e[i];if(s===void 0)continue;let a=cs(o.type);if(a&&!Ul(s,a))throw new TypeError(`Item field "${i}" must be of type ${a}`);let c=Array.isArray(o.values)?o.values:void 0;if(!zl(s,c))throw new TypeError(`Item field "${i}" must match one of the configured allowed values`)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a95f85c5-ca4a-5156-8ce4-3dc9070ea468")}catch{}})();var ls=new Set(["item_format"]),us=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),Hl=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_start_blocker_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),ql=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),Bl={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function Wl(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(ls.has(t)||us.has(t)||Hl.has(t)||t==="context")return t}function Yl(e){let t=e.trim().toLowerCase();return Bl[t]??e}function Ab(e,t){let n=Wl(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:ls.has(n)?{routable:!0,flag:"format",value:t}:us.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:ql.has(n)?Yl(t):t}}function Gl(e){return e==="telemetry.enabled"||/^telemetry[-_]tracking$/u.test(e??"")?"global":"project"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cb883ffc-c431-5bf9-a973-931a8a0a940c")}catch{}})();function pe(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function Rb(e,t){let n=pe(t);return!e||!n?null:[...e.assurance_providers??[]].reverse().find(r=>pe(r.definition.id)===n)??null}function Kl(e,t){let n=pe(t);return!e||!n?null:[...e.search_providers].reverse().find(r=>(pe(r.runtime_definition?.name)??pe(r.definition?.name))===n)??null}function Xl(e,t){let n=pe(t);return!e||!n?null:[...e.vector_store_adapters].reverse().find(r=>(pe(r.runtime_definition?.name)??pe(r.definition?.name))===n)??null}function kb(e){return e.runtime_definition??e.definition}import{readFile as Jl}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]="4441095d-0acd-5780-8758-7df94396cb8e")}catch{}})();var Ql=e=>Jl(e,"utf8"),Zl=async e=>await ze().resolveValue("-",e);function Lr(e){return[...new Set(e.split(/[,\r\n]+/).map(t=>t.trim()).filter(t=>t.length>0))]}function eu(e){let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(typeof r=="number"&&Number.isFinite(r))t.push(String(r));else return"";let n=Lr(t.join(`
11
- `));return n.length>0?n.join(","):""}function ms(e){if(e===void 0)return;if(typeof e=="number")return Number.isFinite(e)?String(e):"";if(Array.isArray(e))return eu(e);if(typeof e!="string")return"";let t=Lr(e);return t.length>0?t.join(","):""}async function tu(e,t="--ids",n={}){if(e===void 0)return;let r=e.trim(),o=e;try{if(r==="-")o=await(n.readStdin??Zl)(t);else if(r.startsWith("@")){let s=r.slice(1).trim();if(s.length===0)throw new p(`${t} @path requires a non-empty file path.`,m.USAGE,{code:"bulk_ids_input_missing_path",required:`Pass ${t} @<path>, ${t} -, or inline IDs.`});o=await(n.readFile??Ql)(s)}}catch(s){if(s instanceof p)throw s;let a=s instanceof Error?s.message:String(s);throw new p(`${t} could not read ${r==="-"?"stdin":`"${r.slice(1).trim()}"`}: ${a}`,m.NOT_FOUND,{code:"bulk_ids_input_unreadable",required:`Provide readable newline/comma-delimited IDs via ${t} -, ${t} @<path>, or inline argv text.`,nextSteps:[`Retry with inline IDs: ${t} pm-a1b2,pm-c3d4`,`Or pipe IDs: pm list --id-only | pm update-many ${t} - --dry-run`]})}let i=ms(o);if(i!=="")return i;throw new p(`${t} requires at least one non-empty item ID.`,m.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more comma- or newline-delimited IDs through argv, stdin, or @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]="1dcf0d72-10da-51b6-b9f6-ab47bebcbf64")}catch{}})();function fs(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Pr(e){if(e==="/body"||e.startsWith("/body/"))return"body";if(e==="/metadata"||e.startsWith("/metadata/")||e==="/front_matter"||e.startsWith("/front_matter/")){let n=e.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return n?fs(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?fs(t):"root"}function ln(e,t){return t==="body"?e.body:t==="metadata"?e.metadata:t==="root"?e:e.metadata[t]}function nu(e,t){let n=t?.windowStartIndex??0,r=t?.field;if(e.length===0||n>=e.length)return[];let o=Ui(),i=[];for(let s=0;s<e.length;s+=1){let a=e[s],c=o,d=_t(o,a.patch),l;d.ok?(l=d.document,o=l):l=c;let u=new Set;for(let _ of a.patch)u.add(Pr(_.path)),_.from!==void 0&&u.add(Pr(_.from));let f=[...u].sort((_,y)=>_.localeCompare(y));if(s>=n)if(r!==void 0){if(!u.has(r))continue;let _={field:r,before:ln(c,r),after:ln(l,r)};i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:[r],changes:[_]})}else{let _=f.map(y=>({field:y,before:ln(c,y),after:ln(l,y)}));i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:f,changes:_})}}return i}import ru from"node:fs/promises";import ou 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]="fd3a41f0-4e82-59ab-bb8c-ed796c96a0d7")}catch{}})();function iu(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function su(e,t){return new p(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,m.NOT_FOUND)}async function au(e,t){return await Ii(ou.dirname(e)),await(await ru.open(e,"a")).close(),z({path:e,scope:"project",op:`${t}:history:auto_create`})}async function un(e){return ps({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function ps(e){let t=iu(e.itemIds),n=[],r=[];for(let o of t){let i=te(e.pmRoot,o);if(!await j(i)){if(e.settings.history.missing_stream==="strict_error")throw su(o,e.commandLabel);r.push(...await au(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}import{readFile as cu}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]="80805c6b-9b9a-5dad-b94b-d7dbd365fe5e")}catch{}})();var du=e=>cu(e,"utf8");async function lu(e,t,n=du){if(t!==void 0)throw new p("--body and --body-file are mutually exclusive; provide the body inline with --body or from a file with --body-file, not both.",m.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 r=e.trim();if(r.length===0)throw new p("--body-file requires a file path.",m.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."});if(r==="-")return await ze().resolveValue("-","--body-file");try{return await n(r)}catch(o){let i=o?.code,s=i==="EISDIR",a=i?` (${i})`:"";throw new p(s?`--body-file "${r}" is a directory, not a file. Point it at a readable file.`:`--body-file could not read "${r}"${a}. Check that the file exists and is readable.`,m.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 "${r}"`,"Or pipe the body with --body-file -.","Or pass the body inline with --body <text>."]})}}import uu from"node:crypto";import mn 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]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function hs(e){let t=[],n=!1;for(let r of(e??"").toLowerCase()){let o=r.charCodeAt(0),i=o>=48&&o<=57,s=o>=97&&o<=122;if(!i&&!s){n=t.length>0;continue}n&&(t.push("-"),n=!1),t.push(r)}return t.length===0?"pm-":`${t.join("")}-`}function Ve(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function le(e,t){let n=hs(t),r=Ve(e);return r.startsWith(n)?r:`${n}${r}`}function mu(e){let t=Oi(e);if(t!==void 0)return t;let n="";for(let r=0;r<e;r+=1)n+=uu.randomInt(0,36).toString(36);return n}async function fu(e,t,n){let r=[...new Set(Object.values(n))].flatMap(o=>[mn.join(e,o,`${t}.md`),mn.join(e,o,`${t}.toon`)]);return r.push(mn.join(e,"history",`${t}.jsonl`)),(await Promise.all(r.map(o=>j(o)))).some(Boolean)}var _s=4,ys=12;function pu(e){return typeof e!="number"||!Number.isFinite(e)?_s:Math.min(ys,Math.max(_s,Math.trunc(e)))}async function _u(e,t,n={}){let r=pu(n.tokenLength),o=Math.min(r+6,ys),i=0;for(;r<=o;){for(let s=0;s<32;s+=1){let a=`${hs(t)}${mu(r)}`;if(!await(n.probeExisting===!1?j(mn.join(e,"history",`${a}.jsonl`)):fu(e,a,n.typeToFolder??ee)))return a;i+=1}r+=1}throw new Error(`Unable to generate unique id after ${i} attempts`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0394e0c1-ff68-5553-b022-1e8b6fff04f0")}catch{}})();var hu=new Set(["none","null","undefined"]);function cE(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new p("Config set parent-reference-policy requires --policy with one of: warn, strict_error (alias: strict)",m.USAGE)}function yu(e,t="cli"){let n=t==="sdk";if(typeof e!="string")throw new p(n?`parent must be a string. ${bt("parent")}.`:"--parent must be a string. Use --unset parent to clear this field.",m.USAGE);let r=e.trim();if(r.length===0)throw new p(an(t,"parent",". Use --parent none to unset."),m.USAGE);if(gs(r))throw new p(n?`parent must not be the placeholder "${r}". ${bt("parent")}, or omit parent.`:`--parent must not use placeholder token "${r}". Use --unset parent to clear this field.`,m.USAGE);return r}function gs(e){return hu.has(e.trim().toLowerCase())}function gu(e,t,n="cli"){if(t==="strict_error")throw new p(`Parent item "${e}" was not found. Create it first or ${n==="sdk"?"omit parent":"use --parent none"}.`,m.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${e}`]}}function wu(e,t,n,r="cli"){let o=le(e,n),i=le(t,n);if(o!==i)return;let s=t!==i||e!==o?` (normalized from parent "${t}" and item "${e}")`:"";throw new p(`Parent item "${i}" cannot be the same as item "${o}"${s}. ${r==="sdk"?`${bt("parent")}.`:"Use --unset parent to clear this field."}`,m.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]="a59d5b7f-9764-53c5-a014-1119868be8ea")}catch{}})();var $r={critical:0,high:1,medium:2,low:3,minimal:4},ws=Object.keys($r),bu=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${ws.join(", ")}), case-insensitive`;function fn(e){return new p(`Invalid priority "${e}". Accepted values: ${bu}.`,m.USAGE,{code:"invalid_argument_value",field:"priority",value:e,allowed:["0","1","2","3","4",...ws]})}function Eu(e){if(typeof e=="number"){if(Number.isInteger(e)&&e>=0&&e<=4)return e;throw fn(String(e))}if(typeof e!="string")throw fn(String(e));let t=e.trim();if(t.length===0)throw fn(e);let n=t.toLowerCase();if(Object.prototype.hasOwnProperty.call($r,n))return $r[n];if(/^[0-4]$/.test(t))return Number(t);throw fn(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]="e363ee89-b438-5c8e-bb06-f4d05cc814cc")}catch{}})();function Su(e){let t={...e};for(let[n,r]of Object.entries(t))Array.isArray(r)&&Reflect.set(t,n,[...r]);return Ar(St(e,t))}function vu(e){return wt(Et(St(e,{...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]="6012e77b-7cdd-5496-a668-c9240a811b1a")}catch{}})();var Tu=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,Iu=64;function wE(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new p("Config set sprint-release-format-policy requires --policy with one of: warn, strict_error (alias: strict)",m.USAGE)}function Cu(e,t,n,r="cli"){let o=t.trim();if(o.length===0)throw new p(an(r,e,`. Use --${e} none to unset.`),m.USAGE);if(o.length<=Iu&&Tu.test(o))return{value:o,warnings:[]};let i="Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._/-]* (no spaces).";if(n==="strict_error")throw new p(`Invalid ${r==="sdk"?e:`--${e}`} value "${o}". ${i}`,m.USAGE);return{value:o,warnings:[`validation_warning:${e}_format:${o}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="14e6c7b4-3161-5f82-b797-f06a879d1370")}catch{}})();var bs={open:"open_status",closed:"close_status",canceled:"canceled_status",cancelled:"canceled_status"},Es="all";function IE(e){if(typeof e!="string")return!1;let t=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);return t.length===1&&t[0]===Es}function Au(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=bs[n];return r?t[r]:gr(e,t)}function xu(e){let t=new Set(Object.keys(bs));for(let n of e.definitions){t.add(n.id);for(let r of n.aliases)t.add(r)}return[...t]}function Ru(e,t){let n=e.trim().toLowerCase(),r,o=Number.POSITIVE_INFINITY;for(let i of xu(t)){let s=be(n,i.toLowerCase(),2);s!==null&&s<o&&(r=i,o=s)}return r}function ku(e,t,n){if(typeof e!="string")return;let r=n?.strict===!0,o=n?.flagLabel??"--status",i=e.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(i.length===0)return;if(i.filter(a=>a.trim().toLowerCase()===Es).length>0){if(i.length===1)return;throw new p(`Invalid ${o} value "all". Use it by itself, or omit ${o} to search every status.`,m.USAGE)}let s=[];for(let a of i){let c=Au(a,t);if(c===void 0){if(r){let d=Ru(a,t);throw new p(`Invalid ${o} value "${a}". Use open|closed|canceled or a configured status id${d?`. Did you mean "${d}"?`:"."}`,m.USAGE)}s.push(a);continue}s.push(c)}return[...new Set(s)]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="50f77f3f-b2b0-5ae2-b669-6ed50bbdd530")}catch{}})();var Ou={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 Du(e){if(e!==void 0)return Ou[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]="c628dcf9-d98f-566e-9f93-cc81e737691c")}catch{}})();function vs(e){let t=[],n=new Set;for(let r of e)for(let o of Object.keys(r))n.has(o)||(n.add(o),t.push(o));return t}function Fr(e){return e==null?"":Array.isArray(e)?e.map(t=>Fr(t)).join(";"):typeof e=="object"?JSON.stringify(e):String(e)}function Ss(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Nu(e){if(e.length===0)return"";let t=vs(e),n=[t.map(r=>Ss(r)).join(",")];for(let r of e)n.push(t.map(o=>Ss(Fr(r[o]))).join(","));return n.join(`
12
- `)}function Mu(e){if(e.length===0)return"";let t=vs(e),n=e.map(s=>t.map(a=>Fr(s[a]))),r=t.map((s,a)=>Math.max(s.length,...n.map(c=>c[a].length))),o=(s,a)=>s.padEnd(r[a]),i=[t.map((s,a)=>o(s,a)).join(" | ")];i.push(r.map(s=>"-".repeat(s)).join("-+-"));for(let s of n)i.push(s.map((a,c)=>o(a,c)).join(" | "));return i.join(`
13
- `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b84fee06-5bbd-57f9-9643-f283d6c87afa")}catch{}})();function Lu(e,t="--limit"){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||n<0)throw new p(`${t} must be a non-negative number`,m.USAGE);return Math.floor(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]="158d5065-075c-5355-a65c-f3edc9c5f1f0")}catch{}})();var Pu=new Map(ot.map(e=>[e.toLowerCase(),e])),$u=/^[A-Za-z][A-Za-z0-9_-]*$/;function Ts(e,t){if(!$u.test(e))throw new Error(`${t} "${e}" is not a valid identifier. Use a single letter-led token of letters, digits, hyphen, or underscore with no spaces or punctuation (e.g. "Spike" or "code-review").`)}function jr(e){return Pu.get(e.trim().toLowerCase())}function As(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Fu(e){return e.replace(/[\\"`$]/g,t=>`\\${t}`)}function xs(e){let t=new Map;for(let n of e){let r=n.trim();if(r.length===0)continue;let o=r.toLowerCase();t.has(o)||t.set(o,r)}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function ME(e){let t=(e.name??"").trim();if(t.length===0)throw new Error("Type name must not be empty.");Ts(t,"Type name");let n=jr(t);if(n)throw new Error(`Cannot redefine built-in item type "${n}". Built-in types are reserved: ${ot.join(", ")}.`);let r=e.description?.trim(),o=e.defaultStatus?.trim(),i=e.folder?.trim(),s=i&&i.length>0?mr(i):void 0,a=xs(e.aliases??[]);for(let c of a){Ts(c,"Alias");let d=jr(c);if(d)throw new Error(`Alias "${c}" collides with built-in item type "${d}". Built-in types are reserved: ${ot.join(", ")}.`)}return{name:t,description:r&&r.length>0?r:void 0,defaultStatus:o&&o.length>0?o:void 0,folder:s,aliases:a}}function LE(e,t){let n=e.name.toLowerCase(),r=new Map;for(let i of t.definitions){if(typeof i.name!="string")continue;let s=i.name.trim();if(!(s.length===0||s.toLowerCase()===n)){r.set(s.toLowerCase(),s);for(let a of As(i.aliases))a.trim().length>0&&r.set(a.trim().toLowerCase(),s)}}let o=r.get(n);if(o)throw new Error(`Type name "${e.name}" collides with an alias of existing item type "${o}".`);for(let i of e.aliases){let s=r.get(i.toLowerCase());if(s)throw new Error(`Alias "${i}" already maps to existing item type "${s}".`)}}function Is(e,t){return typeof t=="string"&&t.trim().length>0?mr(t).toLowerCase():Ci(e).toLowerCase()}function PE(e,t,n){let r=e.name.toLowerCase(),o=Is(e.name,e.folder),i=a=>{throw new Error(`Item type "${e.name}" would store items in folder "${o}", which already belongs to existing item type "${a}". Pass a distinct --folder to keep their storage separate.`)};for(let a of t.definitions){if(typeof a.name!="string")continue;let c=a.name.trim();c.length===0||c.toLowerCase()===r||Is(c,a.folder)===o&&i(c)}let s=n?.get(o);s!==void 0&&s.toLowerCase()!==r&&i(s)}function $E(e){if(e==null||e.trim().length===0)return{definitions:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/types.json contains invalid JSON.")}return{definitions:ju(t)}}function ju(e){let t=Uu(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;typeof o.name!="string"||o.name.trim().length===0||n.push(o)}return n}function Uu(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){let n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function FE(e,t){let n=t.name.toLowerCase(),r=e.definitions.slice(),o=r.findIndex(c=>typeof c.name=="string"&&c.name.trim().toLowerCase()===n),i=o>=0?r[o]:void 0,s=xs([...As(i?.aliases),...t.aliases]),a={...i,name:t.name};return t.folder!==void 0&&(a.folder=t.folder),s.length>0?a.aliases=s:a.aliases!==void 0&&delete a.aliases,Cs(a,"description",t.description),Cs(a,"default_status",t.defaultStatus),o>=0?r[o]=a:r.push(a),r.sort((c,d)=>c.name.localeCompare(d.name)),{file:{definitions:r},definition:a,replaced:o>=0,...i&&typeof i.name=="string"?{previousName:i.name}:{}}}function jE(e,t){let n=(t??"").trim();if(n.length===0)throw new Error("Type name must not be empty.");let r=jr(n);if(r)throw new Error(`Cannot remove built-in item type "${r}". Built-in types are reserved: ${ot.join(", ")}.`);let o=n.toLowerCase(),i=e.definitions.slice(),s=i.findIndex(c=>typeof c.name=="string"&&c.name.trim().toLowerCase()===o);if(s<0)return{file:{definitions:i},removed:!1};let[a]=i.splice(s,1);return{file:{definitions:i},removed:!0,definition:a}}function Cs(e,t,n){let r=e;n!==void 0&&(r[t]=n)}function UE(e){return`${JSON.stringify({definitions:e.definitions},null,2)}
14
- `}function zu(e,t){let n=e.trim().length>0?e.trim():e,r=t?.trim()||".agents/pm/schema/types.json";return`To register a custom type, run: pm schema add-type "${Fu(n)}" (writes ${r}).`}function Vu(e,t,n){return`Invalid type value "${e}". Allowed: ${t.join(", ")}. ${zu(e,n)}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4b79bd02-51ae-5c46-be4c-2f41dd8c9486")}catch{}})();function Rs(e,t){return nt(e,t)}function Hu(e,t,n){let r={};for(let o of t.command_to_fields.get(n)??[]){let i=hr(e,o);i!==void 0&&(r[o.metadata_key]=Li(o,i))}return r}function qu(e,t){for(let[n,r]of Object.entries(t)){let o=e[n];if(Array.isArray(r)){if(Array.isArray(o)){let i=o.map(s=>String(s));if(!r.map(s=>String(s)).every(s=>i.includes(s)))return!1;continue}if(!Rs(o,r[r.length-1]))return!1;continue}if(!Rs(o,r))return!1}return!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77a7b77a-907c-541d-ac55-e06174dbbf11")}catch{}})();function ks(e){return typeof e=="string"?e.trim().toLowerCase():""}function pn(e,t){let n=lt(e);return n.length===0?"":t?.alias_to_id?.get(n)??n}function Bu(e){let t=Array.isArray(e?.type_workflows)?e.type_workflows:[],n=new Map;for(let r of t){let o=ks(r?.type);if(o.length===0||!Array.isArray(r?.allowed_transitions))continue;let i=r.allowed_transitions,s=n.get(o)??{pairs:[],denyAll:!1};i.length===0&&(s.denyAll=!0);for(let a of i){if(!Array.isArray(a)||a.length!==2)continue;let c=lt(a[0]),d=lt(a[1]);c.length===0||d.length===0||s.pairs.some(l=>l[0]===c&&l[1]===d)||s.pairs.push([c,d])}n.set(o,s)}return[...n.entries()].filter(([,r])=>r.pairs.length>0||r.denyAll).map(([r,o])=>({type:r,allowed_transitions:o.pairs})).sort((r,o)=>r.type.localeCompare(o.type))}function Wu(e){let t=ks(e.typeName),n=e.typeWorkflows.find(i=>i.type===t);if(!n)return{allowed:!0,hasRule:!1,allowedTransitions:[]};let r=pn(e.fromStatus,e.statusRegistry),o=pn(e.toStatus,e.statusRegistry);return r.length>0&&r===o?{allowed:!0,hasRule:!0,allowedTransitions:n.allowed_transitions}:{allowed:n.allowed_transitions.some(i=>{let s=pn(i[0],e.statusRegistry),a=pn(i[1],e.statusRegistry);return s===r&&a===o}),hasRule:!0,allowedTransitions:n.allowed_transitions}}function Yu(e){return e.length===0?"(no transitions allowed)":e.map(t=>`${t[0]} -> ${t[1]}`).join(", ")}import{spawnSync as Ds}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]="7889f11f-36f9-5384-8429-58d951c342da")}catch{}})();var Gu="PM_DISABLE_OLLAMA_AUTO_DEFAULTS",Ku="PM_OLLAMA_MODEL",Xu="http://localhost:11434",Ju="qwen3-embedding:0.6b",Qu=".agents/pm/search/lancedb/",Zu=1500,em=2500,tm=/qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i,nm=/embed|embedding/i,ne=E;function rm(){let e=ne(process.env[Gu]);if(!e)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}function Os(e){return e.some(t=>ne(t)!==null)}function om(e){let t=ne(e);return!!(t&&t.toLowerCase()!=="ollama")}function im(e){let t=ne(e);return!!(t&&t.toLowerCase()!=="lancedb")}function sm(e){return om(e.search?.provider)||im(e.vector_store?.adapter)||Os([e.providers?.openai?.base_url,e.providers?.openai?.model,e.providers?.openai?.api_key])?!0:Os([e.vector_store?.qdrant?.url,e.vector_store?.qdrant?.api_key])}function am(){let e=Ds("ollama",["--version"],{encoding:"utf8",timeout:Zu});return e.error?!1:e.status===0}function cm(e){let t=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)return null;let n=t.map(r=>r.split(/\s+/)[0]?.trim()).filter(r=>!!(r&&r.length>0)).filter(r=>r.toUpperCase()!=="NAME");return n.length===0?null:n.find(r=>tm.test(r))||(n.find(r=>nm.test(r))??null)}function dm(e){let t=ne(e.providers?.ollama?.model);if(t)return t;let n=ne(process.env[Ku]);if(n)return n;let r=Ds("ollama",["list"],{encoding:"utf8",timeout:em});if(!r.error&&r.status===0){let o=cm(typeof r.stdout=="string"?r.stdout:"");if(o)return o}return null}function lm(e){return{baseUrl:ne(e.providers?.ollama?.base_url)===null,model:ne(e.providers?.ollama?.model)===null,lancedbPath:ne(e.vector_store?.lancedb?.path)===null,embeddingModel:ne(e.search?.embedding_model)===null}}function um(e){return e.baseUrl||e.model||e.lancedbPath||e.embeddingModel}function mm(e,t,n){if(!t.baseUrl&&!t.model)return;let r=e.providers??={},o=r.ollama??={};t.baseUrl&&(o.base_url=Xu),t.model&&(o.model=n)}function fm(e,t){if(!t.lancedbPath)return;let n=e.vector_store??={},r=n.lancedb??={};r.path=Qu}function pm(e,t,n){if(!t.embeddingModel)return;let r=e.search??={};r.embedding_model=n}function He(e){let t={settings:e,auto_ollama_defaults_applied:!1};if(rm()||sm(e))return t;let n=lm(e);if(!um(n)||n.model&&!am())return t;let r=structuredClone(e),o=dm(r);return o?(mm(r,n,o),fm(r,n),pm(r,n,o),{settings:r,auto_ollama_defaults_applied:!0}):{...t,auto_ollama_defaults_skipped_reason:"no_installed_embedding_model",auto_ollama_defaults_remediation:`Run ollama pull ${Ju} or configure providers.ollama.model explicitly (and search.embedding_model if you need an override).`}}import{spawn as _m}from"node:child_process";import{mkdirSync as Ns,rmSync as Ls,statSync as hm}from"node:fs";import _n 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]="9ecff496-8afa-5cfc-9178-2be8bd403978")}catch{}})();var Ps="reindex",ym="search/pending-refresh.json",gm="search/pending-refresh.gate.lock",wm=3e4,bm="PM_SEARCH_REFRESH_INLINE",$s="PM_SEARCH_REFRESH_CHILD",Em=3e4;function Ms(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Sm(){if(Ms(process.env[bm])||Ms(process.env[$s]))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 Fs(e){return _n.join(e,ym)}function js(e){return _n.join(e,gm)}function vm(e){let t=js(e);try{if(Date.now()-hm(t).mtimeMs<wm)return!1;Ls(t,{recursive:!0,force:!0})}catch{}try{return Ns(_n.dirname(t),{recursive:!0}),Ns(t),!0}catch{return!1}}function Tm(e){try{Ls(js(e),{recursive:!0,force:!0})}catch{}}async function Us(e,t,n){for(let r=0;r<50;r+=1){if(vm(e))try{return await t()}finally{Tm(e)}await Im(20)}return n}function Im(e){return new Promise(t=>{setTimeout(t,e)})}async function zr(e){let t=await C(Fs(e));if(!t||t.trim().length===0)return[];try{let n=JSON.parse(t);return Array.isArray(n.ids)?n.ids.filter(r=>typeof r=="string"&&r.length>0):[]}catch{return[]}}async function zs(e,t){await T(Fs(e),`${JSON.stringify({ids:t})}
15
- `)}async function Ur(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim().length>0);if(n.length===0)return;let r=async()=>{let o=await zr(e),i=[...new Set([...o,...n])].sort((s,a)=>s.localeCompare(a));await zs(e,i)};await Us(e,async()=>(await r(),!0),!1)||await r()}async function Cm(e){return Us(e,async()=>{let t=await zr(e);return t.length>0&&await zs(e,[]),t},[])}function Am(){return _n.join(ct(import.meta.url,["../../.."]),"dist","cli","search-refresh.js")}function Vr(e){try{let t=_m(process.execPath,[Am()],{detached:!0,stdio:"ignore",env:{...process.env,PM_PATH:e,[$s]:"1"}});t.on("error",()=>{}),t.unref()}catch{}}function xm(e){setTimeout(()=>Vr(e),Em)}async function Vs(e,t){await Ur(e,t),Vr(e)}async function aS(e,t,n=xm){let r=[],o=[];if(!await j(e))return{processed:o,rounds:0,warnings:r};let i;try{let l=await Ue(e),u=l.warnings.find(f=>f.startsWith("settings_read_"));if(u)return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${u}`]};i=He(l.settings).settings}catch(l){return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${S(l)}`]}}let s=null;try{s=await Se(e,Ps,i.locks.ttl_seconds,mt(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:r};let a=0,c=!1,d=!1;try{for(;;){let l=await Cm(e);if(l.length===0)break;a+=1;try{let u=await t(e,l);if(r.push(...u.warnings),u.warnings.some(f=>f.startsWith("search_semantic_refresh_skipped:settings_read_failed:"))){await Ur(e,l),c=!0,d=!0;break}o.push(...u.refreshed)}catch(u){r.push(`search_background_refresh_failed:${S(u)}`),await Ur(e,l),c=!0;break}}}finally{await s?.()}return d&&n(e),(c?[]:await zr(e)).length>0&&Vr(e),{processed:[...new Set(o)].sort((l,u)=>l.localeCompare(u)),rounds:a,warnings: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]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function It(e,t=!1){let n=e[0];if(n?.op!=="history_compact_baseline")return 0;let r=n.context?.history_compaction,o=typeof r=="object"&&r!==null&&"version_offset"in r?r.version_offset:void 0;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&Number.isSafeInteger(o+e.length))return o;if(t)return null;throw new p("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",m.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="02424d1c-c29f-5a13-b711-d50267170b9f")}catch{}})();function Rm(e,t){let n=-1;return e.forEach((r,o)=>{let i=Date.parse(r.ts);if(!Number.isFinite(i))throw new p(`History for this item contains invalid timestamp at entry ${o+1}.`,m.GENERIC_FAILURE);i<=t&&(n=o)}),n}function km(e,t){let n=e[0]?.ts??null,r=e.at(-1)?.ts??null,o={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:n,last_timestamp:r}};return r!==null&&(o.examples=[r],t!==null&&(o.examples.unshift(String(t+1),String(t+e.length)),o.valid_range.first_version=t+1,o.valid_range.last_version=t+e.length)),{guidance:o,lastTimestamp:r}}function Om(e,t){let n={};if(t instanceof Error&&t.message.trim().length>0&&(n.reason=t.message.trim()),typeof t!="object"||t===null)return n;let r=t;if(typeof r.index=="number"&&Number.isInteger(r.index)&&r.index>=0&&(n.patchIndex=r.index),typeof r.operation=="object"&&r.operation!==null){let o=r.operation;Object.assign(n,Object.fromEntries(["op","path","from"].flatMap(i=>{let s=o[i];return typeof s=="string"?[[i,s]]:[]})))}if(n.patchIndex!==void 0){let o=e[n.patchIndex];o&&(n.op??=o.op,n.path??=o.path,n.from??=o.from)}return n}function Hs(e,t,n={}){let r=e.trim(),o=n.errorSubject??"history",i=o==="restore"?"Restore":"History",{guidance:s,lastTimestamp:a}=km(t,It(t,!0));if(!r)throw new p(`Missing ${o} target. Use a timestamp or version number.`,m.USAGE,s);if(/^\d+$/.test(r)){let l=It(t),u=Number(r);if(u>=1&&u<=l)throw new p(`History version ${u} was pruned by compaction.`,m.USAGE,{...s,code:"history_version_pruned"});if(!Number.isSafeInteger(u)||u<1||u>l+t.length)throw new p(`${i} version must be between ${l+1} and ${l+t.length} for this item.`,m.USAGE,s);return{kind:"version",raw:r,historyIndex:u-l-1}}let c=Date.parse(r);if(!Number.isFinite(c))throw new p(`Invalid ${o} target "${e}". Use a positive version number or ISO timestamp.`,m.USAGE,s);let d=Rm(t,c);if(d<0||n.allowFutureTimestamp!==!0&&c>Date.parse(a))throw new p(o==="restore"?`No history entries exist at or before timestamp ${r}.`:`No history entry exists at timestamp ${r}.`,m.USAGE,s);return{kind:"timestamp",raw:r,historyIndex:d}}function Hr(e,t,n,r){let o=_t(e,t);if(o.ok)return o.document;let i=Om(t,o.error),s=[`history_op=${r}`,i.patchIndex===void 0?null:`patch_index=${i.patchIndex}`,i.op?`op=${i.op}`:null,i.path?`path=${i.path}`:null,i.from?`from=${i.from}`:null].filter(a=>a!==null);throw new p(`Failed to apply history patch at entry ${n} (${s.join(", ")}). ${i.reason??String(o.error)}`,m.GENERIC_FAILURE)}function qs(e,t){let n=e[0];if(n&&n.op!=="create"&&n.op!=="history_compact_baseline"){let s=_t(pt,n.patch);if(!s.ok||typeof s.document.metadata.id!="string")throw new p("History starts without a reconstructable item baseline.",m.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}let r=e.slice(0,t+1),o=ht([...r]),i=structuredClone(pt);for(let s=0;s<=t;s+=1){let a=e[s];if(!a)throw new p(`History target entry ${s+1} does not exist.`,m.USAGE);i=Hr(i,a.patch,s+1,a.op)}if(!o.ok)throw new p(`History cannot be replayed: ${o.errors.join(", ")}.`,m.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:o.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return i}function hS(e,t){if(Object.keys(e.metadata).length>0){if(typeof e.metadata.id!="string"||!Array.isArray(e.metadata.tags))throw new p("History has no complete item baseline for this target.",m.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return e}throw new p(`History target ${t.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,m.USAGE)}import Bs from"node:fs/promises";import Ct from"node:path";import{isUtf8 as Dm}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="697f1dbe-8315-5901-ab11-e0c5211dbdbf")}catch{}})();var Nm=1048576,Mm=4194304;async function Ws(e,t){let n=Ct.dirname(e);for(;n!==Ct.parse(e).root;){let o=await Bs.stat(n).catch(i=>{if(P(i))return null;throw i});if(o!==null){if(!o.isDirectory())throw new p("Workflow policy storage ancestor must be a directory.",m.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}n=Ct.dirname(n)}let r=await Bs.open(e,"r").catch(o=>{if(P(o))return null;throw o});if(r===null)return null;try{let o=(await r.stat()).size,i=Buffer.alloc(Math.min(t,o)+1),s=0;for(;s<i.length;){let a=await r.read(i,s,i.length-s,s);if(a.bytesRead===0)break;s+=a.bytesRead}if(s===i.length||!Dm(i.subarray(0,s)))throw new p("Workflow policy input exceeds its byte bound or is not valid UTF-8.",m.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return i.toString("utf8",0,s)}finally{await r.close()}}function Lm(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let t;try{t=JSON.parse(e)}catch{throw new p("schema/policies.json must contain valid JSON.",m.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return gi(t)}async function Pm(e){return Lm(await Ws(Ct.join(e,"schema","policies.json"),Nm))}async function $m(e,t){let n=await Ws(te(e,t),Mm);if(n===null)return[];let r;try{if(r=n.split(/\r?\n/).filter(o=>o.trim()).map(o=>JSON.parse(o)),!ht(r).ok)throw new Error("invalid chain")}catch{throw new p("Approval evidence requires a valid item history chain.",m.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${t} --verify before recording or using an approval.`]})}return r.flatMap(o=>{let i=o.context?.workflow_approval;if(o.op!=="policy_approve"||o.record_hash_version!==1||typeof o.record_hash!="string"||typeof i!="object"||i===null)return[];let s=i;return typeof s.policy_fingerprint!="string"||typeof s.content_fingerprint!="string"?[]:[{policy_fingerprint:s.policy_fingerprint,content_fingerprint:s.content_fingerprint,author:o.author}]})}async function Fm(e,t,n){let r=n.before?.status!==n.after?.status&&t.policies.some(s=>s.rule.kind==="approval"&&wi(s,n)),o=n.before?.id??n.after?.id,i=r&&typeof o=="string"?await $m(e,o):[];return bi(t,{...n,approvals:i})}async function qr(e){let t=await Pm(e.pmRoot),n=await Fm(e.pmRoot,t,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(n.allowed)return n;let r=n.decisions.filter(f=>!f.satisfied&&f.effect==="refuse"),o=[],i="";if(!e.dryRun)try{let f=await Sr({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:n.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms});o.push({path:"history/_workspace.jsonl",op:"policy_refused",record_hash:f.entry.record_hash}),i=" Audit appended to tracker-relative history/_workspace.jsonl; retain it with the workspace changes. Each refused attempt records its own audit event."}catch(f){let _=new p("Workflow policy refusal could not be recorded in workspace history.",m.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw _.cause=f,_}let s=r.slice(0,3).map(f=>({policy_id:f.policy_id,rule:f.rule,description:t.policies.find(_=>_.id===f.policy_id).description,missing_fields:f.missing_fields})),a=[...new Set(s.flatMap(f=>f.missing_fields))],c=s.map(f=>`${f.policy_id} (${f.rule})`).join(", "),d=r.length>3?` and ${r.length-3} more`:"",l=e.after?.metadata.id??e.before.metadata.id,u=a.map(f=>{if(e.before===null)return`Supply ${f} in the original ${e.operation} request, then retry; the item was not created.`;let _=lr("update",f);return _===void 0?`Supply ${f} using its declared SDK or package mutation contract, then retry.`:q(["update",l,ur("update",_),`<${f}>`,"--pm-path",Ct.resolve(e.pmRoot)])});throw new p(`Workflow policy refused ${e.operation}: ${c}${d}.${a.length?` Missing: ${a.join(", ")}.`:""}${i}`,m.CONFLICT,{code:"workflow_policy_refused",side_effects:o,reason:s.map(f=>f.policy_id).join(","),policy_violations:s,policy_violation_count:r.length,required:a.length?`Supply missing fields: ${a.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:s.map(f=>f.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:a},nextSteps:[...u,...new Set(r.slice(0,3).filter(f=>f.missing_fields.length===0).map(f=>f.remediation)),...r.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as jm}from"node:async_hooks";import{channel as Um}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var Br=new jm,Wr=Um("@unbrained/pm-cli/item-metadata-enumeration/v1");function hn(e){Wr.publish(e)}async function NS(e){let t={enumeration_calls:0,metadata_rows:0},n=r=>{Br.getStore()?.includes(t)&&(t.enumeration_calls+=1,t.metadata_rows+=r)};Wr.subscribe(n);try{return{result:await Br.run([...Br.getStore()??[],t],e),work:{...t}}}finally{Wr.unsubscribe(n)}}import{AsyncLocalStorage as Ys}from"node:async_hooks";import{realpathSync as zm}from"node:fs";import Gr 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]="0d72cf82-14ea-573b-a36e-0077c82c0c1d")}catch{}})();var Yr=new Ys;function HS(e,t){return Yr.run([...Yr.getStore()??[],{...e,pmRoot:Gr.resolve(e.pmRoot)}],t)}var Vm=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),Hm=globalThis,At=Hm[Vm]??=new Ys;function qe(e){let t=Gr.resolve(e);try{return zm.native(t)}catch{return t}}function qS(){return{entries:new Map}}function BS(e,t){return At.run([...At.getStore()??[],e],t)}function WS(e,t,n){let r=qe(t);if(e.pmRoot!==void 0&&e.pmRoot!==r)throw new p("An expected-revision scope is already bound to another tracker.",m.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});e.pmRoot=r;for(let{id:o,itemHash:i}of n){let s=e.entries.get(o);if(s!==void 0&&s.declared!==i)throw new p(`Item ${o} has two different expected revisions.`,m.USAGE,{code:"expected_revision_duplicate",item_id:o,required:"Declare at most one expected revision per item."});e.entries.set(o,s??{declared:i,expected:i,checked:!1,committed:!1})}}function YS(e){let t=[...e.entries.entries()];return{checked:t.filter(([,n])=>n.checked).map(([n])=>n),unchecked:t.filter(([,n])=>!n.checked).map(([n])=>n)}}function Kr(e,t){let n=At.getStore()??[];if(n.length===0)return[];let r=qe(e),o=new Set(t.filter(i=>typeof i=="string"));return[...new Set(n.flatMap(i=>i.pmRoot===r?[...o].flatMap(s=>i.entries.get(s)??[]):[]))]}function GS(e){let t=At.getStore()??[];if(t.length===0)return[];let n=qe(e),r=new Map;for(let o of t)if(o.pmRoot===n)for(let[i,s]of o.entries){if(s.expected!==s.declared)return;r.set(i,(r.get(i)??new Set).add(s.expected))}if(![...r.values()].some(o=>o.size>1))return[...r].map(([o,i])=>`${o}=${[...i][0]}`)}function KS(e){let t=qe(e);return(At.getStore()??[]).some(n=>n.pmRoot===t&&n.entries.size>0)}function qm(e,t,n){let r=Kr(e,[n,t.metadata.id]);r.length>0&&Xs(r,n,en(t),!1,e)}function XS(e,t,n){let r=Kr(e,[t]);r.length>0&&Xs(r,t,hi(n),!0,e)}var Bm="revision_changed",Wm="document_unreadable";function Ym(e,t,n={}){let r=[...n.scopeArgs??[]],o=[...n.outputArgs??["--json"]],i=q([...r,"get",e,...o]),s=q([...r,"history",e,"--limit","5",...o]);return{required:t?`Recover ${e} without --expect-hash (${q([...r,"restore",e,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${e} (${i} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[q([...r,"get",e,"--fields","item_hash",...o]),s],nextSteps:[i,s]}}var Gm=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),Km=globalThis,Xr=Km[Gm]??=new WeakMap,Xm=8;function Gs(e){for(let t of Ks(e)){let n=Xr.get(t);if(n!==void 0)return n}}function*Ks(e){let t=e;for(let n=0;n<Xm&&typeof t=="object"&&t!==null;n+=1){yield t;try{t=t.cause}catch{return}}}function Xs(e,t,n,r,o){for(let i of e)if(i.checked=!0,!(!r&&i.expected===n))throw ef(o,new p(`Item ${t} is no longer at the expected revision ${i.expected.slice(0,12)}${r?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${i.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,m.CONFLICT,{code:"item_revision_conflict",item_id:t,expected_revision:i.expected,current_revision:n,reason:r?Wm:Bm,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...Ym(t,r)}))}function JS(e,t){let n=Gs(e);return n===void 0||n===qe(t)}var Jm=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),Qm=globalThis,Jr=Qm[Jm]??=new WeakSet;function Zm(e){for(let t of Ks(e))if(Jr.has(t))return!0;return!1}function QS(e){return Jr.add(e),e}function ZS(e,t){let n=Gs(e);return n!==void 0&&Xr.set(t,n),Zm(e)&&Jr.add(t),t}function ef(e,t){return Xr.set(t,qe(e)),t}function Qr(e,t,n=t.metadata.id){qm(e,t,n);for(let r of Zr(e,[n,t.metadata.id]))r.validate(t)}function Zr(e,t){let n=Gr.resolve(e);return(Yr.getStore()??[]).filter(r=>r.pmRoot===n&&t.includes(r.id))}function eo(e,t,n=t.metadata.id,r=[],o){let i=Kr(e,[n,t.metadata.id,...r]);if(i.length>0){let s=o??en(t);for(let a of i)a.expected=s,a.committed=!0}for(let s of Zr(e,[n,t.metadata.id,...r]))s.committed?.(t)}function Js(e,t){return Object.assign({},...Zr(e,t).map(n=>n.historyContext))}import Ie from"node:fs/promises";import Zs from"node:path";import{randomUUID as tf}from"node:crypto";import{createRequire as nf}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]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var rf="metadata-query-index.sqlite",xt="5",to;function Rt(){return to!==void 0||(to=ji(process.versions.node,nf(import.meta.url))),to}function Qs(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function Be(e){return Zs.join(e,"runtime",rf)}function of(e){e.exec(`
5
+ `)}function ns(e){let t=[],n="",r=0,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i];if(s==="\\"&&e[i+1]===","){n+=",",i+=1;continue}if(s==="\\"&&e[i+1]!==void 0){n+=`${s}${e[i+1]}`,i+=1;continue}if(s==='"'){o=!o,n+=s;continue}if(s===","&&!o){t.push({text:n,raw:e.slice(r,i)}),n="",r=i+1;continue}n+=s}return n.trim()&&t.push({text:n,raw:e.slice(r)}),t}function ol(e){return ns(e).map(t=>t.text)}function Bw(e){return ns(e.trim()).map(({text:t,raw:n})=>{let r=rs(t),o=t.slice(0,Math.max(r,0)).trim();return Xi.test(o)?{text:t,raw:n,key:o,value:Or(t.slice(r+1).trim())}:{text:t,raw:n}})}function Or(e){let t=e.trim();if(t.startsWith('"')&&t.endsWith('"')){try{let n=JSON.parse(t);if(typeof n=="string")return n}catch{}return t.slice(1,-1).replace(/\\"/g,'"')}return e}function rs(e){let t=e.indexOf("="),n=e.indexOf(":"),r=t>=0,o=n>=0;return r&&o?Math.min(t,n):r?t:o?n:-1}function il(e,t){if((t==="--add"||t==="--add-glob")&&(/[./\\]/.test(e)||/\.[a-z]{1,6}$/i.test(e.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(t!=="--event")return"";let n=e.toLowerCase(),r=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).':"",o=n.includes("recur_byweekday")?" Use recur_by_weekday (with underscores) for weekday recurrence filters.":"";return`${r}${o}`}function Ki(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=il(e,t);return`Invalid ${t} value "${r}". Expected key=value entries separated by commas. `+o+`Also accepts markdown-style key/value lines (for example "- path: README.md"). Use ${t} ${de} to read piped stdin input.`}function os(e,t,n,r){let o=Object.keys(e).find(i=>i.toLowerCase()===t.toLowerCase());if(o!==void 0)throw new p(`${r} sets key "${t}" more than once in one entry, so the later value would silently replace the earlier one.`,m.USAGE,{code:"structured_entry_key_repeated",flag:r,value:n,required:`Give each key once per ${r} entry. Repeat ${r} for another entry; if the repeated key belongs to prose, quote that value or pass it through its standalone flag.`,why:"A structured entry keeps one value per key, so accepting a repeat would store data the author did not intend without any refusal.",details:{repeated_key:t,first_key:o}})}function sl(e,t){let n=ts(e).trim();if(n.length===0||!n.includes(`
6
+ `)&&!n.startsWith("-")&&!n.startsWith("*")&&!n.startsWith("+"))return null;let r={},o,i=kr(n).split(`
7
+ `).map(s=>s.trim()).filter(s=>s.length>0);for(let s of i){let a=s.match(/^(?:[-*+]\s+)?([a-zA-Z0-9_.-]+)\s*(=|:)\s*(.*)$/);if(a){let c=a[1].trim();os(r,c,e,t),r[c]=Or(a[3].trim()),o=c;continue}if(o&&Rr.has(o.toLowerCase())){r[o]=`${r[o]}
8
+ ${s}`;continue}return null}return r}function Dr(e,t){let n=ts(e).trim();if(!n)throw new p(`${t} cannot be empty`,m.USAGE);let r=sl(n,t);if(r)return r;let o={},i,s=ol(n);for(let a of s){let c=rs(a),d=a.slice(0,Math.max(c,0)).trim();if(d!==""&&i!==void 0&&Rr.has(i.toLowerCase())&&!Xi.test(d)){o[i]=`${o[i]},${a}`;continue}if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new p(Ki(e,t),m.USAGE);let u=Or(a.slice(c+1).trim());os(o,l,e,t),o[l]=u,i=l;continue}if(i&&Rr.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new p(Ki(e,t),m.USAGE)}return o}var al=/^[A-Za-z]:[\\/]/,cl=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function dl(e){let t=e.trim();return al.test(t)?!1:cl.test(t)}function Ww(e,t,n,r){if(!(r||!e.includes(",")))throw new p(`${t} received an ambiguous comma-bearing bare ${n}. Repeat ${t} for multiple values, or quote or escape literal commas in a structured key=<value> entry.`,m.USAGE,{code:"bare_comma_entry_ambiguous",required:`Use one ${t} per bare ${n}, or quote or escape literal commas in a structured key=<value> entry.`})}function ll(e,t,n){let r=new Set(n.map(i=>i.toLowerCase())),o=Object.keys(e).filter(i=>!r.has(i.toLowerCase()));if(o.length>0)throw new p(`${t} does not recognize key${o.length>1?"s":""} ${o.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${n.join(", ")}.`,m.USAGE);for(let i of Object.keys(e)){let s=i.toLowerCase();if(s!==i){if(Object.hasOwn(e,s))throw new p(`${t} provides key "${i}" more than once after case normalization.`,m.USAGE);e[s]=e[i],delete e[i]}}}async function ul(e){if(process.stdin.isTTY===!0)throw new p(`${e} value "${de}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,m.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((t,n)=>{let r="";process.stdin.on("data",o=>{r+=o}),process.stdin.on("end",()=>{t(kr(r))}),process.stdin.on("error",o=>{n(o)})})}var ve=Symbol("all-mutation-stdin-fields"),G=new WeakMap;function Yw(e){return xr(e)?e:wt(Et({...e}))}function Et(e){return G.set(e,ve),e}function ml(e,t){let n=G.get(e);return n===ve||G.set(e,new Set([...n??[],...t])),e}function St(e,t){Gi(e,t);let n=G.get(e);return n===void 0||G.set(t,n===ve?n:new Set(n)),t}function Gw(e,t){let n=G.get(e),r=G.get(t);return n===void 0||r===ve?t:n===ve?(G.set(t,n),t):(G.set(t,new Set([...r??[],...n])),t)}function fl(e){return G.get(e)!==ve}function cn(e,t){let n=G.get(e);return n!==ve&&!n?.has(t)}function pl(e){let t;for(let n of e){if(n.resolveToken===!1||n.value===void 0)continue;let r=(Array.isArray(n.value)?n.value:[n.value]).filter(o=>o.trim()===de).length;if(r>1)throw new p(`${n.optionName} accepts "${de}" stdin token at most once per command invocation`,m.USAGE);if(r!==0){if(t!==void 0&&t!==n.optionName)throw new p(`Only one option may use "${de}" stdin token per command invocation. Already used by ${t}.`,m.USAGE);t=n.optionName}}}async function Kw(e,t,n){let r=e,o=[...t,...n];pl(o.map(([a,c])=>({value:r[a],optionName:c,resolveToken:cn(e,a)})));let i=ze(),s={...r};for(let[a,c]of t)s[a]=await i.resolveValue(r[a],c,cn(e,a));for(let[a,c]of n)s[a]=await i.resolveList(r[a],c,cn(e,a));return Et(St(e,s))}function ze(){let e,t,n=async r=>{if(t&&t!==r)throw new p(`Only one option may use "${de}" stdin token per command invocation. Already used by ${t}.`,m.USAGE);return t=r,e||(e=ul(r)),await e};return{resolveValue:async(r,o,i=!0)=>{if(!i)return r;if(r!==void 0)return r.trim()!==de?r:await n(o)},resolveList:async(r,o,i=!0)=>{if(!i)return r;if(!r)return;let s=r.map((d,l)=>d.trim()===de?l:-1).filter(d=>d>=0);if(s.length===0)return r;if(s.length>1)throw new p(`${o} accepts "${de}" stdin token at most once per command invocation`,m.USAGE);let a=await n(o),c=[...r];return c[s[0]]=a,c}}}function _l(e,t){let n=Number(e);if(!Number.isFinite(n))throw new p(`Invalid ${t} value "${e}"`,m.USAGE);return n}function hl(e,t){let n=e.trim(),r=Number(n);if(n===""||!Number.isInteger(r)||r<0)throw new p(`Invalid ${t} value "${e}". Expected a non-negative integer.`,m.USAGE);return 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]="ccb1b39b-3dde-511b-8133-d4747bb6e55e")}catch{}})();function tb(e){try{return e()}catch(t){throw!(t instanceof p)||t.exitCode!==m.USAGE?t:new p(`${t.message} No changes were made.`,m.USAGE,{...t.context,code:t.code==="linked_test_command_not_executable"?t.code:"invalid_argument_value",reason:"test_option_invalid",changed:!1,required:t.context.required??t.message})}}function yl(e,t){if(e[t]==="'"){let n=e.indexOf("'",t+1);return n<0?void 0:n+1}for(let n=t+1;n<e.length;n+=1){if(e[n]==='"')return n+1;if(e[n]==="\\"){n+=1;continue}if(e[n]==="`"||e.startsWith("$(",n))return}}function gl(e,t){let n=t;for(;n<e.length;){let r=e[n];if(/\s/u.test(r)||";&|".includes(r))return n;if(r==="\\"){n+=2;continue}if(r==="'"||r==='"'){let o=yl(e,n);if(o===void 0)return;n=o;continue}if("<>()`".includes(r))return;n+=1}return n===e.length?n:void 0}function Nr(e,t){let n=t;for(;n<e.length;){if(/\s/u.test(e[n])){n+=1;continue}if(e[n]!=="#")return n;let r=e.indexOf(`
9
+ `,n);if(r<0)return e.length;n=r+1}return n}function wl(e,t){let n=Nr(e,t),r=e[n];return r===void 0||!";&|".includes(r)?n:(n+=1,r!==";"&&e[n]===r&&(n+=1),Nr(e,n))}function bl(e){let t=e.trim(),n=Nr(t,0);if(t.length===0)return!1;for(;n<t.length;){if(!/[A-Za-z_]/u.test(t[n]))return!1;let r=n+1;for(;r<t.length&&/[A-Za-z0-9_]/u.test(t[r]);)r+=1;if(t[r]!=="=")return!1;let o=gl(t,r+1);if(o===void 0)return!1;n=wl(t,o)}return!0}function Mr(e){if(!(e===void 0||!bl(e)))throw new p("Linked-test command contains only variable assignments or comments and has no executable command.",m.USAGE,{code:"linked_test_command_not_executable",required:'Supply an actual test command with --add "command=<actual command>" or --add-json. Environment assignments may precede that command.',examples:['pm test <id> --add "command=node --version"'],nextSteps:["Remove any already-stored assignment-only entry with --remove-index, then register the actual test command."]})}function nb(e){if(Mr(e.command),!(e.pm_context_mode!=="none"||e.workspace_context_mode==="isolated"||e.workspace_context_mode==="snapshot"))throw new p("pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.",m.USAGE,{code:"linked_test_context_invalid",required:"Set workspace_context_mode to isolated or snapshot when pm_context_mode is none.",examples:[q(["test","<id>","--add-json",JSON.stringify({command:e.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}function rb(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}var vt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],El=new Set(vt);function ob(e){return Ji(e,vt)}function is(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!El.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw new p(`${t} provides key "${o}" more than once after case normalization`,m.USAGE);n[s]=i}if(r.length>0)throw new p(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`,m.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new p(`${t} command and cmd must match when both are provided`,m.USAGE);let{cmd:o,...i}=n;return{...i,command:i.command??o}}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b58016fa-9817-5421-a4a3-78d1b1d22937")}catch{}})();function ss(e){if(!e?.trim())return!1;try{return Mr(e.trim()),!0}catch{return!1}}function Sl(e){try{let{command:t,...n}=is(Dr(e,"--add"),"--add");return ss(t)?["--add",e]:["command=<actual command>",...Object.entries(n).map(([r,o])=>`${r}=${JSON.stringify(o)}`)].join(",")}catch{return}}function vl(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Ti.has(n)&&n!=="--all")continue;let r=n.split("=",1)[0];if(!vi.has(r)||["--author","--path","--pm-path"].includes(r))return!1;if(!n.includes("=")){let o=e[++t];if(o===void 0||o.startsWith("-"))return!1}}return!0}function Tl(e,t){let n=Ii(t);if(n===void 0)return;let r=Si(t.slice(n));if((r?.alias??t[n])!==e)return;let o=n+(r?.canonical_argv.length??1),i=t[o],s=t[o+1];if(!(!i||i==="add"||i.startsWith("-"))&&!(!s||s.startsWith("-"))&&vl(t.slice(o+2)))return{idIndex:o,value:s}}function Il(e,t){let n=/^[A-Za-z_][A-Za-z0-9_]*=/u.exec(t)?.[0];if(e==="test")return n?["command=","cmd="].includes(n)?Sl(t):vt.includes(n.slice(0,-1))?`command=<actual command>,${t}`:void 0:ss(t)?["--add-json",JSON.stringify({command:t})]:"command=<actual command>";if(!(n&&n!=="path="))return["--add",n?t:`path=${JSON.stringify(t)}`]}function Cl(e,t){if(e===void 0||!["files","docs","test"].includes(e))return;let n=Tl(e,t);if(!n)return;let{idIndex:r,value:o}=n,i=t[r],s=Il(e,o);if(s!==void 0)return typeof s=="string"?{itemId:i,value:o,templateArgs:[...t.slice(0,r+1),"--add",s,...t.slice(r+2)]}:{itemId:i,value:o,retryArgs:[...t.slice(0,r+1),...s,...t.slice(r+2)]}}import{readFile as Al}from"node:fs/promises";import as 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]="7cc00705-c03e-5a18-9bec-af2585939ed8")}catch{}})();function wb(e){if(e!==void 0){if(typeof e!="string")throw new p("--rollback requires a non-empty checkpoint ID string",m.USAGE);return cs(e)}}function cs(e){let t=e.trim();if(!t)throw new p("--rollback requires a non-empty checkpoint ID",m.USAGE);if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new p("--rollback checkpoint ID must match [a-zA-Z0-9._-]+",m.USAGE);return t}function xl(e,t){let n=t.replace(/[-:.TZ]/g,"").slice(0,14),r=Math.random().toString(36).slice(2,8);return`${e}-${n}-${r}`}function Rl(e,t){return as.join(e,"checkpoints",t)}function ds(e,t,n){return as.join(Rl(e,t),`${n}.json`)}async function kl(e,t,n,r){let o=ds(e,t,n),i=`${JSON.stringify(r,null,2)}
10
+ `;if(!await Ri(o,i)&&await C(o)!==i)throw new p(`Checkpoint ${n} already exists with different contents; use a new checkpoint ID.`,m.CONFLICT);return o}function Ol(e,t){if(!Array.isArray(e.items))throw new p(`Checkpoint ${t} is missing items`,m.GENERIC_FAILURE);return e.items.map(n=>{if(!n||typeof n!="object")throw new p(`Checkpoint ${t} contains an invalid item entry`,m.GENERIC_FAILURE);let r=n;if(typeof r.id!="string"||r.id.trim().length===0)throw new p(`Checkpoint ${t} contains an item entry without ID`,m.GENERIC_FAILURE);if(typeof r.target_updated_at!="string"||r.target_updated_at.trim().length===0)throw new p(`Checkpoint ${t} contains an item entry without target_updated_at`,m.GENERIC_FAILURE);return{id:r.id.trim(),target_updated_at:r.target_updated_at.trim()}})}async function Dl(e,t,n,r){let o=cs(n),i=ds(e,t,o);if(!await j(i))throw new p(`Checkpoint ${o} not found`,m.NOT_FOUND);let s=await Al(i,"utf8"),a;try{a=JSON.parse(s)}catch(l){throw new p(`Checkpoint ${o} contains invalid JSON: ${S(l)}`,m.GENERIC_FAILURE)}if(!a||typeof a!="object")throw new p(`Checkpoint ${o} is invalid`,m.GENERIC_FAILURE);let c=a;if(c.schema_version!==r)throw new p(`Checkpoint ${o} has unsupported schema version. Inspect pm history and use an explicit pm restore only after reviewing later edits.`,m.GENERIC_FAILURE);let d=Ol(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:$(),author:typeof c.author=="string"?c.author:"unknown"}}async function Nl(e,t){let n=[],r=[];for(let o of e)try{let i=await t(o.id,o.target_updated_at);n.push({id:o.id,status:i.skipped?"skipped":"restored",changed_fields:i.changed_fields,warnings:i.warnings}),i.skipped||r.push(o.id)}catch(i){n.push({id:o.id,status:"failed",error:S(i)})}return{rows:n,restored_ids:r,failed_count:n.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]="e23f9ca6-9fa6-566b-9bfb-7cbe6d449a59")}catch{}})();var Tb=[{code:"unknown_lifecycle_action"}];function Ml(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Math.floor(n.length/3);return t.map(o=>({candidate:o,distance:be(n,o.toLowerCase(),r)??Number.POSITIVE_INFINITY})).filter(({distance:o})=>Number.isFinite(o)).sort((o,i)=>o.distance!==i.distance?o.distance-i.distance:o.candidate.localeCompare(i.candidate))[0]?.candidate}function ls(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function Ll(e){let t=e.command_path.trim().replaceAll(/\s+/gu," "),n=e.token.trim(),r=n.length===0?"<empty>":n,o=[...new Set(e.allowed.map(f=>f.trim()))].filter(Boolean).sort((f,_)=>f.localeCompare(_));if(t.length===0||r.length===0||o.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let i=t.split(" "),s=e.trailing_args??[],a=e.display_name??`pm ${t}`,c=e.token_kind??"subcommand",d=e.retry_command?void 0:Ml(r,o),l=ls([...i,r,...s]),u=e.retry_command??(d?ls([...i,d,...s]):void 0);return new p(`Unknown ${a} ${c} "${r}". Allowed: ${o.join(", ")}${e.message_suffix??""}`,e.exit_code??m.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:r,examples:[...u?[u]:[],...e.examples??[],`pm ${t} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:l,allowed_values:o,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4e02447f-3fb0-5f7c-9512-be2b348fd082")}catch{}})();var Te=new Set(ar),dn=Object.freeze({get size(){return Te.size},has(e){return Te.has(e)},entries(){return Te.entries()},keys(){return Te.keys()},values(){return Te.values()},forEach(e,t){Te.forEach(n=>e.call(t,n,n,dn))},[Symbol.iterator](){return Te.values()}});function us(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ms(e){return typeof e!="string"?null:Ni(e)}function Pl(e){try{return structuredClone(e)}catch{return e}}function $l(e){let t=e.trim(),n=t.indexOf("=");if(n<=0)throw new p(`--field entries must use name=value syntax, received: ${e}`,m.USAGE);let r=t.slice(0,n).trim(),o=t.slice(n+1);return{key:r,value:o}}function Fl(e,t,n){try{let r=JSON.parse(e);if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r}catch{}throw new p(`--field ${t}=... must be valid JSON ${n}`,m.USAGE)}function jl(e,t,n){if(t==="string")return n;if(t==="number"){let r=n.trim();if(r.length===0)throw new p(`--field ${e}=... must be a number`,m.USAGE);let o=Number(r);if(!Number.isFinite(o))throw new p(`--field ${e}=... must be a number`,m.USAGE);return o}if(t==="boolean"){let r=n.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new p(`--field ${e}=... must be one of true|false|1|0|yes|no`,m.USAGE)}return t==="string_array"?n.split(/[\n,|]/u).map(r=>r.trim()).filter(r=>r.length>0):Fl(n,e,t)}function Lr(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=us(r.name),i=ms(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new p(`Extension item field "${o}" is declared with conflicting types: ${s.type}, ${i}`,m.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(o,{name:o,type:i})}return t}function fs(e){if(dn.has(e))throw new p(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...dn].sort((t,n)=>t.localeCompare(n)).join(", ")}.`,m.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function Tt(e){return[...Lr(e).keys()].sort((t,n)=>t.localeCompare(n))}function Ul(e,t,n,r){if(!e||e.length===0)return{};let o=Lr(t),i={};for(let s of e){let{key:a,value:c}=$l(s),d=o.get(a);if(!d)throw zl(a,o,n,r);fs(d.name),i[d.name]=jl(d.name,d.type,c)}return i}function zl(e,t,n,r){if(dn.has(e)){let s=n?.(e)??{recovery:{provided_fields:[e]},nextSteps:["Core metadata has no generic --field mutation path. Use the owning lifecycle, evidence, or importer API; inspect pm update <id> --help for declared mutation flags."]};return new p(`--field ${e} is a core item field, not an extension field`,m.USAGE,{code:"core_item_field_requires_dedicated_flag",field:e,...s})}let o=r?.(e);if(o!==void 0){let s=o.recovery?.suggested_flags?.[0];return new p(s===void 0?`--field ${e} is a project-schema field, not an extension field`:`--field ${e} is a project-schema field; set it with its declared flag ${s}`,m.USAGE,{code:"project_schema_field_requires_declared_flag",field:e,changed:!1,...o})}let i=[...t.keys()].sort((s,a)=>s.localeCompare(a));return new p(`--field ${e} is not declared by an active extension item-field registration`,m.USAGE,{code:"extension_item_field_unknown",field:e,recovery:{provided_fields:[e]},nextSteps:i.length>0?[`Use one of the declared fields: ${i.join(", ")}`]:["Activate an extension that calls registerItemFields before setting extension fields."]})}function Vl(e,t){return t==="string"?typeof e=="string":t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":t==="array"?Array.isArray(e):t==="string_array"?Array.isArray(e)&&e.every(n=>typeof n=="string"):typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hl(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function ql(e,t,n={}){if(t){Lr(t);for(let r of t.item_fields)for(let o of r.fields){let i=us(o.name);if(!i)continue;fs(i),!(i in e)&&!n.skipDefaultFields?.has(i)&&Object.prototype.hasOwnProperty.call(o,"default")&&(e[i]=Pl(o.default));let s=e[i];if(s===void 0)continue;let a=ms(o.type);if(a&&!Vl(s,a))throw new TypeError(`Item field "${i}" must be of type ${a}`);let c=Array.isArray(o.values)?o.values:void 0;if(!Hl(s,c))throw new TypeError(`Item field "${i}" must match one of the configured allowed values`)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a95f85c5-ca4a-5156-8ce4-3dc9070ea468")}catch{}})();var ps=new Set(["item_format"]),_s=new Set(["definition_of_done","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"]),Bl=new Set(["history_missing_stream_policy","sprint_release_format_policy","parent_reference_policy","metadata_validation_profile","governance_preset","governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default","governance_require_close_reason","governance_create_default_type","governance_workflow_enforcement","governance_start_blocker_enforcement","governance_parent_reference_policy","governance_metadata_validation_profile","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking","agent_identity_vocabulary"]),Wl=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),Yl={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function Gl(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(ps.has(t)||_s.has(t)||Bl.has(t)||t==="context")return t}function Kl(e){let t=e.trim().toLowerCase();return Yl[t]??e}function kb(e,t){let n=Gl(e);return n===void 0?{routable:!1,reason:`Unknown config key "${e}" cannot route a positional value.`}:n==="context"?{routable:!1,reason:"Config set context does not accept a positional value. Use --default-depth, --activity-limit, --stale-threshold-days, or --section-<name> flags."}:ps.has(n)?{routable:!0,flag:"format",value:t}:_s.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:Wl.has(n)?Kl(t):t}}function Xl(e){return e==="telemetry.enabled"||/^telemetry[-_]tracking$/u.test(e??"")?"global":"project"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cb883ffc-c431-5bf9-a973-931a8a0a940c")}catch{}})();function pe(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function Db(e,t){let n=pe(t);return!e||!n?null:[...e.assurance_providers??[]].reverse().find(r=>pe(r.definition.id)===n)??null}function Jl(e,t){let n=pe(t);return!e||!n?null:[...e.search_providers].reverse().find(r=>(pe(r.runtime_definition?.name)??pe(r.definition?.name))===n)??null}function Ql(e,t){let n=pe(t);return!e||!n?null:[...e.vector_store_adapters].reverse().find(r=>(pe(r.runtime_definition?.name)??pe(r.definition?.name))===n)??null}function Nb(e){return e.runtime_definition??e.definition}import{readFile as Zl}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]="4441095d-0acd-5780-8758-7df94396cb8e")}catch{}})();var eu=e=>Zl(e,"utf8"),tu=async e=>await ze().resolveValue("-",e);function Pr(e){return[...new Set(e.split(/[,\r\n]+/).map(t=>t.trim()).filter(t=>t.length>0))]}function nu(e){let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(typeof r=="number"&&Number.isFinite(r))t.push(String(r));else return"";let n=Pr(t.join(`
11
+ `));return n.length>0?n.join(","):""}function hs(e){if(e===void 0)return;if(typeof e=="number")return Number.isFinite(e)?String(e):"";if(Array.isArray(e))return nu(e);if(typeof e!="string")return"";let t=Pr(e);return t.length>0?t.join(","):""}async function ru(e,t="--ids",n={}){if(e===void 0)return;let r=e.trim(),o=e;try{if(r==="-")o=await(n.readStdin??tu)(t);else if(r.startsWith("@")){let s=r.slice(1).trim();if(s.length===0)throw new p(`${t} @path requires a non-empty file path.`,m.USAGE,{code:"bulk_ids_input_missing_path",required:`Pass ${t} @<path>, ${t} -, or inline IDs.`});o=await(n.readFile??eu)(s)}}catch(s){if(s instanceof p)throw s;let a=s instanceof Error?s.message:String(s);throw new p(`${t} could not read ${r==="-"?"stdin":`"${r.slice(1).trim()}"`}: ${a}`,m.NOT_FOUND,{code:"bulk_ids_input_unreadable",required:`Provide readable newline/comma-delimited IDs via ${t} -, ${t} @<path>, or inline argv text.`,nextSteps:[`Retry with inline IDs: ${t} pm-a1b2,pm-c3d4`,`Or pipe IDs: pm list --id-only | pm update-many ${t} - --dry-run`]})}let i=hs(o);if(i!=="")return i;throw new p(`${t} requires at least one non-empty item ID.`,m.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more comma- or newline-delimited IDs through argv, stdin, or @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]="1dcf0d72-10da-51b6-b9f6-ab47bebcbf64")}catch{}})();function ys(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function $r(e){if(e==="/body"||e.startsWith("/body/"))return"body";if(e==="/metadata"||e.startsWith("/metadata/")||e==="/front_matter"||e.startsWith("/front_matter/")){let n=e.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return n?ys(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?ys(t):"root"}function ln(e,t){return t==="body"?e.body:t==="metadata"?e.metadata:t==="root"?e:e.metadata[t]}function ou(e,t){let n=t?.windowStartIndex??0,r=t?.field;if(e.length===0||n>=e.length)return[];let o=zi(),i=[];for(let s=0;s<e.length;s+=1){let a=e[s],c=o,d=_t(o,a.patch),l;d.ok?(l=d.document,o=l):l=c;let u=new Set;for(let _ of a.patch)u.add($r(_.path)),_.from!==void 0&&u.add($r(_.from));let f=[...u].sort((_,y)=>_.localeCompare(y));if(s>=n)if(r!==void 0){if(!u.has(r))continue;let _={field:r,before:ln(c,r),after:ln(l,r)};i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:[r],changes:[_]})}else{let _=f.map(y=>({field:y,before:ln(c,y),after:ln(l,y)}));i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:f,changes:_})}}return i}import iu from"node:fs/promises";import su 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]="fd3a41f0-4e82-59ab-bb8c-ed796c96a0d7")}catch{}})();function au(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function cu(e,t){return new p(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,m.NOT_FOUND)}async function du(e,t){return await Ci(su.dirname(e)),await(await iu.open(e,"a")).close(),z({path:e,scope:"project",op:`${t}:history:auto_create`})}async function un(e){return gs({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function gs(e){let t=au(e.itemIds),n=[],r=[];for(let o of t){let i=te(e.pmRoot,o);if(!await j(i)){if(e.settings.history.missing_stream==="strict_error")throw cu(o,e.commandLabel);r.push(...await du(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}import{readFile as lu}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]="80805c6b-9b9a-5dad-b94b-d7dbd365fe5e")}catch{}})();var uu=e=>lu(e,"utf8");async function mu(e,t,n=uu){if(t!==void 0)throw new p("--body and --body-file are mutually exclusive; provide the body inline with --body or from a file with --body-file, not both.",m.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 r=e.trim();if(r.length===0)throw new p("--body-file requires a file path.",m.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."});if(r==="-")return await ze().resolveValue("-","--body-file");try{return await n(r)}catch(o){let i=o?.code,s=i==="EISDIR",a=i?` (${i})`:"";throw new p(s?`--body-file "${r}" is a directory, not a file. Point it at a readable file.`:`--body-file could not read "${r}"${a}. Check that the file exists and is readable.`,m.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 "${r}"`,"Or pipe the body with --body-file -.","Or pass the body inline with --body <text>."]})}}import fu from"node:crypto";import mn 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]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function bs(e){let t=[],n=!1;for(let r of(e??"").toLowerCase()){let o=r.charCodeAt(0),i=o>=48&&o<=57,s=o>=97&&o<=122;if(!i&&!s){n=t.length>0;continue}n&&(t.push("-"),n=!1),t.push(r)}return t.length===0?"pm-":`${t.join("")}-`}function Ve(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function le(e,t){let n=bs(t),r=Ve(e);return r.startsWith(n)?r:`${n}${r}`}function pu(e){let t=Di(e);if(t!==void 0)return t;let n="";for(let r=0;r<e;r+=1)n+=fu.randomInt(0,36).toString(36);return n}async function _u(e,t,n){let r=[...new Set(Object.values(n))].flatMap(o=>[mn.join(e,o,`${t}.md`),mn.join(e,o,`${t}.toon`)]);return r.push(mn.join(e,"history",`${t}.jsonl`)),(await Promise.all(r.map(o=>j(o)))).some(Boolean)}var ws=4,Es=12;function hu(e){return typeof e!="number"||!Number.isFinite(e)?ws:Math.min(Es,Math.max(ws,Math.trunc(e)))}async function yu(e,t,n={}){let r=hu(n.tokenLength),o=Math.min(r+6,Es),i=0;for(;r<=o;){for(let s=0;s<32;s+=1){let a=`${bs(t)}${pu(r)}`;if(!await(n.probeExisting===!1?j(mn.join(e,"history",`${a}.jsonl`)):_u(e,a,n.typeToFolder??ee)))return a;i+=1}r+=1}throw new Error(`Unable to generate unique id after ${i} attempts`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0394e0c1-ff68-5553-b022-1e8b6fff04f0")}catch{}})();var gu=new Set(["none","null","undefined"]);function uE(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new p("Config set parent-reference-policy requires --policy with one of: warn, strict_error (alias: strict)",m.USAGE)}function wu(e,t="cli"){let n=t==="sdk";if(typeof e!="string")throw new p(n?`parent must be a string. ${bt("parent")}.`:"--parent must be a string. Use --unset parent to clear this field.",m.USAGE);let r=e.trim();if(r.length===0)throw new p(an(t,"parent",". Use --parent none to unset."),m.USAGE);if(Ss(r))throw new p(n?`parent must not be the placeholder "${r}". ${bt("parent")}, or omit parent.`:`--parent must not use placeholder token "${r}". Use --unset parent to clear this field.`,m.USAGE);return r}function Ss(e){return gu.has(e.trim().toLowerCase())}function bu(e,t,n="cli"){if(t==="strict_error")throw new p(`Parent item "${e}" was not found. Create it first or ${n==="sdk"?"omit parent":"use --parent none"}.`,m.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${e}`]}}function Eu(e,t,n,r="cli"){let o=le(e,n),i=le(t,n);if(o!==i)return;let s=t!==i||e!==o?` (normalized from parent "${t}" and item "${e}")`:"";throw new p(`Parent item "${i}" cannot be the same as item "${o}"${s}. ${r==="sdk"?`${bt("parent")}.`:"Use --unset parent to clear this field."}`,m.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]="a59d5b7f-9764-53c5-a014-1119868be8ea")}catch{}})();var Fr={critical:0,high:1,medium:2,low:3,minimal:4},vs=Object.keys(Fr),Su=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${vs.join(", ")}), case-insensitive`;function fn(e){return new p(`Invalid priority "${e}". Accepted values: ${Su}.`,m.USAGE,{code:"invalid_argument_value",field:"priority",value:e,allowed:["0","1","2","3","4",...vs]})}function vu(e){if(typeof e=="number"){if(Number.isInteger(e)&&e>=0&&e<=4)return e;throw fn(String(e))}if(typeof e!="string")throw fn(String(e));let t=e.trim();if(t.length===0)throw fn(e);let n=t.toLowerCase();if(Object.prototype.hasOwnProperty.call(Fr,n))return Fr[n];if(/^[0-4]$/.test(t))return Number(t);throw fn(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]="e363ee89-b438-5c8e-bb06-f4d05cc814cc")}catch{}})();function Tu(e){let t={...e};for(let[n,r]of Object.entries(t))Array.isArray(r)&&Reflect.set(t,n,[...r]);return Ar(St(e,t))}function Iu(e){return wt(Et(St(e,{...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]="6012e77b-7cdd-5496-a668-c9240a811b1a")}catch{}})();var Cu=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,Au=64;function SE(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new p("Config set sprint-release-format-policy requires --policy with one of: warn, strict_error (alias: strict)",m.USAGE)}function xu(e,t,n,r="cli"){let o=t.trim();if(o.length===0)throw new p(an(r,e,`. Use --${e} none to unset.`),m.USAGE);if(o.length<=Au&&Cu.test(o))return{value:o,warnings:[]};let i="Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._/-]* (no spaces).";if(n==="strict_error")throw new p(`Invalid ${r==="sdk"?e:`--${e}`} value "${o}". ${i}`,m.USAGE);return{value:o,warnings:[`validation_warning:${e}_format:${o}`]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="14e6c7b4-3161-5f82-b797-f06a879d1370")}catch{}})();var Ts={open:"open_status",closed:"close_status",canceled:"canceled_status",cancelled:"canceled_status"},Is="all";function xE(e){if(typeof e!="string")return!1;let t=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);return t.length===1&&t[0]===Is}function Ru(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Ts[n];return r?t[r]:gr(e,t)}function ku(e){let t=new Set(Object.keys(Ts));for(let n of e.definitions){t.add(n.id);for(let r of n.aliases)t.add(r)}return[...t]}function Ou(e,t){let n=e.trim().toLowerCase(),r,o=Number.POSITIVE_INFINITY;for(let i of ku(t)){let s=be(n,i.toLowerCase(),2);s!==null&&s<o&&(r=i,o=s)}return r}function Du(e,t,n){if(typeof e!="string")return;let r=n?.strict===!0,o=n?.flagLabel??"--status",i=e.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(i.length===0)return;if(i.filter(a=>a.trim().toLowerCase()===Is).length>0){if(i.length===1)return;throw new p(`Invalid ${o} value "all". Use it by itself, or omit ${o} to search every status.`,m.USAGE)}let s=[];for(let a of i){let c=Ru(a,t);if(c===void 0){if(r){let d=Ou(a,t);throw new p(`Invalid ${o} value "${a}". Use open|closed|canceled or a configured status id${d?`. Did you mean "${d}"?`:"."}`,m.USAGE)}s.push(a);continue}s.push(c)}return[...new Set(s)]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="50f77f3f-b2b0-5ae2-b669-6ed50bbdd530")}catch{}})();var Nu={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 Mu(e){if(e!==void 0)return Nu[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]="c628dcf9-d98f-566e-9f93-cc81e737691c")}catch{}})();function As(e){let t=[],n=new Set;for(let r of e)for(let o of Object.keys(r))n.has(o)||(n.add(o),t.push(o));return t}function jr(e){return e==null?"":Array.isArray(e)?e.map(t=>jr(t)).join(";"):typeof e=="object"?JSON.stringify(e):String(e)}function Cs(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Lu(e){if(e.length===0)return"";let t=As(e),n=[t.map(r=>Cs(r)).join(",")];for(let r of e)n.push(t.map(o=>Cs(jr(r[o]))).join(","));return n.join(`
12
+ `)}function Pu(e){if(e.length===0)return"";let t=As(e),n=e.map(s=>t.map(a=>jr(s[a]))),r=t.map((s,a)=>Math.max(s.length,...n.map(c=>c[a].length))),o=(s,a)=>s.padEnd(r[a]),i=[t.map((s,a)=>o(s,a)).join(" | ")];i.push(r.map(s=>"-".repeat(s)).join("-+-"));for(let s of n)i.push(s.map((a,c)=>o(a,c)).join(" | "));return i.join(`
13
+ `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b84fee06-5bbd-57f9-9643-f283d6c87afa")}catch{}})();function $u(e,t="--limit"){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||n<0)throw new p(`${t} must be a non-negative number`,m.USAGE);return Math.floor(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]="158d5065-075c-5355-a65c-f3edc9c5f1f0")}catch{}})();var Fu=new Map(ot.map(e=>[e.toLowerCase(),e])),ju=/^[A-Za-z][A-Za-z0-9_-]*$/;function xs(e,t){if(!ju.test(e))throw new Error(`${t} "${e}" is not a valid identifier. Use a single letter-led token of letters, digits, hyphen, or underscore with no spaces or punctuation (e.g. "Spike" or "code-review").`)}function Ur(e){return Fu.get(e.trim().toLowerCase())}function Os(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Uu(e){return e.replace(/[\\"`$]/g,t=>`\\${t}`)}function Ds(e){let t=new Map;for(let n of e){let r=n.trim();if(r.length===0)continue;let o=r.toLowerCase();t.has(o)||t.set(o,r)}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function $E(e){let t=(e.name??"").trim();if(t.length===0)throw new Error("Type name must not be empty.");xs(t,"Type name");let n=Ur(t);if(n)throw new Error(`Cannot redefine built-in item type "${n}". Built-in types are reserved: ${ot.join(", ")}.`);let r=e.description?.trim(),o=e.defaultStatus?.trim(),i=e.folder?.trim(),s=i&&i.length>0?mr(i):void 0,a=Ds(e.aliases??[]);for(let c of a){xs(c,"Alias");let d=Ur(c);if(d)throw new Error(`Alias "${c}" collides with built-in item type "${d}". Built-in types are reserved: ${ot.join(", ")}.`)}return{name:t,description:r&&r.length>0?r:void 0,defaultStatus:o&&o.length>0?o:void 0,folder:s,aliases:a}}function FE(e,t){let n=e.name.toLowerCase(),r=new Map;for(let i of t.definitions){if(typeof i.name!="string")continue;let s=i.name.trim();if(!(s.length===0||s.toLowerCase()===n)){r.set(s.toLowerCase(),s);for(let a of Os(i.aliases))a.trim().length>0&&r.set(a.trim().toLowerCase(),s)}}let o=r.get(n);if(o)throw new Error(`Type name "${e.name}" collides with an alias of existing item type "${o}".`);for(let i of e.aliases){let s=r.get(i.toLowerCase());if(s)throw new Error(`Alias "${i}" already maps to existing item type "${s}".`)}}function Rs(e,t){return typeof t=="string"&&t.trim().length>0?mr(t).toLowerCase():Ai(e).toLowerCase()}function jE(e,t,n){let r=e.name.toLowerCase(),o=Rs(e.name,e.folder),i=a=>{throw new Error(`Item type "${e.name}" would store items in folder "${o}", which already belongs to existing item type "${a}". Pass a distinct --folder to keep their storage separate.`)};for(let a of t.definitions){if(typeof a.name!="string")continue;let c=a.name.trim();c.length===0||c.toLowerCase()===r||Rs(c,a.folder)===o&&i(c)}let s=n?.get(o);s!==void 0&&s.toLowerCase()!==r&&i(s)}function UE(e){if(e==null||e.trim().length===0)return{definitions:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/types.json contains invalid JSON.")}return{definitions:zu(t)}}function zu(e){let t=Vu(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;typeof o.name!="string"||o.name.trim().length===0||n.push(o)}return n}function Vu(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){let n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function zE(e,t){let n=t.name.toLowerCase(),r=e.definitions.slice(),o=r.findIndex(c=>typeof c.name=="string"&&c.name.trim().toLowerCase()===n),i=o>=0?r[o]:void 0,s=Ds([...Os(i?.aliases),...t.aliases]),a={...i,name:t.name};return t.folder!==void 0&&(a.folder=t.folder),s.length>0?a.aliases=s:a.aliases!==void 0&&delete a.aliases,ks(a,"description",t.description),ks(a,"default_status",t.defaultStatus),o>=0?r[o]=a:r.push(a),r.sort((c,d)=>c.name.localeCompare(d.name)),{file:{definitions:r},definition:a,replaced:o>=0,...i&&typeof i.name=="string"?{previousName:i.name}:{}}}function VE(e,t){let n=(t??"").trim();if(n.length===0)throw new Error("Type name must not be empty.");let r=Ur(n);if(r)throw new Error(`Cannot remove built-in item type "${r}". Built-in types are reserved: ${ot.join(", ")}.`);let o=n.toLowerCase(),i=e.definitions.slice(),s=i.findIndex(c=>typeof c.name=="string"&&c.name.trim().toLowerCase()===o);if(s<0)return{file:{definitions:i},removed:!1};let[a]=i.splice(s,1);return{file:{definitions:i},removed:!0,definition:a}}function ks(e,t,n){let r=e;n!==void 0&&(r[t]=n)}function HE(e){return`${JSON.stringify({definitions:e.definitions},null,2)}
14
+ `}function Hu(e,t){let n=e.trim().length>0?e.trim():e,r=t?.trim()||".agents/pm/schema/types.json";return`To register a custom type, run: pm schema add-type "${Uu(n)}" (writes ${r}).`}function qu(e,t,n){return`Invalid type value "${e}". Allowed: ${t.join(", ")}. ${Hu(e,n)}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4b79bd02-51ae-5c46-be4c-2f41dd8c9486")}catch{}})();function Ns(e,t){return nt(e,t)}function Bu(e,t,n){let r={};for(let o of t.command_to_fields.get(n)??[]){let i=hr(e,o);i!==void 0&&(r[o.metadata_key]=Pi(o,i))}return r}function Wu(e,t){for(let[n,r]of Object.entries(t)){let o=e[n];if(Array.isArray(r)){if(Array.isArray(o)){let i=o.map(s=>String(s));if(!r.map(s=>String(s)).every(s=>i.includes(s)))return!1;continue}if(!Ns(o,r[r.length-1]))return!1;continue}if(!Ns(o,r))return!1}return!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77a7b77a-907c-541d-ac55-e06174dbbf11")}catch{}})();function Ms(e){return typeof e=="string"?e.trim().toLowerCase():""}function pn(e,t){let n=lt(e);return n.length===0?"":t?.alias_to_id?.get(n)??n}function Yu(e){let t=Array.isArray(e?.type_workflows)?e.type_workflows:[],n=new Map;for(let r of t){let o=Ms(r?.type);if(o.length===0||!Array.isArray(r?.allowed_transitions))continue;let i=r.allowed_transitions,s=n.get(o)??{pairs:[],denyAll:!1};i.length===0&&(s.denyAll=!0);for(let a of i){if(!Array.isArray(a)||a.length!==2)continue;let c=lt(a[0]),d=lt(a[1]);c.length===0||d.length===0||s.pairs.some(l=>l[0]===c&&l[1]===d)||s.pairs.push([c,d])}n.set(o,s)}return[...n.entries()].filter(([,r])=>r.pairs.length>0||r.denyAll).map(([r,o])=>({type:r,allowed_transitions:o.pairs})).sort((r,o)=>r.type.localeCompare(o.type))}function Gu(e){let t=Ms(e.typeName),n=e.typeWorkflows.find(i=>i.type===t);if(!n)return{allowed:!0,hasRule:!1,allowedTransitions:[]};let r=pn(e.fromStatus,e.statusRegistry),o=pn(e.toStatus,e.statusRegistry);return r.length>0&&r===o?{allowed:!0,hasRule:!0,allowedTransitions:n.allowed_transitions}:{allowed:n.allowed_transitions.some(i=>{let s=pn(i[0],e.statusRegistry),a=pn(i[1],e.statusRegistry);return s===r&&a===o}),hasRule:!0,allowedTransitions:n.allowed_transitions}}function Ku(e){return e.length===0?"(no transitions allowed)":e.map(t=>`${t[0]} -> ${t[1]}`).join(", ")}import{spawnSync as Ps}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]="7889f11f-36f9-5384-8429-58d951c342da")}catch{}})();var Xu="PM_DISABLE_OLLAMA_AUTO_DEFAULTS",Ju="PM_OLLAMA_MODEL",Qu="http://localhost:11434",Zu="qwen3-embedding:0.6b",em=".agents/pm/search/lancedb/",tm=1500,nm=2500,rm=/qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i,om=/embed|embedding/i,ne=E;function im(){let e=ne(process.env[Xu]);if(!e)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}function Ls(e){return e.some(t=>ne(t)!==null)}function sm(e){let t=ne(e);return!!(t&&t.toLowerCase()!=="ollama")}function am(e){let t=ne(e);return!!(t&&t.toLowerCase()!=="lancedb")}function cm(e){return sm(e.search?.provider)||am(e.vector_store?.adapter)||Ls([e.providers?.openai?.base_url,e.providers?.openai?.model,e.providers?.openai?.api_key])?!0:Ls([e.vector_store?.qdrant?.url,e.vector_store?.qdrant?.api_key])}function dm(){let e=Ps("ollama",["--version"],{encoding:"utf8",timeout:tm});return e.error?!1:e.status===0}function lm(e){let t=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)return null;let n=t.map(r=>r.split(/\s+/)[0]?.trim()).filter(r=>!!(r&&r.length>0)).filter(r=>r.toUpperCase()!=="NAME");return n.length===0?null:n.find(r=>rm.test(r))||(n.find(r=>om.test(r))??null)}function um(e){let t=ne(e.providers?.ollama?.model);if(t)return t;let n=ne(process.env[Ju]);if(n)return n;let r=Ps("ollama",["list"],{encoding:"utf8",timeout:nm});if(!r.error&&r.status===0){let o=lm(typeof r.stdout=="string"?r.stdout:"");if(o)return o}return null}function mm(e){return{baseUrl:ne(e.providers?.ollama?.base_url)===null,model:ne(e.providers?.ollama?.model)===null,lancedbPath:ne(e.vector_store?.lancedb?.path)===null,embeddingModel:ne(e.search?.embedding_model)===null}}function fm(e){return e.baseUrl||e.model||e.lancedbPath||e.embeddingModel}function pm(e,t,n){if(!t.baseUrl&&!t.model)return;let r=e.providers??={},o=r.ollama??={};t.baseUrl&&(o.base_url=Qu),t.model&&(o.model=n)}function _m(e,t){if(!t.lancedbPath)return;let n=e.vector_store??={},r=n.lancedb??={};r.path=em}function hm(e,t,n){if(!t.embeddingModel)return;let r=e.search??={};r.embedding_model=n}function He(e){let t={settings:e,auto_ollama_defaults_applied:!1};if(im()||cm(e))return t;let n=mm(e);if(!fm(n)||n.model&&!dm())return t;let r=structuredClone(e),o=um(r);return o?(pm(r,n,o),_m(r,n),hm(r,n,o),{settings:r,auto_ollama_defaults_applied:!0}):{...t,auto_ollama_defaults_skipped_reason:"no_installed_embedding_model",auto_ollama_defaults_remediation:`Run ollama pull ${Zu} or configure providers.ollama.model explicitly (and search.embedding_model if you need an override).`}}import{spawn as ym}from"node:child_process";import{mkdirSync as $s,rmSync as js,statSync as gm}from"node:fs";import _n 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]="9ecff496-8afa-5cfc-9178-2be8bd403978")}catch{}})();var Us="reindex",wm="search/pending-refresh.json",bm="search/pending-refresh.gate.lock",Em=3e4,Sm="PM_SEARCH_REFRESH_INLINE",zs="PM_SEARCH_REFRESH_CHILD",vm=3e4;function Fs(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Tm(){if(Fs(process.env[Sm])||Fs(process.env[zs]))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 Vs(e){return _n.join(e,wm)}function Hs(e){return _n.join(e,bm)}function Im(e){let t=Hs(e);try{if(Date.now()-gm(t).mtimeMs<Em)return!1;js(t,{recursive:!0,force:!0})}catch{}try{return $s(_n.dirname(t),{recursive:!0}),$s(t),!0}catch{return!1}}function Cm(e){try{js(Hs(e),{recursive:!0,force:!0})}catch{}}async function qs(e,t,n){for(let r=0;r<50;r+=1){if(Im(e))try{return await t()}finally{Cm(e)}await Am(20)}return n}function Am(e){return new Promise(t=>{setTimeout(t,e)})}async function Vr(e){let t=await C(Vs(e));if(!t||t.trim().length===0)return[];try{let n=JSON.parse(t);return Array.isArray(n.ids)?n.ids.filter(r=>typeof r=="string"&&r.length>0):[]}catch{return[]}}async function Bs(e,t){await T(Vs(e),`${JSON.stringify({ids:t})}
15
+ `)}async function zr(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim().length>0);if(n.length===0)return;let r=async()=>{let o=await Vr(e),i=[...new Set([...o,...n])].sort((s,a)=>s.localeCompare(a));await Bs(e,i)};await qs(e,async()=>(await r(),!0),!1)||await r()}async function xm(e){return qs(e,async()=>{let t=await Vr(e);return t.length>0&&await Bs(e,[]),t},[])}function Rm(){return _n.join(ct(import.meta.url,["../../.."]),"dist","cli","search-refresh.js")}function Hr(e){try{let t=ym(process.execPath,[Rm()],{detached:!0,stdio:"ignore",env:{...process.env,PM_PATH:e,[zs]:"1"}});t.on("error",()=>{}),t.unref()}catch{}}function km(e){setTimeout(()=>Hr(e),vm)}async function Ws(e,t){await zr(e,t),Hr(e)}async function lS(e,t,n=km){let r=[],o=[];if(!await j(e))return{processed:o,rounds:0,warnings:r};let i;try{let l=await Ue(e),u=l.warnings.find(f=>f.startsWith("settings_read_"));if(u)return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${u}`]};i=He(l.settings).settings}catch(l){return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${S(l)}`]}}let s=null;try{s=await Se(e,Us,i.locks.ttl_seconds,mt(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:r};let a=0,c=!1,d=!1;try{for(;;){let l=await xm(e);if(l.length===0)break;a+=1;try{let u=await t(e,l);if(r.push(...u.warnings),u.warnings.some(f=>f.startsWith("search_semantic_refresh_skipped:settings_read_failed:"))){await zr(e,l),c=!0,d=!0;break}o.push(...u.refreshed)}catch(u){r.push(`search_background_refresh_failed:${S(u)}`),await zr(e,l),c=!0;break}}}finally{await s?.()}return d&&n(e),(c?[]:await Vr(e)).length>0&&Hr(e),{processed:[...new Set(o)].sort((l,u)=>l.localeCompare(u)),rounds:a,warnings: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]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function It(e,t=!1){let n=e[0];if(n?.op!=="history_compact_baseline")return 0;let r=n.context?.history_compaction,o=typeof r=="object"&&r!==null&&"version_offset"in r?r.version_offset:void 0;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&Number.isSafeInteger(o+e.length))return o;if(t)return null;throw new p("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",m.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="02424d1c-c29f-5a13-b711-d50267170b9f")}catch{}})();function Om(e,t){let n=-1;return e.forEach((r,o)=>{let i=Date.parse(r.ts);if(!Number.isFinite(i))throw new p(`History for this item contains invalid timestamp at entry ${o+1}.`,m.GENERIC_FAILURE);i<=t&&(n=o)}),n}function Dm(e,t){let n=e[0]?.ts??null,r=e.at(-1)?.ts??null,o={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:n,last_timestamp:r}};return r!==null&&(o.examples=[r],t!==null&&(o.examples.unshift(String(t+1),String(t+e.length)),o.valid_range.first_version=t+1,o.valid_range.last_version=t+e.length)),{guidance:o,lastTimestamp:r}}function Nm(e,t){let n={};if(t instanceof Error&&t.message.trim().length>0&&(n.reason=t.message.trim()),typeof t!="object"||t===null)return n;let r=t;if(typeof r.index=="number"&&Number.isInteger(r.index)&&r.index>=0&&(n.patchIndex=r.index),typeof r.operation=="object"&&r.operation!==null){let o=r.operation;Object.assign(n,Object.fromEntries(["op","path","from"].flatMap(i=>{let s=o[i];return typeof s=="string"?[[i,s]]:[]})))}if(n.patchIndex!==void 0){let o=e[n.patchIndex];o&&(n.op??=o.op,n.path??=o.path,n.from??=o.from)}return n}function Ys(e,t,n={}){let r=e.trim(),o=n.errorSubject??"history",i=o==="restore"?"Restore":"History",{guidance:s,lastTimestamp:a}=Dm(t,It(t,!0));if(!r)throw new p(`Missing ${o} target. Use a timestamp or version number.`,m.USAGE,s);if(/^\d+$/.test(r)){let l=It(t),u=Number(r);if(u>=1&&u<=l)throw new p(`History version ${u} was pruned by compaction.`,m.USAGE,{...s,code:"history_version_pruned"});if(!Number.isSafeInteger(u)||u<1||u>l+t.length)throw new p(`${i} version must be between ${l+1} and ${l+t.length} for this item.`,m.USAGE,s);return{kind:"version",raw:r,historyIndex:u-l-1}}let c=Date.parse(r);if(!Number.isFinite(c))throw new p(`Invalid ${o} target "${e}". Use a positive version number or ISO timestamp.`,m.USAGE,s);let d=Om(t,c);if(d<0||n.allowFutureTimestamp!==!0&&c>Date.parse(a))throw new p(o==="restore"?`No history entries exist at or before timestamp ${r}.`:`No history entry exists at timestamp ${r}.`,m.USAGE,s);return{kind:"timestamp",raw:r,historyIndex:d}}function qr(e,t,n,r){let o=_t(e,t);if(o.ok)return o.document;let i=Nm(t,o.error),s=[`history_op=${r}`,i.patchIndex===void 0?null:`patch_index=${i.patchIndex}`,i.op?`op=${i.op}`:null,i.path?`path=${i.path}`:null,i.from?`from=${i.from}`:null].filter(a=>a!==null);throw new p(`Failed to apply history patch at entry ${n} (${s.join(", ")}). ${i.reason??String(o.error)}`,m.GENERIC_FAILURE)}function Gs(e,t){let n=e[0];if(n&&n.op!=="create"&&n.op!=="history_compact_baseline"){let s=_t(pt,n.patch);if(!s.ok||typeof s.document.metadata.id!="string")throw new p("History starts without a reconstructable item baseline.",m.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}let r=e.slice(0,t+1),o=ht([...r]),i=structuredClone(pt);for(let s=0;s<=t;s+=1){let a=e[s];if(!a)throw new p(`History target entry ${s+1} does not exist.`,m.USAGE);i=qr(i,a.patch,s+1,a.op)}if(!o.ok)throw new p(`History cannot be replayed: ${o.errors.join(", ")}.`,m.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:o.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return i}function wS(e,t){if(Object.keys(e.metadata).length>0){if(typeof e.metadata.id!="string"||!Array.isArray(e.metadata.tags))throw new p("History has no complete item baseline for this target.",m.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return e}throw new p(`History target ${t.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,m.USAGE)}import Ks from"node:fs/promises";import Ct from"node:path";import{isUtf8 as Mm}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="697f1dbe-8315-5901-ab11-e0c5211dbdbf")}catch{}})();var Lm=1048576,Pm=4194304;async function Xs(e,t){let n=Ct.dirname(e);for(;n!==Ct.parse(e).root;){let o=await Ks.stat(n).catch(i=>{if(P(i))return null;throw i});if(o!==null){if(!o.isDirectory())throw new p("Workflow policy storage ancestor must be a directory.",m.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}n=Ct.dirname(n)}let r=await Ks.open(e,"r").catch(o=>{if(P(o))return null;throw o});if(r===null)return null;try{let o=(await r.stat()).size,i=Buffer.alloc(Math.min(t,o)+1),s=0;for(;s<i.length;){let a=await r.read(i,s,i.length-s,s);if(a.bytesRead===0)break;s+=a.bytesRead}if(s===i.length||!Mm(i.subarray(0,s)))throw new p("Workflow policy input exceeds its byte bound or is not valid UTF-8.",m.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return i.toString("utf8",0,s)}finally{await r.close()}}function $m(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let t;try{t=JSON.parse(e)}catch{throw new p("schema/policies.json must contain valid JSON.",m.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return wi(t)}async function Fm(e){return $m(await Xs(Ct.join(e,"schema","policies.json"),Lm))}async function jm(e,t){let n=await Xs(te(e,t),Pm);if(n===null)return[];let r;try{if(r=n.split(/\r?\n/).filter(o=>o.trim()).map(o=>JSON.parse(o)),!ht(r).ok)throw new Error("invalid chain")}catch{throw new p("Approval evidence requires a valid item history chain.",m.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${t} --verify before recording or using an approval.`]})}return r.flatMap(o=>{let i=o.context?.workflow_approval;if(o.op!=="policy_approve"||o.record_hash_version!==1||typeof o.record_hash!="string"||typeof i!="object"||i===null)return[];let s=i;return typeof s.policy_fingerprint!="string"||typeof s.content_fingerprint!="string"?[]:[{policy_fingerprint:s.policy_fingerprint,content_fingerprint:s.content_fingerprint,author:o.author}]})}async function Um(e,t,n){let r=n.before?.status!==n.after?.status&&t.policies.some(s=>s.rule.kind==="approval"&&bi(s,n)),o=n.before?.id??n.after?.id,i=r&&typeof o=="string"?await jm(e,o):[];return Ei(t,{...n,approvals:i})}async function Br(e){let t=await Fm(e.pmRoot),n=await Um(e.pmRoot,t,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(n.allowed)return n;let r=n.decisions.filter(f=>!f.satisfied&&f.effect==="refuse"),o=[],i="";if(!e.dryRun)try{let f=await Sr({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:n.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms});o.push({path:"history/_workspace.jsonl",op:"policy_refused",record_hash:f.entry.record_hash}),i=" Audit appended to tracker-relative history/_workspace.jsonl; retain it with the workspace changes. Each refused attempt records its own audit event."}catch(f){let _=new p("Workflow policy refusal could not be recorded in workspace history.",m.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw _.cause=f,_}let s=r.slice(0,3).map(f=>({policy_id:f.policy_id,rule:f.rule,description:t.policies.find(_=>_.id===f.policy_id).description,missing_fields:f.missing_fields})),a=[...new Set(s.flatMap(f=>f.missing_fields))],c=s.map(f=>`${f.policy_id} (${f.rule})`).join(", "),d=r.length>3?` and ${r.length-3} more`:"",l=e.after?.metadata.id??e.before.metadata.id,u=a.map(f=>{if(e.before===null)return`Supply ${f} in the original ${e.operation} request, then retry; the item was not created.`;let _=lr("update",f);return _===void 0?`Supply ${f} using its declared SDK or package mutation contract, then retry.`:q(["update",l,ur("update",_),`<${f}>`,"--pm-path",Ct.resolve(e.pmRoot)])});throw new p(`Workflow policy refused ${e.operation}: ${c}${d}.${a.length?` Missing: ${a.join(", ")}.`:""}${i}`,m.CONFLICT,{code:"workflow_policy_refused",side_effects:o,reason:s.map(f=>f.policy_id).join(","),policy_violations:s,policy_violation_count:r.length,required:a.length?`Supply missing fields: ${a.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:s.map(f=>f.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:a},nextSteps:[...u,...new Set(r.slice(0,3).filter(f=>f.missing_fields.length===0).map(f=>f.remediation)),...r.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as zm}from"node:async_hooks";import{channel as Vm}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var Wr=new zm,Yr=Vm("@unbrained/pm-cli/item-metadata-enumeration/v1");function hn(e){Yr.publish(e)}async function PS(e){let t={enumeration_calls:0,metadata_rows:0},n=r=>{Wr.getStore()?.includes(t)&&(t.enumeration_calls+=1,t.metadata_rows+=r)};Yr.subscribe(n);try{return{result:await Wr.run([...Wr.getStore()??[],t],e),work:{...t}}}finally{Yr.unsubscribe(n)}}import{AsyncLocalStorage as Js}from"node:async_hooks";import{realpathSync as Hm}from"node:fs";import Kr 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]="0d72cf82-14ea-573b-a36e-0077c82c0c1d")}catch{}})();var Gr=new Js;function WS(e,t){return Gr.run([...Gr.getStore()??[],{...e,pmRoot:Kr.resolve(e.pmRoot)}],t)}var qm=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),Bm=globalThis,At=Bm[qm]??=new Js;function qe(e){let t=Kr.resolve(e);try{return Hm.native(t)}catch{return t}}function YS(){return{entries:new Map}}function GS(e,t){return At.run([...At.getStore()??[],e],t)}function KS(e,t,n){let r=qe(t);if(e.pmRoot!==void 0&&e.pmRoot!==r)throw new p("An expected-revision scope is already bound to another tracker.",m.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});e.pmRoot=r;for(let{id:o,itemHash:i}of n){let s=e.entries.get(o);if(s!==void 0&&s.declared!==i)throw new p(`Item ${o} has two different expected revisions.`,m.USAGE,{code:"expected_revision_duplicate",item_id:o,required:"Declare at most one expected revision per item."});e.entries.set(o,s??{declared:i,expected:i,checked:!1,committed:!1})}}function XS(e){let t=[...e.entries.entries()];return{checked:t.filter(([,n])=>n.checked).map(([n])=>n),unchecked:t.filter(([,n])=>!n.checked).map(([n])=>n)}}function Xr(e,t){let n=At.getStore()??[];if(n.length===0)return[];let r=qe(e),o=new Set(t.filter(i=>typeof i=="string"));return[...new Set(n.flatMap(i=>i.pmRoot===r?[...o].flatMap(s=>i.entries.get(s)??[]):[]))]}function JS(e){let t=At.getStore()??[];if(t.length===0)return[];let n=qe(e),r=new Map;for(let o of t)if(o.pmRoot===n)for(let[i,s]of o.entries){if(s.expected!==s.declared)return;r.set(i,(r.get(i)??new Set).add(s.expected))}if(![...r.values()].some(o=>o.size>1))return[...r].map(([o,i])=>`${o}=${[...i][0]}`)}function QS(e){let t=qe(e);return(At.getStore()??[]).some(n=>n.pmRoot===t&&n.entries.size>0)}function Wm(e,t,n){let r=Xr(e,[n,t.metadata.id]);r.length>0&&ea(r,n,en(t),!1,e)}function ZS(e,t,n){let r=Xr(e,[t]);r.length>0&&ea(r,t,yi(n),!0,e)}var Ym="revision_changed",Gm="document_unreadable";function Km(e,t,n={}){let r=[...n.scopeArgs??[]],o=[...n.outputArgs??["--json"]],i=q([...r,"get",e,...o]),s=q([...r,"history",e,"--limit","5",...o]);return{required:t?`Recover ${e} without --expect-hash (${q([...r,"restore",e,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${e} (${i} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[q([...r,"get",e,"--fields","item_hash",...o]),s],nextSteps:[i,s]}}var Xm=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),Jm=globalThis,Jr=Jm[Xm]??=new WeakMap,Qm=8;function Qs(e){for(let t of Zs(e)){let n=Jr.get(t);if(n!==void 0)return n}}function*Zs(e){let t=e;for(let n=0;n<Qm&&typeof t=="object"&&t!==null;n+=1){yield t;try{t=t.cause}catch{return}}}function ea(e,t,n,r,o){for(let i of e)if(i.checked=!0,!(!r&&i.expected===n))throw nf(o,new p(`Item ${t} is no longer at the expected revision ${i.expected.slice(0,12)}${r?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${i.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,m.CONFLICT,{code:"item_revision_conflict",item_id:t,expected_revision:i.expected,current_revision:n,reason:r?Gm:Ym,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...Km(t,r)}))}function ev(e,t){let n=Qs(e);return n===void 0||n===qe(t)}var Zm=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),ef=globalThis,Qr=ef[Zm]??=new WeakSet;function tf(e){for(let t of Zs(e))if(Qr.has(t))return!0;return!1}function tv(e){return Qr.add(e),e}function nv(e,t){let n=Qs(e);return n!==void 0&&Jr.set(t,n),tf(e)&&Qr.add(t),t}function nf(e,t){return Jr.set(t,qe(e)),t}function Zr(e,t,n=t.metadata.id){Wm(e,t,n);for(let r of eo(e,[n,t.metadata.id]))r.validate(t)}function eo(e,t){let n=Kr.resolve(e);return(Gr.getStore()??[]).filter(r=>r.pmRoot===n&&t.includes(r.id))}function to(e,t,n=t.metadata.id,r=[],o){let i=Xr(e,[n,t.metadata.id,...r]);if(i.length>0){let s=o??en(t);for(let a of i)a.expected=s,a.committed=!0}for(let s of eo(e,[n,t.metadata.id,...r]))s.committed?.(t)}function ta(e,t){return Object.assign({},...eo(e,t).map(n=>n.historyContext))}import Ie from"node:fs/promises";import ra from"node:path";import{randomUUID as rf}from"node:crypto";import{createRequire as of}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]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var sf="metadata-query-index.sqlite",xt="5",no;function Rt(){return no!==void 0||(no=Ui(process.versions.node,of(import.meta.url))),no}function na(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function Be(e){return ra.join(e,"runtime",sf)}function af(e){e.exec(`
16
16
  PRAGMA foreign_keys = ON;
17
17
  PRAGMA journal_mode = OFF;
18
18
  PRAGMA synchronous = OFF;
@@ -67,7 +67,7 @@ ${i}`;continue}return null}return n}function Or(e,t){let n=Zi(e).trim();if(!n)th
67
67
  tags,
68
68
  tokenize = 'unicode61'
69
69
  );
70
- `)}function gn(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function ea(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
70
+ `)}function gn(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function oa(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
71
71
  id, relative_path, metadata_json, status, type, priority,
72
72
  updated_at, created_at, parent, assignee, sprint, release
73
73
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -82,10 +82,10 @@ ${i}`;continue}return null}return n}function Or(e,t){let n=Zi(e).trim();if(!n)th
82
82
  parent = excluded.parent,
83
83
  assignee = excluded.assignee,
84
84
  sprint = excluded.sprint,
85
- release = excluded.release`).run(n.id,t.relativePath,JSON.stringify(n),n.status,n.type,n.priority,n.updated_at,n.created_at,n.parent??null,n.assignee??null,n.sprint??null,n.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_search WHERE rowid = (SELECT rowid FROM items WHERE id = ?)").run(n.id),e.prepare("INSERT INTO item_search(rowid, id, title, description, tags) SELECT rowid, ?, ?, ?, ? FROM items WHERE id = ?").run(n.id,n.title,n.description,n.tags.join(" "),n.id);let r=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let i of Object.keys(n))r.run(n.id,i);let o=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let i of t.linkedFiles??[])o.run(n.id,i.path,i.scope,i.note??null)}async function ta(e){let t=Be(e.pmRoot),n=Rt();if(!n){await Ie.rm(t,{force:!0});return}await Ie.mkdir(Zs.dirname(t),{recursive:!0});let r=`${t}.${tf()}.tmp`,o;try{o=new n(r),of(o),o.exec("BEGIN IMMEDIATE"),gn(o,"version",xt),gn(o,"context_fingerprint",e.contextFingerprint),gn(o,"source_cursor",e.sourceCursor);for(let i of e.rows)ea(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Ie.rm(t,{force:!0}),await Ie.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Ie.rm(r,{force:!0})]),i}}function wn(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function na(e){let t=Rt();if(!t)return!1;let n=Be(e.pmRoot),r;try{await Ie.access(n),r=new t(n),r.exec("PRAGMA foreign_keys = ON");let o=wn(r);if(o.version!==xt||o.context_fingerprint!==e.contextFingerprint||o.source_cursor!==e.expectedSourceCursor)return r.close(),!1;r.exec("BEGIN IMMEDIATE");let i=r.prepare("DELETE FROM items WHERE relative_path = ?"),s=r.prepare("SELECT rowid FROM items WHERE relative_path = ?"),a=r.prepare("DELETE FROM item_search WHERE rowid = ?");for(let c of e.deletedRelativePaths??[]){let d=s.get(c);i.run(c),d&&a.run(d.rowid)}return e.row&&ea(r,e.row),gn(r,"source_cursor",e.sourceCursor),r.exec("COMMIT"),r.close(),!0}catch{try{r?.exec("ROLLBACK")}catch{}return r?.close(),!1}}function yn(e,t,n,r,o){!r||r.length===0||(e.push(`${n} ${o} (${r.map(()=>"?").join(", ")})`),t.push(...r))}function sf(e){let t=[],n=[];yn(t,n,"status",e.statuses,"IN"),yn(t,n,"status",e.excludeStatuses,"NOT IN"),yn(t,n,"type",e.types,"IN"),yn(t,n,"id",e.ids,"IN");for(let r of e.metadataKeys??[])t.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),n.push(r);for(let[r,o]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])o!==void 0&&(t.push(`${r} = ?`),n.push(o));return e.priority!==void 0&&(t.push("priority = ?"),n.push(e.priority)),{where:t.length===0?"":` WHERE ${t.join(" AND ")}`,parameters:n}}async function av(e){let t=Rt();if(!t)return null;let n=e.query??{},{where:r,parameters:o}=sf(n),i;try{i=new t(Be(e.pmRoot),{readOnly:!0});let s=wn(i);if(s.version!==xt||s.source_cursor!==e.expectedSourceCursor)return i.close(),null;let a=i.prepare(`SELECT COUNT(*) AS count FROM items${r}`).get(...o),c=[],d="";n.limit!==void 0?(d+=" LIMIT ?",c.push(Math.max(0,Math.floor(n.limit))),n.offset!==void 0&&(d+=" OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))))):n.offset!==void 0&&(d+=" LIMIT -1 OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))));let l=i.prepare(`SELECT metadata_json FROM items${r}
86
- ORDER BY ${n.terminalStatuses&&n.terminalStatuses.length>0?`CASE WHEN status IN (${n.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${d}`).all(...o,...n.terminalStatuses??[],...c).map(u=>{let f=JSON.parse(String(u.metadata_json));if(!f.id)throw new TypeError("Indexed metadata row has no id");return f});return i.close(),{source_cursor:s.source_cursor,total:Number(a.count),items:l}}catch{return i?.close(),null}}async function cv(e){let t=Rt();if(!t||e.paths.length===0)return null;let n;try{n=new t(Be(e.pmRoot),{readOnly:!0});let r=wn(n);if(r.version!==xt||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let o=e.paths.map(()=>"?").join(", "),i=e.scope===void 0?"":" AND scope = ?",s=[...e.paths,...e.scope===void 0?[]:[e.scope]],a=`path IN (${o})${i}`,c=n.prepare(`SELECT COUNT(DISTINCT item_id) AS count
85
+ release = excluded.release`).run(n.id,t.relativePath,JSON.stringify(n),n.status,n.type,n.priority,n.updated_at,n.created_at,n.parent??null,n.assignee??null,n.sprint??null,n.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_search WHERE rowid = (SELECT rowid FROM items WHERE id = ?)").run(n.id),e.prepare("INSERT INTO item_search(rowid, id, title, description, tags) SELECT rowid, ?, ?, ?, ? FROM items WHERE id = ?").run(n.id,n.title,n.description,n.tags.join(" "),n.id);let r=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let i of Object.keys(n))r.run(n.id,i);let o=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let i of t.linkedFiles??[])o.run(n.id,i.path,i.scope,i.note??null)}async function ia(e){let t=Be(e.pmRoot),n=Rt();if(!n){await Ie.rm(t,{force:!0});return}await Ie.mkdir(ra.dirname(t),{recursive:!0});let r=`${t}.${rf()}.tmp`,o;try{o=new n(r),af(o),o.exec("BEGIN IMMEDIATE"),gn(o,"version",xt),gn(o,"context_fingerprint",e.contextFingerprint),gn(o,"source_cursor",e.sourceCursor);for(let i of e.rows)oa(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Ie.rm(t,{force:!0}),await Ie.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Ie.rm(r,{force:!0})]),i}}function wn(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function sa(e){let t=Rt();if(!t)return!1;let n=Be(e.pmRoot),r;try{await Ie.access(n),r=new t(n),r.exec("PRAGMA foreign_keys = ON");let o=wn(r);if(o.version!==xt||o.context_fingerprint!==e.contextFingerprint||o.source_cursor!==e.expectedSourceCursor)return r.close(),!1;r.exec("BEGIN IMMEDIATE");let i=r.prepare("DELETE FROM items WHERE relative_path = ?"),s=r.prepare("SELECT rowid FROM items WHERE relative_path = ?"),a=r.prepare("DELETE FROM item_search WHERE rowid = ?");for(let c of e.deletedRelativePaths??[]){let d=s.get(c);i.run(c),d&&a.run(d.rowid)}return e.row&&oa(r,e.row),gn(r,"source_cursor",e.sourceCursor),r.exec("COMMIT"),r.close(),!0}catch{try{r?.exec("ROLLBACK")}catch{}return r?.close(),!1}}function yn(e,t,n,r,o){!r||r.length===0||(e.push(`${n} ${o} (${r.map(()=>"?").join(", ")})`),t.push(...r))}function cf(e){let t=[],n=[];yn(t,n,"status",e.statuses,"IN"),yn(t,n,"status",e.excludeStatuses,"NOT IN"),yn(t,n,"type",e.types,"IN"),yn(t,n,"id",e.ids,"IN");for(let r of e.metadataKeys??[])t.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),n.push(r);for(let[r,o]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])o!==void 0&&(t.push(`${r} = ?`),n.push(o));return e.priority!==void 0&&(t.push("priority = ?"),n.push(e.priority)),{where:t.length===0?"":` WHERE ${t.join(" AND ")}`,parameters:n}}async function lv(e){let t=Rt();if(!t)return null;let n=e.query??{},{where:r,parameters:o}=cf(n),i;try{i=new t(Be(e.pmRoot),{readOnly:!0});let s=wn(i);if(s.version!==xt||s.source_cursor!==e.expectedSourceCursor)return i.close(),null;let a=i.prepare(`SELECT COUNT(*) AS count FROM items${r}`).get(...o),c=[],d="";n.limit!==void 0?(d+=" LIMIT ?",c.push(Math.max(0,Math.floor(n.limit))),n.offset!==void 0&&(d+=" OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))))):n.offset!==void 0&&(d+=" LIMIT -1 OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))));let l=i.prepare(`SELECT metadata_json FROM items${r}
86
+ ORDER BY ${n.terminalStatuses&&n.terminalStatuses.length>0?`CASE WHEN status IN (${n.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${d}`).all(...o,...n.terminalStatuses??[],...c).map(u=>{let f=JSON.parse(String(u.metadata_json));if(!f.id)throw new TypeError("Indexed metadata row has no id");return f});return i.close(),{source_cursor:s.source_cursor,total:Number(a.count),items:l}}catch{return i?.close(),null}}async function uv(e){let t=Rt();if(!t||e.paths.length===0)return null;let n;try{n=new t(Be(e.pmRoot),{readOnly:!0});let r=wn(n);if(r.version!==xt||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let o=e.paths.map(()=>"?").join(", "),i=e.scope===void 0?"":" AND scope = ?",s=[...e.paths,...e.scope===void 0?[]:[e.scope]],a=`path IN (${o})${i}`,c=n.prepare(`SELECT COUNT(DISTINCT item_id) AS count
87
87
  FROM item_linked_files
88
- WHERE ${a}`).get(...s),d=Qs(e.limit,50),l=Qs(e.offset,0),u=n.prepare(`SELECT items.id, items.metadata_json
88
+ WHERE ${a}`).get(...s),d=na(e.limit,50),l=na(e.offset,0),u=n.prepare(`SELECT items.id, items.metadata_json
89
89
  FROM items
90
90
  WHERE EXISTS (
91
91
  SELECT 1 FROM item_linked_files
@@ -96,29 +96,29 @@ ${i}`;continue}return null}return n}function Or(e,t){let n=Zi(e).trim();if(!n)th
96
96
  FROM item_linked_files
97
97
  WHERE item_id IN (${_.map(()=>"?").join(", ")})
98
98
  AND ${a}
99
- ORDER BY path ASC, scope ASC`).all(..._,...s),g=new Map(_.map(h=>[h,[]]));for(let h of y){let w=String(h.item_id),b=g.get(w);b.push({path:String(h.path),scope:String(h.scope),...h.note===null?{}:{note:String(h.note)}}),g.set(w,b)}for(let h of u){let w=JSON.parse(String(h.metadata_json));f.push({item:w,files:g.get(String(h.id))})}}return n.close(),{source_cursor:r.source_cursor,total:Number(c.count),matches:f}}catch{return n?.close(),null}}async function dv(e){let t=Rt();if(!t)return null;let n;try{n=new t(Be(e.pmRoot),{readOnly:!0});let r=wn(n);if(r.version!==xt||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let o=n.prepare(`SELECT items.metadata_json
99
+ ORDER BY path ASC, scope ASC`).all(..._,...s),g=new Map(_.map(h=>[h,[]]));for(let h of y){let w=String(h.item_id),b=g.get(w);b.push({path:String(h.path),scope:String(h.scope),...h.note===null?{}:{note:String(h.note)}}),g.set(w,b)}for(let h of u){let w=JSON.parse(String(h.metadata_json));f.push({item:w,files:g.get(String(h.id))})}}return n.close(),{source_cursor:r.source_cursor,total:Number(c.count),matches:f}}catch{return n?.close(),null}}async function mv(e){let t=Rt();if(!t)return null;let n;try{n=new t(Be(e.pmRoot),{readOnly:!0});let r=wn(n);if(r.version!==xt||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let o=n.prepare(`SELECT items.metadata_json
100
100
  FROM item_search
101
101
  JOIN items ON items.id = item_search.id
102
102
  WHERE item_search MATCH ?
103
103
  ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
104
- LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(i=>JSON.parse(String(i.metadata_json)));return n.close(),{source_cursor:r.source_cursor,items:o}}catch{return n?.close(),null}}async function bn(e){await Ie.rm(Be(e),{force:!0})}import N from"node:fs/promises";import v from"node:path";import{createHash as af,randomUUID as aa}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();var re=8,ca=500,cf="metadata-derived-index",df="metadata-cache.json",lf="metadata-cache-bodies.json",uf="metadata-cache-collections.json",mf="metadata-cache-delta.json",ff="metadata-cache-manifest.json",ra=4,pf=["comments","notes","learnings","files","tests","test_runs","docs"];function da(){return Tt(fe())}function Sn(e){let t={...e},n={};for(let r of pf)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function la(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function ua(e,t,n,r){let o=af("sha256");o.update(`format:${e??"default"}`);let i=Object.entries(t).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}=${a}`).join(",");return o.update(`|types:${i}`),n&&o.update(`|schema:${JSON.stringify(n)}`),r.length>0&&o.update(`|extension_fields:${r.join(",")}`),o.digest("hex").slice(0,16)}function vn(e){return v.join(e,"runtime",df)}function Tn(e){return v.join(e,"runtime",lf)}function In(e){return v.join(e,"runtime",uf)}function ro(e){return v.join(e,"runtime",mf)}function oo(e){return v.join(e,"runtime",ff)}function Cn(e,t){let n=v.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var _f=24,B=new Map,An=new WeakMap;function io(e){return An.get(e)??e.source_cursor}function hf(e,t){let n=io(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){An.set(e,n);for(let[r,o]of Object.entries(t.changes))o.entry?e.entries[r]=o.entry:delete e.entries[r];e.directory_signatures=t.directory_signatures,e.source_cursor=t.source_cursor}}function yf(e,t){if(!e)return;let n=io(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){An.set(e,n);for(let[r,o]of Object.entries(t.changes))o.body?e.bodies[r]=o.body:delete e.bodies[r];e.source_cursor=t.source_cursor}}function gf(e,t){if(!e)return;let n=io(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){An.set(e,n);for(let[r,o]of Object.entries(t.changes))o.collections?e.collections[r]=o.collections:delete e.collections[r];e.source_cursor=t.source_cursor}}function wf(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(hf(e,r),yf(t,r),gf(n,r))}function no(e,t){B.size>=_f&&!B.has(e)&&ki(B),B.set(e,t)}async function _e(e,t){let n;try{n=await N.stat(e)}catch{return B.delete(e),null}let r=B.get(e);if(r&&kt(r.signature,n.mtimeMs,n.ctimeMs,n.size))return B.delete(e),B.set(e,r),r.envelope;let o;try{o=t(await N.readFile(e,"utf8"))}catch{o=null}return no(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function bf(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==re||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=vn(e),i=await _e(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await _e(Cn(o,t),r);return s===null&&Nt(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function Ef(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==re||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Tn(e),o=await _e(r,n);return t&&o?.context_fingerprint!==t?await _e(Cn(r,t),n):o}async function Sf(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==re||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=In(e),o=await _e(r,n);return t&&o?.context_fingerprint!==t?await _e(Cn(r,t),n):o}async function so(e){let t=ro(e),n=await _e(t,r=>{let o=JSON.parse(r);return o.version!==re||typeof o.base_source_cursor!="string"||typeof o.source_cursor!="string"||typeof o.changes!="object"||o.changes===null?null:o});if(n)return{envelope:n,invalid:!1};try{return await N.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function ao(e){let t=oo(e),n=await _e(t,r=>{let o=JSON.parse(r);return o.version!==re||typeof o.context_fingerprint!="string"||typeof o.source_cursor!="string"||!Number.isInteger(o.entry_count)||o.entry_count<0||typeof o.directory_signatures!="object"||o.directory_signatures===null?null:o});if(n)return n;try{await N.stat(t),await We(e)}catch{}return null}async function Ot(e,t){await N.mkdir(v.dirname(e),{recursive:!0}),await T(e,JSON.stringify(t));try{let r=await N.stat(e);no(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{B.delete(e)}let n=v.dirname(v.dirname(e));if(e===vn(n)||e===Tn(n)||e===In(n)){let r=Cn(e,t.context_fingerprint);await T(r,JSON.stringify(t));try{let c=await N.stat(r);no(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{B.delete(r)}let o=v.dirname(e),i=v.extname(e),s=v.basename(e,i),a=(await N.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==v.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>v.join(o,c.name));if(a.length>ra){let c=(await Promise.all(a.map(async d=>{try{return{path:d,mtime:(await N.stat(d)).mtimeMs}}catch{return null}}))).filter(d=>d!==null);for(let d of c.sort((l,u)=>l.mtime-u.mtime).slice(0,Math.max(0,c.length-ra)))await N.rm(d.path,{force:!0}),B.delete(d.path)}}}function vf(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function ma(e,t,n){return e===void 0||vf(e,t,n)}function Nt(e,t){e&&!e.includes(t)&&e.push(t)}function kt(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function Tf(e,t,n){let r=v.join(e,t);try{let o=await N.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!P(o)&&Nt(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function If(e,t){try{let n=await N.stat(v.join(e,t));return[t,{exists:!0,mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size}]}catch{return[t,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function En(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await If(e,n))))}function Dt(e,t){return!e||Object.keys(e).length!==Object.keys(t).length?!1:Object.entries(t).every(([n,r])=>{let o=e[n];return o!==void 0&&o.exists===r.exists&&kt(o,r.mtime_ms,r.ctime_ms,r.size)})}function Cf(e){return Gt.some(t=>e.toLowerCase().endsWith(t))}function Af(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function xf(e,t,n){if(n)for(let r of await Ee({path:e,scope:"project"}))Nt(t,r)}function oa(e,t,n,r){if(e)return t&&n?n.collections:r}async function Rf(e,t,n){let r=await N.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=st(e);await xf(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],d=!n.forceSourceRead&&c!==void 0&&kt(c,o,i,s),l=n.previousBodies[t],u=!n.forceSourceRead&&l!==void 0&&kt(l,o,i,s),f=n.previousCollections[t],_=!n.forceSourceRead&&f!==void 0&&kt(f,o,i,s);if(!(!d||n.includeBody&&!u||n.includeCollections&&!_))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:oa(n.includeCollections,_,f,void 0),bodyLength:c.body_length,body:n.includeBody?l.body:void 0};let y=await N.readFile(e,"utf8"),g=ce(y,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:w=>Nt(n.warnings,w)}),h=Sn(g.metadata);return Af(n.state.misses,n.includeBody,n.includeCollections,d,u,_),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:d?c.metadata:h.light,heavyMetadata:oa(n.includeCollections,_,f,h.heavy),bodyLength:d?c.body_length:g.body.length,body:n.includeBody?g.body:void 0}}function kf(e,t,n,r){n.state.newEntries[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,metadata:r.lightMetadata,body_length:r.bodyLength},n.includeBody&&r.body!==void 0&&(n.state.newBodies[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,body:r.body}),n.includeCollections&&r.heavyMetadata!==void 0&&(n.state.newCollections[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,collections:r.heavyMetadata});let o=n.includeCollections?la(r.lightMetadata,r.heavyMetadata):r.lightMetadata,i=n.state.documentsById.get(o.id),s={metadata:o,body:r.body,item_format:r.itemFormat,item_path:e};ma(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function Of(e,t,n,r){try{let o=await Rf(t,n,r);kf(t,n,r,o)}catch{Nt(r.warnings,`item_list_item_read_failed:${e}/${v.basename(t)}`)}}function Df(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function Nf(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function Mf(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function Lf(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function Pf(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!Cf(s))continue;let a=v.join(o,s),c=v.relative(t.pmRoot,a);n.push(Of(r,a,c,t)),n.length===32&&(await Promise.all(n),n.length=0)}await Promise.all(n)}async function $f(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Dt(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Ot(vn(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Ot(oo(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let t=[...e.state.documentsById.values()].map(({candidate:n})=>({relativePath:v.relative(e.pmRoot,n.item_path),metadata:Sn(n.metadata).light,linkedFiles:n.metadata.files??[]}));t.length>=e.minimumIndexedItems?await ta({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:t}):await bn(e.pmRoot)}catch{}}async function Ff(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await Ot(Tn(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function jf(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await Ot(In(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function co(e,t,n={}){let r=await ao(e);return n.required!==!0&&(r===null||r.entry_count<ca)?async()=>{}:Se(e,cf,30,t,!1,!1,3e3)}async function Sv(e,t){let n=await ao(e);if(n===null)return null;let r=await so(e);if(r.invalid)return await We(e),null;let o=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.source_cursor:n.source_cursor,i=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.directory_signatures:n.directory_signatures;return t&&!Dt(i,await En(e,t))?null:{source_cursor:o,entry_count:n.entry_count}}function ia(e,t){let n=v.relative(e,t);return n===""||n===".."||n.startsWith(`..${v.sep}`)||v.isAbsolute(n)?null:n}async function We(e){await Promise.all([vn(e),Tn(e),In(e),ro(e),oo(e)].map(async t=>{await N.rm(t,{force:!0}),B.delete(t)})),await bn(e)}async function Uf(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await N.stat(e.mutation.itemPath),n=Sn(e.mutation.document.metadata),r={mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size};return{entry:{...r,metadata:n.light,body_length:e.mutation.document.body.length},body:{...r,body:e.mutation.document.body},collections:{...r,collections:n.heavy}}}function zf(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function lo(e){let t=ia(e.pmRoot,e.itemPath),n=e.previousItemPath?ia(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await We(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=ua(e.preferredFormat,e.typeToFolder,e.schema,da()),o=await ao(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await so(e.pmRoot);if(s.invalid)return await We(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=zf(s.envelope,r,i),c=s.envelope?.context_fingerprint===r&&s.envelope.base_source_cursor===i?s.envelope.source_cursor:i;n!==void 0&&(a[n]={entry:null,body:null,collections:null}),a[t]=await Uf({mutation:e});let d=aa();return await Ot(ro(e.pmRoot),{version:re,context_fingerprint:r,base_source_cursor:i,source_cursor:d,directory_signatures:await En(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await na({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:d,row:e.document===null?null:{relativePath:t,metadata:Sn(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await bn(e.pmRoot),[]}catch{return await We(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function Vf(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function sa(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function Hf(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function qf(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=st(n);if(!o)continue;let i=e.includeCollections?la(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);ma(s?.itemFormat,o,e.preferredFormat)&&t.set(i.id,{itemFormat:o,candidate:{metadata:i,body:e.includeBody?e.previousBodies[n]?.body:void 0,item_format:o,item_path:v.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function Bf(e){return e.forceSourceScan||_r()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Dt(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||sa(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||sa(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&Hf(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Mt(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=da(),d=ua(t,n,o,c),l=await so(e);l.invalid&&await We(e);let u=await bf(e,d,i.cacheDiagnostics),f=s?await Ef(e,d):null,_=a?await Sf(e,d):null;wf(u,f,_,l.envelope);let y=Df(u,d),g=Nf(f,d),h=Mf(_,d),w=[...new Set(Object.values(n))],b=await En(e,w),I=Object.keys(y),A=Math.max(1,Math.floor(i.derivedIndexMinimumItems??ca));if(Bf({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:d,existingCache:u,existingBodyCache:f,existingCollectionsCache:_,directorySignatures:b,entryKeys:I,minimumIndexedItems:A,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:h}))return qf({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:y,previousBodies:g,previousCollections:h});let L=await Promise.all(w.map(Wt=>Tf(e,Wt,r))),x=_r(),D=Lf(),Q={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:x,previousEntries:y,previousBodies:g,previousCollections:h,state:D};await Pf(L,Q);let ae=await En(e,w),Z=Dt(b,ae)?ae:{},H=D.misses.metadata||Object.keys(y).length!==Object.keys(D.newEntries).length||!Dt(u?.directory_signatures,Z)||u===null?aa():u.source_cursor;return await $f({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCache:u,previousEntries:y,directorySignatures:Z,state:D,minimumIndexedItems:A}),s&&await Ff({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingBodyCache:f,previousBodies:g,state:D}),a&&await jf({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCollectionsCache:_,previousCollections:h,state:D}),Vf(D)}async function fa(e,t,n,r,o){return(await Mt(e,t,n,r,o,{includeBody:!1})).map(i=>({metadata:i.metadata,body:i.body??""}))}async function pa(e,t,n,r,o){return(await Mt(e,t,n,r,o,{includeBody:!1,includeCollections:!1})).map(i=>({metadata:i.metadata,body:i.body??""}))}import he from"node:fs/promises";import{statSync as Wf}from"node:fs";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();function Yf(e,t){let n=-1,r=structuredClone(pt);for(let[a,c]of e.entries()){if(r=Hr(r,c.patch,a+1,c.op),r.metadata.id!==void 0&&r.metadata.id!==t)throw new p(`History belongs to item ${String(r.metadata.id)}, expected ${t}.`,m.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});r.metadata.id===t&&Array.isArray(r.metadata.tags)&&(n=a)}let o=It(e,!0),i=n<0||o===null?null:o+n+1,s=i===null?void 0:String(i);if(n>=0&&s===void 0){let a=e[n].ts;Hs(a,e).historyIndex===n&&(s=a)}return{version:i,target:s}}async function _a(e,t,n){let r=new Set([le(t,n),Ve(t)]);for(let o of r){let i=te(e,o);if(!Wf(i,{throwIfNoEntry:!1})?.isFile())continue;let s=await ft(i,o),a=-1;if(s.forEach((_,y)=>{_.op==="delete"&&(a=y)}),a<0)continue;let c=qs(s,s.length-1);if(Object.keys(c.metadata).length!==0)continue;let{version:d,target:l}=Yf(s,o),u=l===void 0?["history",o,"--verify"]:["get",o,"--at",l],f=q(u);return new p(`Item ${o} was deleted at ${s[a].ts}; its history is retained.`,m.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:o,tombstone:{deleted:!0,deleted_at:s[a].ts,recoverable:l!==void 0,last_materialized_version:d},nextSteps:[f,...l===void 0?["Recover the pre-compaction history from version control."]:[q(["restore",o,l])]],recovery:{suggested_retry:f,suggested_retry_args:u}})}}import{AsyncLocalStorage as Gf}from"node:async_hooks";import ha 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]="c343ed33-0135-5d3a-94a4-67314b295168")}catch{}})();var ya=new Gf;function $v(e,t){return ya.run({...e,pmRoot:ha.resolve(e.pmRoot)},t)}function ga(e,t){let n=ya.getStore();return n?.pmRoot===ha.resolve(e)&&n.itemId===t?{bulk_checkpoint:n.checkpointId}:void 0}import uo from"node:path";import{isUtf8 as Kf}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bc3df8a-c200-52a0-8227-0deda053a955")}catch{}})();async function Xf(e){try{return await he.access(e),!0}catch{return!1}}function Jf(e,t){e&&(e.includes(t)||e.push(t))}function mo(e){return e??Tt(fe())}function Qf(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Ye(e,t,n="pm-",r,o=ee){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=le(t,n),c=Ve(t),d=[...new Set([s,a,c])].filter(f=>f.length>0),l=Object.entries(o),u=Qf(r);for(let f of d){let _=new Map;for(let[y]of l)for(let g of u){let h=$e(e,y,f,g,o);await Xf(h)&&_.set(h,_.get(h)??{id:f,type:y,itemPath:h,item_format:g})}if(_.size>1){let y=[..._.keys()].map(g=>uo.relative(e,g).split(uo.sep).join("/")).sort();throw new p(`Item ${f} has ambiguous identity across ${y.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,m.CONFLICT,{code:"item_identity_ambiguous",item_id:f,paths:y})}for(let y of _.values())return y}return null}async function Lt(e,t={}){let n=await Zf(e,t);if(n.error!==null)throw n.error;return{raw:n.raw,document:n.document}}async function Zf(e,t={}){let n=await he.readFile(e.itemPath);if(!Kf(n))throw new p("Item contains invalid UTF-8; preserve a binary backup before recovering it.",m.CONFLICT,{code:"item_document_encoding_invalid",item_id:e.id,item_path:e.itemPath,byte_length:n.length,empty:!1});let r=n.toString("utf8");await Ee({path:e.itemPath,scope:"project"});let o;try{o=ce(r,{format:e.item_format,requireSupportedFormat:!0,schema:t.schema,extensionFieldNames:mo(t.extensionFieldNames),onWarning:i=>Jf(t.warnings,i)})}catch(i){if(i instanceof p&&i.code==="item_format_version_unsupported")throw new p(`Item ${e.id}: ${i.message}`,i.exitCode,{...i.context,item_id:e.id,item_path:e.itemPath});if(i instanceof p&&i.code==="item_document_invalid")return{raw:r,document:null,error:new p(`Cannot read ${e.id} at ${e.itemPath}${n.length===0?" (zero-length file)":""}: ${i.message}`,i.exitCode,{...i.context,item_id:e.id,item_path:e.itemPath,byte_length:n.length,empty:n.length===0,nextSteps:[`Run pm history ${e.id} --full, then pm restore ${e.id} <version> to recover a recorded state.`]})};throw i}return{raw:r,document:o,error:null}}async function ba(e,t,n=ee,r,o){await on(e);let i=await fa(e,t,n,r,o);return hn(i.length),i.map(s=>s.metadata)}async function ep(e,t,n=ee,r,o){await on(e);let i=await pa(e,t,n,r,o);return hn(i.length),i.map(s=>s.metadata)}async function p0(e,t,n=ee,r,o,i={}){await on(e);let s=await Mt(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan});return hn(s.length),s.map(a=>({...a.metadata,body:a.body}))}function fo(e){return{async get(t){let n=await Ye(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Lt(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>ba(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function tp(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await he.readdir(uo.join(e,o));for(let s of i)for(let a of Gt)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function np(e,t,n,r){let o=le(t,n),i=await tp(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(a=>({id:a,distance:be(a,o,s)})).filter(a=>a.distance!==null).sort((a,c)=>a.distance-c.distance).slice(0,3).map(a=>a.id)}async function Ea(e,t,n,r){let o=await _a(e,t,n);if(o)return o;let i=await np(e,t,n,r),s=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return i.length>0&&s.unshift(`Did you mean one of: ${i.join(", ")}?`),new p(`Item ${t} not found`,m.NOT_FOUND,{code:"item_not_found",id:t,nextSteps:s})}function rp(e,t){return e==="claim"||t===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function Sa(e){let t=e.typeToFolder??it(e.settings,fe()).type_to_folder,n=await Ye(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await Ea(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await wr(e.pmRoot,n.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms,{waitPolicy:"progress"}),o=r.release;try{let i=[],{raw:s,document:a}=await Lt(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:i}),c=a.metadata.assignee?.trim(),d=a.metadata.claim_principal?.trim()||c,l=Er(e.author),u=Vi(e.settings);if(c&&d!==l&&!e.force&&!rp(e.op,e.bypassAssigneeConflict)){if(u.ownership_enforcement==="strict")throw new p(`Item ${n.id} is assigned to ${c}. Use --force to override.`,m.CONFLICT);u.ownership_enforcement==="warn"&&i.push(`ownership_warning:assignee_conflict:${n.id}:${c}`)}return{typeToFolder:t,located:n,originalRaw:s,document:a,warnings:i,releaseLock:o,lease:r}}catch(i){throw await o(),i}}async function va(e,t,n,r){return e.fence(async()=>{let o;try{o=await he.readFile(t.itemPath,"utf8")}catch(i){if(!P(i))throw i;o=null}if(o!==n)throw new p(`Item ${t.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,m.CONFLICT,{code:"stale_revision",item_id:t.id,reason:o===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return r()})}function op(e,t,n){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:t,effectiveSerializedAfter:n,skipItemWrite:!1};let r=e.result;return{effectiveTargetItemPath:typeof r.target_item_path=="string"&&r.target_item_path.trim().length>0?r.target_item_path:t,effectiveSerializedAfter:typeof r.contents=="string"?r.contents:n,skipItemWrite:r.skip_write===!0}}async function Ta(e){try{let t=await Ye(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return{document:cr};let n=ce(await he.readFile(t.itemPath,"utf8"),{format:t.item_format,requireSupportedFormat:!0,schema:e.settings.schema,extensionFieldNames:mo(e.extensionFieldNames)});return n.metadata.id===e.embeddedId?{document:n}:{document:e.fallback,revision:wa}}catch{return{document:e.fallback,revision:wa}}}var wa="unreadable-after-storage-override";async function ip(e){let t=await Zt("item_store_delete",e),n=t.handled&&typeof t.result=="object"&&t.result!==null?t.result:{};return{effectiveItemPath:typeof n.item_path=="string"&&n.item_path.trim().length>0?n.item_path:e.item_path,skipDelete:n.skip_delete===!0,warnings:t.warnings}}async function sp(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await T(e.originalItemPath,e.originalRaw),await he.rm(e.effectiveTargetItemPath,{force:!0});return}await T(e.originalItemPath,e.originalRaw)}}async function po(e){$i(e.op);let t=await Sa({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:n,located:r,originalRaw:o,document:i,warnings:s,releaseLock:a,lease:c}=t;try{Qr(e.pmRoot,i,r.id);let d=je(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=je(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(l);if(e.skipNoop===!0&&u.changedFields.length===0)return{item:d.metadata,body:d.body,changedFields:[],warnings:[...s,...u.warnings??[]]};let f={...e.resolveHistoryContext?.(),...ga(e.pmRoot,r.id),...Js(e.pmRoot,[r.id,i.metadata.id])},_=Math.max(yr(d.metadata),yr(l.metadata));Hi(fr(e.pmRoot),_),_>Pi(l.metadata)&&(l.metadata.pm_format_version=_,u.changedFields.push("pm_format_version")),l.metadata.updated_at=$();let y=je(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=await qr({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:d,after:y});await Qt({pm_root:e.pmRoot,operation:e.op,before:d,after:y,changed_fields:u.changedFields,sdk:fo({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let h=await un({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),w="toon",b=ut(y,{format:w,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),I=$e(e.pmRoot,y.metadata.type,r.id,w,n),A=te(e.pmRoot,r.id),L=await va(c,r,o,async()=>{let Z=await Zt("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:I,history_path:A,item_format:w,before:d,after:y,contents:b}),{effectiveTargetItemPath:H,effectiveSerializedAfter:Wt,skipItemWrite:tt}=op(Z,I,b),Vd=await co(e.pmRoot,e.author),_i=[];try{tt||await T(H,Wt),!tt&&H!==r.itemPath&&await he.rm(r.itemPath);let qd=tn({nowIso:y.metadata.updated_at,author:e.author,op:e.op,before:d,after:y,message:e.message,context:g.decisions.length===0?Object.keys(f).length===0?void 0:f:{...f,workflow_policies:g.decisions}});try{await nn(A,qd)}catch(Bd){throw await sp({skipItemWrite:tt,effectiveTargetItemPath:H,originalItemPath:r.itemPath,originalRaw:o}),Bd}tt||(_i=await lo({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:H,previousItemPath:r.itemPath,document:y}))}finally{await Vd()}let Hd=tt||H!==I||Wt!==b;return{derivedIndexWarnings:_i,effectiveTargetItemPath:H,overrideWarnings:Z.warnings,stored:Hd?await Ta({pmRoot:e.pmRoot,settings:e.settings,id:r.id,typeToFolder:n,extensionFieldNames:e.extensionFieldNames,fallback:y,embeddedId:y.metadata.id}):{document:y}}}),{derivedIndexWarnings:x,effectiveTargetItemPath:D,stored:Q}=L;eo(e.pmRoot,Q.document,r.id,[y.metadata.id],Q.revision);let ae=[...await z({path:D,scope:"project",op:e.op,item_id:y.metadata.id,item_type:y.metadata.type,before:d,after:y,changed_fields:u.changedFields}),...await z({path:A,scope:"project",op:`${e.op}:history`,item_id:y.metadata.id,item_type:y.metadata.type,before:d,after:y,changed_fields:u.changedFields})];return Jt({id:y.metadata.id,op:e.op,item_type:y.metadata.type,previous_status:d.metadata.status,status:y.metadata.status,previous:dt(d.metadata,u.changedFields),current:dt(y.metadata,u.changedFields),changed_fields:u.changedFields}),{item:y.metadata,body:y.body,changedFields:u.changedFields,warnings:[...s,...u.warnings??[],...g.warnings,...h.warnings,...L.overrideWarnings,...x,...ae]}}finally{await a()}}async function ap(e){let{historyContext:t,...n}=e;return po({...n,resolveHistoryContext:()=>t})}async function _0(e){return po(e)}async function cp(e){return po(e)}async function dp(e){let t=await Sa({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:n,originalRaw:r,document:o,warnings:i,releaseLock:s,lease:a}=t;try{Qr(e.pmRoot,o,n.id);let c=mo(void 0),d=je(o,{schema:e.settings.schema,extensionFieldNames:c}),l=await qr({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:d,after:null,dryRun:e.dryRun});await Qt({pm_root:e.pmRoot,operation:"delete",before:d,after:null,changed_fields:["deleted"],sdk:fo({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let u=await un({pmRoot:e.pmRoot,settings:e.settings,itemId:n.id,commandLabel:"delete"}),f=$(),_=cr,y=tn({nowIso:f,author:e.author,op:"delete",before:d,after:_,message:e.message,context:l.decisions.length===0?void 0:{workflow_policies:l.decisions}}),g=te(e.pmRoot,n.id),h=()=>ip({op:"delete",pm_root:e.pmRoot,item_id:n.id,item_path:n.itemPath,history_path:g,before:d});if(e.dryRun===!0){let x=await h();return{item:d.metadata,changedFields:["deleted"],targetPath:x.effectiveItemPath,warnings:[...i,...l.warnings,...u.warnings,...x.warnings]}}let w=await va(a,n,r,async()=>{let{effectiveItemPath:x,skipDelete:D,warnings:Q}=await h(),ae=await co(e.pmRoot,e.author),Z=[];try{D||await he.rm(x);try{await nn(g,y)}catch(H){throw D||await T(x,r),H}D||(Z=await lo({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:x,document:null}))}finally{await ae()}return{derivedIndexWarnings:Z,effectiveItemPath:x,overrideWarnings:Q,stored:D||x!==n.itemPath?await Ta({pmRoot:e.pmRoot,settings:e.settings,id:n.id,typeToFolder:t.typeToFolder,fallback:_,embeddedId:o.metadata.id}):{document:_}}}),{derivedIndexWarnings:b,effectiveItemPath:I,stored:A}=w;eo(e.pmRoot,A.document,n.id,[o.metadata.id],A.revision);let L=[...await z({path:I,scope:"project",op:"delete",item_id:d.metadata.id,item_type:d.metadata.type,before:d,after:_,changed_fields:["deleted"]}),...await z({path:g,scope:"project",op:"delete:history",item_id:d.metadata.id,item_type:d.metadata.type,before:d,after:_,changed_fields:["deleted"]})];return Jt({id:d.metadata.id,op:"delete",item_type:d.metadata.type,previous_status:d.metadata.status,previous:dt(d.metadata,Object.keys(d.metadata)),changed_fields:["deleted"]}),{item:d.metadata,changedFields:["deleted"],warnings:[...i,...l.warnings,...u.warnings,...w.overrideWarnings,...b,...L]}}finally{await s()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b58b44d-819c-5115-b011-f9dfa8e2ab41")}catch{}})();var lp=3e4,Pt=class extends Error{status;constructor(t,n){super(t),this.name="SearchHttpError",this.status=n}};function Ce(e,t,n=lp){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} timeout must be a positive finite number`);return Math.floor(r)}function Ae(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 up(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${S(t)})`}}async function xn(e){let t=new AbortController,n=setTimeout(()=>{t.abort()},e.timeoutMs);try{let r;try{r=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: ${S(o)}`)}if(!r.ok){let o=await up(r),i=o.length>0?`: ${o}`:"";throw new Pt(`${e.requestLabel} failed with status ${r.status} ${r.statusText}${i}`,r.status)}try{return await r.json()}catch(o){throw new Error(`${e.responseLabel} JSON parse failed: ${S(o)}`)}}finally{clearTimeout(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]="5452a392-2477-5028-8aa8-521c6b245f52")}catch{}})();function E0(e,t){let n=E(e);if(!n)return"unconfigured";let r=E(t);return r&&r.toLowerCase()===n.toLowerCase()?"configured":"auto-detected"}function mp(e){let t=at(e),n=t.toLowerCase();return n.endsWith("/embeddings")?t:n.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function Ca(e){let t=e.search?.embedding_model;return E(t)||null}function fp(e){let t=E(e.providers?.openai?.base_url),n=E(e.providers?.openai?.model);if(!t||!n)return null;let r=Ca(e),o=E(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:r??n,...o?{api_key:o}:{}}}function pp(e){let t=E(e.providers?.ollama?.base_url),n=E(e.providers?.ollama?.model);if(!t||!n)return null;let r=Ca(e);return{name:"ollama",base_url:t,model:r??n}}function Aa(e){let t=(Array.isArray(e)?e:[e]).map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new Error("Embedding input must include at least one non-empty string");return t}function _p(e){let t=[],n=[],r=new Map;for(let o of e){let i=r.get(o);if(i===void 0){let s=t.length;t.push(o),r.set(o,s),n.push(s);continue}n.push(i)}return{uniqueInputs:t,originalToUniqueIndex:n}}function hp(e){let t=e.map((n,r)=>({embedding:n.embedding,index:n.index,position:r}));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,r)=>{let o=n.index-r.index;return o!==0?o:n.position-r.position})}return t}function Rn(e){let t=fp(e),n=pp(e),r=[t,n].filter(s=>s!==null),o=E(e.search?.provider),i=o?o.toLowerCase():null;return{active:(i?r.find(s=>s.name===i):void 0)??r[0]??null,available:r}}function Ia(e){let t=at(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:mp(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function yp(e,t){let n=Aa(t);return e.name==="openai"?{target:Ia(e),method:"POST",headers:{"content-type":"application/json",...e.api_key?{authorization:`Bearer ${e.api_key}`}:{}},body:{model:e.model,input:n.length===1?n[0]:n}}:{target:Ia(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:n}}}function gp(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 hp(o).map((i,s)=>{let a=i.embedding;if(!Fe(a))throw new Error(`OpenAI embedding response entry at index ${s} is missing a numeric embedding vector`);return[...a]})}let n=t.embedding;if(Fe(n))return[[...n]];let r=t.embeddings;if(Array.isArray(r)&&r.length>0)return r.map((o,i)=>{if(!Fe(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 xa(e,t,n={}){let r=Ce(n.timeout_ms,"Embedding request"),o=Ae(n.fetcher,"Embedding request"),i=Aa(t),s=_p(i),a=yp(e,s.uniqueInputs),c=await xn({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:r,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),d=gp(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(l=>[...d[l]])}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d563454-0999-5df5-afb9-58503b409436")}catch{}})();var kn=["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 ho(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...kn];let n=new Set(kn),r=Array.from(new Set(t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0&&n.has(o))));return r.length>0?r:[...kn]}var wp=8e3,bp=3200,xe="...[semantic corpus truncated]",Ep="search_embedding_corpus_max_characters_invalid:using_provider_default";function ie(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function Sp(e){return(e.reminders??[]).map(t=>ie([t.at,t.text]))}function vp(e){return(e.events??[]).map(t=>ie([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 Tp(e,t){e.push(t.title,t.body,t.status,t.owner,t.evidence,t.blocked_reason,t.superseded_by);for(let n of t.linked_items??[])e.push(`${n.kind} ${n.id}`,n.note);for(let n of t.files??[])e.push(n.path,n.note);for(let n of t.tests??[])e.push(n.command,n.path,n.note);for(let n of t.docs??[])e.push(n.path,n.note)}function Ip(e,t){for(let n of t.plan_decisions??[])e.push(n.decision,n.rationale,n.evidence);for(let n of t.plan_discoveries??[])e.push(n.text);for(let n of t.plan_validation??[])e.push(n.text,n.command,n.expected)}function T0(e){let t=[];t.push(e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context);for(let n of e.plan_steps??[])Tp(t,n);return Ip(t,e),t.filter(n=>typeof n=="string"&&n.length>0).join(" ")}function Cp(e){let t=(e.plan_steps??[]).map(i=>ie([i.order,i.id,i.title,i.body,i.status,i.owner,i.evidence,i.blocked_reason,i.superseded_by,(i.linked_items??[]).map(s=>ie([s.kind,s.id,s.note])).join(" "),(i.files??[]).map(s=>ie([s.path,s.note])).join(" "),(i.tests??[]).map(s=>ie([s.command,s.path,s.note])).join(" "),(i.docs??[]).map(s=>ie([s.path,s.note])).join(" ")])),n=(e.plan_decisions??[]).map(i=>ie([i.decision,i.rationale,i.evidence,i.step_id])),r=(e.plan_discoveries??[]).map(i=>ie([i.text,i.step_id])),o=(e.plan_validation??[]).map(i=>ie([i.text,i.command,i.expected]));if([e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context,...t,...n,...r,...o].some(i=>i!==void 0))return{mode:e.plan_mode,scope:e.plan_scope,harness:e.plan_harness,resume_context:e.plan_resume_context,steps:t,decisions:n,discoveries:r,validation:o}}function _o(e){return(e??[]).flatMap(t=>Object.prototype.toString.call(t)==="[object Object]"&&typeof t.text=="string"?[t.text]:[])}function oe(e){return typeof e=="string"&&e.trim().length>0}var Ap={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=>oe(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>oe(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>oe(e.metadata.goal)?e.metadata.goal:void 0,value:e=>oe(e.metadata.value)?e.metadata.value:void 0,why_now:e=>oe(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>oe(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=>oe(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>oe(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>oe(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>oe(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>_o(e.metadata.comments),notes:e=>_o(e.metadata.notes),learnings:e=>_o(e.metadata.learnings),reminders:e=>Sp(e.metadata),events:e=>vp(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>Cp(e.metadata)};function Ra(e,t={}){let n=t.fields??kn,r={};for(let o of n){let i=Ap[o];if(!i)continue;let s=i(e);s!==void 0&&(r[o]=s)}return r}function xp(e){return e?.trim().toLowerCase()==="ollama"?bp:wp}function Ge(e,t){let n=xp(e),r=Ri(t);return r!==null?{maxCharacters:r,warning:null}:{maxCharacters:n,warning:t==null?null:Ep}}function yo(e,t={}){let n=JSON.stringify(Ra(e,{fields:t.fields})),r=Ge(t.providerName,t.maxCharacters).maxCharacters;if(n.length<=r)return n;if(r<=xe.length)return xe.slice(0,r);let o=Math.max(0,r-xe.length);return`${n.slice(0,o)}${xe}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67bae1a1-19d1-50ea-816f-4b68e6bb69d9")}catch{}})();function Rp(e,t,n){let r=e.search.embedding_batch_size,o=e.search.embedding_timeout_ms,i=e.search.scanner_max_batch_retries,s=Number.isFinite(r)&&r>0?Math.max(1,Math.floor(r)):1,a=Number.isFinite(o)&&o>0?Math.max(1,Math.floor(o)):3e4,c=Number.isFinite(i)&&i>=0?Math.floor(i):0;return{batchSize:s,timeoutMs:a,maxRetries:c,maxRequestBytes:n,maxInputCharacters:t}}function kp(e,t,n,r){let o=[],i=[],s=Buffer.byteLength(JSON.stringify({model:e.model,input:[]})),a=s;for(let c of t){let d=Buffer.byteLength(JSON.stringify(c.trim()));if(s+d>r)throw new RangeError(`Embedding input exceeds request byte ceiling ${r}; lower search.embedding_corpus_max_characters or raise maxRequestBytes`);let l=i.length>0?1:0;(i.length>=n||a+l+d>r)&&(o.push(i),i=[],a=s),a+=d+(i.length>0?1:0),i.push(c)}return o.push(i),o}function Op(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let n=Math.max(0,t-xe.length);return`${e.slice(0,n)}${xe}`.slice(0,t)}function ka(e){let t=S(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function Dp(e,t,n,r,o,i){let s=`Embedding batch ${t} failed after ${o} attempt(s): ${S(i)}`,a=`provider=${e.name} model=${e.model} batch_size=${n} timeout_ms=${r}`;return ka(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})`}function Np(e){return e instanceof Pt?e.status===413?"payload_too_large":null:ka(e)?"timeout":null}async function go(e,t,n,r,o,i,s){let a=null;for(let c=0;c<=o;c+=1)try{s.requests+=1;let d=await xa(e,t,{timeout_ms:r});return c>0&&i.push(`search_embedding_batch_retry_succeeded:batch=${n}:attempt=${c+1}:size=${t.length}`),s.successful_batches+=1,s.batch_size_histogram[t.length]=(s.batch_size_histogram[t.length]??0)+1,d}catch(d){a=d;let l=Np(d);if(l!==null&&t.length>1){s.split_batches+=1;let u=Math.ceil(t.length/2),f=t.slice(0,u),_=t.slice(u);return i.push(`search_embedding_batch_split_after_${l}:batch=${n}:size=${t.length}:parts=${f.length}|${_.length}`),[...await go(e,f,`${n}.1`,r,o,i,s),...await go(e,_,`${n}.2`,r,o,i,s)]}if(c<o){s.retries+=1;let u=Math.min(1e3*2**c,8e3);await new Promise(f=>setTimeout(f,u))}}throw new Error(Dp(e,n,t.length,r,o+1,a))}async function wo(e,t,n,r={}){if(n.length===0)return{vectors:[],warnings:[]};let o=performance.now(),i=r.maxRequestBytes??262144;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError("maxRequestBytes must be a positive safe integer");let s={provider:e.name,model:e.model,max_request_bytes:i,limit_source:r.maxRequestBytes===void 0?"default":"caller",planned_batches:0,requests:0,successful_batches:0,split_batches:0,retries:0,batch_size_histogram:{},elapsed_ms:0,inputs_per_second:0},a=[],c=Ge(e.name,t.search.embedding_corpus_max_characters);c.warning&&a.push(c.warning);let d=Rp(t,c.maxCharacters,i),l=0,u=n.map(g=>{if(g.trim().length===0)throw new TypeError("Embedding inputs must be non-empty strings");let h=Op(g,d.maxInputCharacters);return h.length<g.length&&(l+=1),h});l>0&&a.push(`search_embedding_input_truncated:count=${l}:max_characters=${d.maxInputCharacters}`);let f=kp(e,u,d.batchSize,d.maxRequestBytes);s.planned_batches=f.length;let _=[],y=0;for(let g=0;g<f.length;g+=1){let h=f[g];r.onProgress?.({batch_index:g+1,batch_total:f.length,batch_size:h.length,completed_inputs:y,total_inputs:u.length,phase:"start"}),_.push(...await go(e,h,String(g+1),d.timeoutMs,d.maxRetries,a,s)),y+=h.length,r.onProgress?.({batch_index:g+1,batch_total:f.length,batch_size:h.length,completed_inputs:y,total_inputs:u.length,phase:"complete"})}return s.elapsed_ms=Math.max(1,performance.now()-o),s.inputs_per_second=n.length*1e3/s.elapsed_ms,{vectors:_,warnings:a,receipt:s}}import{mkdir as Mp,readFile as Lp,stat as So,unlink as Pp}from"node:fs/promises";import{basename as Oa,dirname as bo,isAbsolute as $p,join as Fp,resolve as vo}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]="4f917418-051d-5458-9080-fa23cd36c4d1")}catch{}})();var To="pm_items",jp=/[^a-zA-Z0-9_-]/g,Up=128,zp=".pm-cli-local-vectors",Eo=1,Re=new Map;function Ft(e){return(E(e.collection_name)??To).replaceAll(jp,"_").slice(0,Up)}function On(e){if(!Fe(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function Na(e){if(!Number.isFinite(e)||e<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(e)}function Vp(e){let t=e.result;if(!Array.isArray(t))throw new TypeError("Qdrant query response must include a result array");let n=t.map((r,o)=>{let i=r.id,s=typeof i=="number"?String(i):i,a=E(s);if(!a)throw new Error(`Qdrant query response entry at index ${o} is missing a non-empty id`);let c=r.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=r.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 n.sort((r,o)=>r.score!==o.score?o.score-r.score:r.id.localeCompare(o.id)),n}function Io(e){let t=E(e.result?.status);if(t)return{status:t};let n=E(e.status);if(n)return{status:n};throw new Error("Qdrant upsert response must include status metadata")}async function $t(e,t,n,r,o){return await xn({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:n,fetcher:r,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function Hp(e){let t=E(e.vector_store?.qdrant?.url);if(!t)return null;let n=E(e.vector_store?.collection_name),r=E(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...n&&n!==To?{collection_name:n}:{},...r?{api_key:r}:{}}}function qp(e){let t=vo(e),n=bo(t);return Oa(t)==="pm"&&Oa(n)===".agents"?bo(n):t}function Bp(e,t){return!t||$p(e)?e:vo(qp(t),e)}function Wp(e,t){let n=E(e.vector_store?.lancedb?.path);if(!n)return null;let r=E(e.vector_store?.collection_name);return{name:"lancedb",path:Bp(n,t),...r&&r!==To?{collection_name:r}:{}}}function Yp(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector upsert records must include at least one entry");return e.map((t,n)=>{let r=E(t.id);if(!r)throw new Error(`Vector upsert record at index ${n} is missing a non-empty id`);let o=On(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 ${n} must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}})}function Gp(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector delete ids must include at least one entry");let t=e.map((r,o)=>{let i=E(r);if(!i)throw new Error(`Vector delete id at index ${o} is missing a non-empty value`);return i}).sort((r,o)=>r.localeCompare(o)),n=[];for(let r of t)n.at(-1)!==r&&n.push(r);return n}function Kp(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function Xp(e){return e.replace(/\/points\?wait=true$/,"")}function Dn(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function Nn(e,t){return Ke(e,t)}function Ke(e,t){return Fp(vo(e),zp,`${t}.json`)}function Jp(e,t,n){let r=E(e.id);if(!r)throw new Error(`LanceDB local snapshot '${n}' record at index ${t} is missing a non-empty id`);let o=On(e.vector),i=e.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`LanceDB local snapshot '${n}' record '${r}' must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}}function Qp(e,t,n){let r;try{r=JSON.parse(n)}catch(a){throw new Error(`LanceDB local snapshot at '${e}' is not valid JSON: ${S(a)}`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`LanceDB local snapshot at '${e}' must be a JSON object`);if(r.version!==Eo)throw new Error(`LanceDB local snapshot at '${e}' must include version=${Eo}`);let o=E(r.table);if(!o)throw new Error(`LanceDB local snapshot at '${e}' must include a non-empty table value`);if(o!==t)throw new Error(`LanceDB local snapshot at '${e}' table mismatch: expected '${t}', received '${o}'`);let i=r.records;if(!Array.isArray(i))throw new TypeError(`LanceDB local snapshot at '${e}' must include a records array`);let s=new Map;for(let a=0;a<i.length;a+=1){let c=Jp(i[a],a,e);s.set(c.id,c)}return s}async function Zp(e){try{let t=await So(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!P(t))throw t;return null}}function e_(e,t){if(!t)return null;if(t.mtimeMs===null&&t.size===null&&t.records.size===0)return t.records;let n=new Map;return Re.set(e,{records:n,mtimeMs:null,size:null}),n}function t_(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Co(e,t){let n=Nn(e,t),r=Ke(e,t),o=await Zp(r),i=Re.get(n);if(!o){let a=e_(n,i);if(a)return a}if(t_(i,o))return i.records;let s=new Map;try{let a=await Lp(r,"utf8");s=Qp(r,t,a)}catch(a){if(!P(a))throw a}return Re.set(n,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function n_(e){let t=[...e.values()];return t.sort((n,r)=>n.id.localeCompare(r.id)),t.map(n=>({id:n.id,vector:[...n.vector],...n.payload?{payload:n.payload}:{}}))}async function Ma(e){try{await Pp(e)}catch(t){if(!P(t))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${S(t)}`)}}async function La(e,t,n){let r=Ke(e,t);if(n.size===0){await Ma(r);return}let o=bo(r);try{await Mp(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${S(s)}`)}let i=`${JSON.stringify({version:Eo,table:t,records:n_(n)})}
105
- `;try{await T(r,i)}catch(s){throw new Error(`LanceDB local snapshot write failed at '${r}': ${S(s)}`)}}async function r_(e,t){let n=Nn(e,t),r=Ke(e,t);await Ma(r),Re.delete(n)}function Da(e){let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.sqrt(t)}function o_(e,t){let n=0;for(let i=0;i<e.length;i+=1)n+=e[i]*t[i];let r=Da(e),o=Da(t);return r===0||o===0?0:n/(r*o)}function Mn(e,t){let n=Hp(e),r=Wp(e,t),o=[n,r].filter(a=>a!==null),i=E(e.vector_store?.adapter),s=i?i.toLowerCase():null;return{active:(s?o.find(a=>a.name===s):void 0)??o[0]??null,available:o}}function Ln(e){let t=Ft(e);if(e.name==="qdrant"){let o=at(e.url),i=encodeURIComponent(t);return{store:"qdrant",query_target:`${o}/collections/${i}/points/search`,upsert_target:`${o}/collections/${i}/points?wait=true`}}let n=encodeURIComponent(e.path),r=encodeURIComponent(t);return{store:"lancedb",query_target:`lancedb://${n}#${r}`,upsert_target:`lancedb://${n}#${r}`}}function i_(e,t,n){let r=Ln(e),o=On(t),i=Na(n);return e.name==="qdrant"?{target:r,method:"POST",headers:Dn(e),body:{vector:o,limit:i,with_payload:!0}}:{target:r,method:"LOCAL",headers:{},body:{table:Ft(e),vector:o,limit:i}}}function s_(e,t){let n=Ln(e),r=Yp(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Dn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ft(e),records:r}}}function a_(e,t){let n=Ln(e),r=Gp(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Dn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ft(e),ids:r}}}async function P0(e,t,n,r={}){let o=i_(e,t,n);if(o.method==="LOCAL"){let c=e,d=o.body,l=await Co(c.path,d.table);if(l.size===0)return[];let u=On(d.vector),f=Na(d.limit),_=[],y=0;for(let g of l.values()){if(g.vector.length!==u.length){y++;continue}_.push({id:g.id,score:o_(u,g.vector),...g.payload?{payload:g.payload}:{}})}return y>0&&r.warnings&&r.warnings.push(`vector_dimension_mismatch:${y} records skipped (expected ${u.length} dimensions)`),_.sort((g,h)=>g.score!==h.score?h.score-g.score:g.id.localeCompare(h.id)),_.slice(0,f)}let i=Ce(r.timeout_ms,"Vector request"),s=Ae(r.fetcher,"Vector request"),a=await $t(o.target.query_target,{method:"POST",headers:o.headers,body:o.body},i,s,"query");return Vp(a)}async function Ao(e,t,n={}){let r=s_(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=Nn(a.path,c.table),l=await Co(a.path,c.table);for(let _ of c.records)l.set(_.id,_);await La(a.path,c.table,l);let u=Ke(a.path,c.table),f=await So(u);return Re.set(d,{records:l,mtimeMs:f.mtimeMs,size:f.size}),{status:"ok"}}let o=Ce(n.timeout_ms,"Vector request"),i=Ae(n.fetcher,"Vector request"),s=await $t(r.target.upsert_target,{method:"POST",headers:r.headers,body:r.body},o,i,"upsert");return Io(s)}async function Pn(e,t,n={}){let r=a_(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=Nn(a.path,c.table),l=await Co(a.path,c.table);if(l.size===0)return{status:"ok"};for(let u of c.ids)l.delete(u);if(await La(a.path,c.table,l),l.size===0)Re.delete(d);else{let u=Ke(a.path,c.table),f=await So(u);Re.set(d,{records:l,mtimeMs:f.mtimeMs,size:f.size})}return{status:"ok"}}let o=Ce(n.timeout_ms,"Vector request"),i=Ae(n.fetcher,"Vector request"),s=await $t(Kp(r.target.upsert_target),{method:"POST",headers:r.headers,body:r.body},o,i,"delete");return Io(s)}async function Pa(e,t=[],n={},r){if(e.name==="lancedb")return await r_(e.path,Ft(e)),{status:"ok"};if(r!==void 0){if(!Number.isInteger(r)||r<=0)throw new Error("Vector reset dimension must be a positive integer when provided");let i=Ln(e),s=Xp(i.upsert_target),a=Ce(n.timeout_ms,"Vector request"),c=Ae(n.fetcher,"Vector request"),d=Dn(e);try{await $t(s,{method:"DELETE",headers:d,body:{}},a,c,"delete")}catch(u){if(!S(u).includes("failed with status 404"))throw u}let l=await $t(s,{method:"PUT",headers:d,body:{vectors:{size:r,distance:"Cosine"}}},a,c,"upsert");return Io(l)}let o=t.map(i=>i.trim()).filter(i=>i.length>0);return o.length===0?{status:"ok"}:await Pn(e,o,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]="f8acaac5-64f7-5e22-987e-4eb12a1aa1cf")}catch{}})();function $n(e,t){let n=E(e),r=E(t);return!n||!r?null:{provider:n,model:r}}function $a(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=$n(e.provider,e.model),n=e.vector_dimension;if(!t||typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error("Vectorization embedding metadata must include provider, model, and positive vector_dimension");return{...t,vector_dimension:n}}function xo(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 Ro(e,t){return!e||e.provider!==t.provider||e.model!==t.model}function ko(e,t){return!!(e&&e.vector_dimension!==t)}function Oo(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 r=1;r<e.length;r+=1)if(e[r]?.length!==n)throw new Error(`${t} returned mixed vector dimensions`);return n}import Do 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]="7113dff5-c8e0-5ba6-b0ae-2ff849ed94df")}catch{}})();var c_=["index/manifest.json","search/embeddings.jsonl"],ja="search/vectorization-status.json";function d_(e,t){return`search_cache_invalidation_failed:${e}:${String(t)}`}function Xe(e){return[...new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ua(e){return typeof e=="string"&&e.trim().length>0&&Number.isFinite(Date.parse(e))}function za(e){let t=new Map;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!Ua(r)||t.set(o,r)}return Object.fromEntries([...t.entries()].sort((n,r)=>n[0].localeCompare(r[0])))}async function Va(e){let t=Do.join(e,ja),n=await C(t);if(n===null||n.trim().length===0)return{entries:{},embedding:null,warnings:[]};let r;try{r=JSON.parse(n)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}if(typeof r!="object"||r===null||r.version!==1||!Array.isArray(r.items))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let o=new Map;for(let s of r.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||!Ua(c))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};o.set(a.trim(),c)}let i=null;try{i=$a(r.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 Ha(e,t,n){let r=za(t),o=Do.join(e,ja),i=`${JSON.stringify({version:1,generated_at:$(),...n?{embedding:n}:{},items:Object.entries(r).map(([s,a])=>({id:s,updated_at:a}))},null,2)}
106
- `;await T(o,i)}function l_(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function u_(e){let t=$n(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function jt(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function m_(e,t,n){if(!n.settings&&!await j(we(e)))return jt(t,"search_semantic_refresh_skipped:settings_not_initialized");let r;try{if(n.settings)r=n.settings;else{let a=await Ue(e),c=a.warnings.find(d=>d.startsWith("settings_read_"));if(c)return jt(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);r=a.settings}}catch(a){return jt(t,`search_semantic_refresh_skipped:settings_read_failed:${S(a)}`)}let o=n.apply_runtime_defaults?He(r).settings:r,i=Rn(o).active;if(!i)return jt(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=Mn(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:jt(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function f_(e,t,n,r,o,i){let s=[],a=new Set,c=new Set,d=[];for(let l of r){let u=await Ye(e,l,t,n,o);if(!u){c.add(l);continue}try{let f=await Lt(u,{schema:i});d.push({id:f.document.metadata.id,document:f.document})}catch(f){a.add(u.id),s.push(`search_semantic_refresh_item_read_failed:${u.id}:${S(f)}`)}}return d.sort((l,u)=>l.id.localeCompare(u.id)),{documents:d,missingIds:Xe(c),skippedIds:Xe(a),warnings:s}}async function p_(e,t,n){let r=Ge(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=ho(e),i=n.map(a=>yo(a.document,{providerName:t.name,maxCharacters:r,fields:o})),s=await wo(t,e,i);return{vectors:s.vectors,vector_dimension:Oo(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function __(e,t,n){return await Ao(e,t.map((r,o)=>({id:r.id,vector:n[o],payload:l_(r.document.metadata)}))),{refreshed:t.map(r=>r.id),skipped:[],warnings:[]}}async function h_(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await Pn(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(n){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${S(n)}`]}}}async function y_(e){let t=[],n=[];for(let r of c_){let o=Do.join(e,r);try{if(!await j(o))continue;await rt(o),t.push(r)}catch(i){n.push(d_(r,i))}}return{invalidated:t,warnings:n}}async function Fa(e,t,n={}){let r=Xe(t);if(r.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await m_(e,r,n);if(!("settings"in o))return o;let i=it(o.settings,fe()),s=await f_(e,o.settings.id_prefix,o.settings.item_format,r,i.type_to_folder,o.settings.schema),a=s.documents.length>0||s.missingIds.length>0?await Va(e):{entries:{},embedding:null,warnings:[]},c=u_(o.provider),d=a.entries,l={refreshed:[],skipped:[],warnings:[]},u=a.embedding;if(s.documents.length>0)if(a.embedding&&Ro(a.embedding,c))l={refreshed:[],skipped:s.documents.map(h=>h.id),warnings:["search_semantic_refresh_requires_reindex:embedding_identity_changed"]};else try{let h=await p_(o.settings,o.provider,s.documents);if(ko(a.embedding,h.vector_dimension))l={refreshed:[],skipped:s.documents.map(w=>w.id),warnings:[...h.warnings,"search_semantic_refresh_requires_reindex:vector_dimension_changed"]};else{u=xo(c,h.vector_dimension);let w=await __(o.vectorStore,s.documents,h.vectors);l={refreshed:w.refreshed,skipped:w.skipped,warnings:[...h.warnings,...w.warnings]}}}catch(h){l={refreshed:[],skipped:s.documents.map(w=>w.id),warnings:[`search_semantic_refresh_failed:${S(h)}`]}}let f=await h_(o.vectorStore,s.missingIds),_=new Set(l.refreshed),y=Object.fromEntries(s.documents.filter(h=>_.has(h.id)).map(h=>[h.id,h.document.metadata.updated_at])),g=[];if(Object.keys(y).length>0||s.missingIds.length>0){let h={...d,...za(y)};for(let w of s.missingIds)delete h[w];try{await Ha(e,h,u)}catch(w){g.push(`search_vectorization_status_ledger_write_failed:${S(w)}`)}g.push(...a.warnings)}return{refreshed:Xe([...l.refreshed,...f.refreshed]),skipped:Xe([...s.skippedIds,...l.skipped,...f.skipped]),warnings:[...s.warnings,...l.warnings,...f.warnings,...g]}}function g_(e,t){let n=t?He(e).settings:e;return!!(Rn(n).active&&Mn(n).active)}async function w_(e,t,n={}){let r=await y_(e),o=Xe(t);if(o.length===0)return{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:r.warnings};if(!await j(we(e))){let c=await Fa(e,o);return{invalidated:r.invalidated,refreshed:c.refreshed,skipped:c.skipped,warnings:[...r.warnings,...c.warnings]}}let i;try{let c=await Ue(e),d=c.warnings.find(l=>l.startsWith("settings_read_"));if(d)return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:[...r.warnings,`search_semantic_refresh_skipped:settings_read_failed:${d}`]};i=c.settings}catch(c){return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:[...r.warnings,`search_semantic_refresh_skipped:settings_read_failed:${S(c)}`]}}if(i.search.mutation_refresh_policy==="cache_only")return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:r.warnings};let s=i.search.mutation_refresh_policy==="semantic_auto";if(n.background&&g_(i,s))return await Vs(e,o),{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:[...r.warnings,"search_semantic_refresh_scheduled_background"],scheduled:!0};let a=await Fa(e,o,{settings:i,apply_runtime_defaults:s});return{invalidated:r.invalidated,refreshed:a.refreshed,skipped:a.skipped,warnings:[...r.warnings,...a.warnings]}}import{createHash as b_}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="225abd7e-ddd7-5597-818d-efadc974b7e3")}catch{}})();var E_=new Set(["1","true","yes","on"]),Fn=["user","automation","test","dogfood"],qa=new Set(Fn);function Je(e={},t=process.env,n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let r=(t.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();if(qa.has(r))return{source_context:r,source_context_source:"env_override"};let o=r?"env_override_rejected":"inferred";return jn(t)?{source_context:"test",source_context_source:o}:{source_context:!n||Ut("CI",t)||e.json===!0||e.quiet===!0?"automation":"user",source_context_source:o}}function jn(e=process.env){return typeof e.VITEST=="string"||typeof e.VITEST_WORKER_ID=="string"||typeof e.NODE_TEST_CONTEXT=="string"||(e.NODE_ENV??"").trim().toLowerCase()==="test"}var Un=new Set(["stats","ops stats","list","get","next","context","activity","aggregate"]);function Ba(e,t,n=process.env){let r=n.PM_TELEMETRY_READ_SAMPLE_RATE?.trim();if(!r||!t||!Un.has(e))return 1;let o=Number(r);return Number.isFinite(o)&&o>0&&o<=1?o:1}function Ut(e,t){return E_.has((t[e]??"").trim().toLowerCase())}function U(e=process.env){let t=(e.PM_TELEMETRY_ENDPOINT??"").trim(),n=URL.canParse(t)?new URL(t).protocol:"";return n==="http:"||n==="https:"?{endpoint:t,invalid:!1}:{endpoint:null,invalid:t.length>0}}function zt(e,t=U().endpoint){if(t===null)return e;let n=b_("sha256").update(t).digest("hex").slice(0,16);return e.replace(/\.(jsonl|json)$/u,`.${n}.$1`)}function S_(e){return e.replaceAll(/(\/\/)[^/?#\s]*@/gu,"$1")}function zn(e){let t=e.trim();if(!URL.canParse(t))return S_(t).replace(/[?#].*$/su,"");let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}function Vn(e){return e.replaceAll(/\b[a-z][a-z\d+.-]*:\/\/[^\s"'<>]+/giu,t=>zn(t))}function oT(e,t=process.env){return U(t).endpoint??e}function K(e=process.env){let t=Ut("DO_NOT_TRACK",e),n=U(e),r=(e.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase(),o=jn(e)&&!qa.has(r)&&!Ut("PM_TELEMETRY_SEND_TEST_EVENTS",e);return{telemetry_disabled:t||o||n.invalid||Ut("PM_TELEMETRY_DISABLED",e)||Ut("PM_NO_TELEMETRY",e),do_not_track:t,test_suppressed:o,endpoint_override:n.endpoint===null?null:zn(n.endpoint),endpoint_override_invalid:n.invalid}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a483f454-e261-5232-bae0-da3cdb8c0518")}catch{}})();var ke=Object.freeze({max_bytes:4096,max_depth:8}),Wa=160,v_=new Set(["not_plain_object","unsupported_value","non_finite_number","malformed_unicode","reserved_key","depth_limit","byte_limit","diagnostic_budget"]),Ga=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,T_=new Set(["__proto__"]),M=class extends Error{reason;path;constructor(t,n){super(t),this.reason=t,this.path=n}};function Mo(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function I_(e,t){return/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Ka(e){if(Buffer.byteLength(e,"utf8")<=Wa)return e;let t="",n=Buffer.byteLength("\u2026","utf8");for(let r of e){if(n+=Buffer.byteLength(r,"utf8"),n>Wa)break;t+=r}return`${t}\u2026`}function Hn(e,t,n){if(e.bytes+=t,!(e.bytes<=ke.max_bytes))throw new M("byte_limit",n)}function Xa(e,t,n){if(e.bytes+t>ke.max_bytes)throw new M("byte_limit",n)}function No(e,t,n){let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||!("value"in r))throw new M("unsupported_value",n);return r.value}function C_(e,t,n){if(typeof e=="number"&&!Number.isFinite(e))throw new M("non_finite_number",t);if(typeof e=="string"&&(Xa(n,e.length+2,t),Ga.test(e)))throw new M("malformed_unicode",t);if(e!==null&&!["boolean","number","string"].includes(typeof e))throw new M("unsupported_value",t);return Hn(n,Buffer.byteLength(JSON.stringify(e),"utf8"),t),e}function Ja(e,t,n,r){if(typeof e!="object"||e===null)return C_(e,t,r);if(n>=ke.max_depth)throw new M("depth_limit",t);if(Array.isArray(e)){let o=No(e,"length",t);if(typeof o!="number"||!Number.isSafeInteger(o)||o<0)throw new M("unsupported_value",t);Hn(r,o>0?o+1:2,t);let i=[];for(let s=0;s<o;s+=1){let a=`${t}[${s}]`;i.push(Ja(No(e,String(s),a),a,n+1,r))}return i}if(!Mo(e))throw new M("unsupported_value",t);return Qa(e,t,n+1,r)}function Qa(e,t,n,r){let o=Object.keys(e);Hn(r,o.length>0?o.length+1:2,t);let i={};for(let s of o){Xa(r,s.length+3,t);let a=I_(t,s);if(T_.has(s))throw new M("reserved_key",a);if(Ga.test(s))throw new M("malformed_unicode",a);Hn(r,Buffer.byteLength(JSON.stringify(s),"utf8")+1,a),i[s]=Ja(No(e,s,a),a,n,r)}return i}function A_(e){try{if(e instanceof M)return e}catch{}return new M("unsupported_value","details")}function Bn(e){let t=ke.max_bytes,n={bytes:0};try{if(!Mo(e))throw new M("not_plain_object","details");return{ok:!0,details:Qa(e,"details",0,n),byte_length:n.bytes}}catch(r){let o=A_(r);return{ok:!1,omission:o.reason==="byte_limit"?{reason:"byte_limit",byte_limit:t}:{reason:o.reason,path:Ka(o.path),byte_limit:t}}}}function x_(e){return Bn(e).ok}function Za(e){if(e===void 0)return;let t=Bn(e);return t.ok?{details:t.details}:{details_omitted:t.omission}}function qn(){return{reason:"unsupported_value",path:"details",byte_limit:ke.max_bytes}}function Ya(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n?n.value:void 0}function R_(e){if(!Mo(e))return;let t=Ya(e,"reason");if(typeof t!="string"||!v_.has(t))return;let n=Ya(e,"path"),r=typeof n=="string"?Ka(n):void 0;return{reason:t,...r===void 0?{}:{path:r},byte_limit:ke.max_bytes}}function ec(e){let t={};try{if(typeof e!="object"||e===null||Array.isArray(e))return t;for(let[n,r]of Object.entries(Object.getOwnPropertyDescriptors(e)))r.enumerable&&("value"in r?Object.defineProperty(t,n,{value:r.value,enumerable:!0,writable:!0,configurable:!0}):n==="details"&&(t.details_omitted=qn()));return t}catch{return{}}}function tc(e){if(!(typeof e!="object"||e===null))try{let t=Object.getOwnPropertyDescriptor(e,"details");if(t!==void 0&&!("value"in t))return{details_omitted:qn()};if(t!==void 0&&t.value!==void 0)return Za(t.value);let n=Object.getOwnPropertyDescriptor(e,"details_omitted"),r=n!==void 0&&"value"in n?R_(n.value):void 0;return r===void 0?void 0:{details_omitted:r}}catch{return{details_omitted:qn()}}}var nc=new Set(["details","details_omitted"]);function k_(e){let t={};for(let n of Object.keys(e)){if(nc.has(n)||n==="toJSON")continue;let r=Object.getOwnPropertyDescriptor(e,n);r!==void 0&&"value"in r&&Object.defineProperty(t,n,{value:r.value,enumerable:!0,writable:!0,configurable:!0})}return t}function O_(e){if(typeof e!="object"||e===null)return e;try{return Array.isArray(e)?e:{...k_(e),...tc(e)}}catch{return{details_omitted:qn()}}}function Qe(e){let t={};for(let[n,r]of Object.entries(ec(e)))nc.has(n)||n==="toJSON"||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0});return t}var D_=12,N_=new Set(["context","error_context"]),M_=new Set(["arguments"]);function rc(e){let t=new WeakSet,n=(r,o)=>{if(typeof r!="object"||r===null||o>D_||t.has(r))return;t.add(r);let i=r,s;try{s=Object.keys(i)}catch{return}for(let a of s){let c=Object.getOwnPropertyDescriptor(i,a);if(c===void 0||!("value"in c))continue;let d=c.value,l=N_.has(a)?{}:M_.has(a)?[]:d;l!==d&&(i[a]=l),n(l,o+1)}};n(e,0)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e82bc812-181f-57ab-a29a-61703e8bec1b")}catch{}})();function Lo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function uT(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!Lo(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return Lo(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&Lo(t.feasible_tokens)&&t.reason===void 0;case"unavailable":return t.minimum_feasible_tokens===null&&t.feasible_tokens===null&&["query_cost_limit","search_limit","output_constraints"].includes(t.reason);default:return!1}}var L_="PmCliError";function mT(e){if(!Vt(e)||e.code!=="item_already_exists"||e.exitCode!==m.CONFLICT)return!1;let t=e.context;return typeof t=="object"&&t!==null&&t.code==="item_already_exists"&&typeof t.id=="string"&&t.id.trim().length>0&&typeof t.path=="string"&&t.path.trim().length>0}function P_(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=m.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function $_(e){if(e==null)return{};if(!Object.hasOwn(e,"details"))return e;let t=Object.getOwnPropertyDescriptor(e,"details");if(!("value"in t))throw oc("unsupported_value","details");if(t.value===void 0)return e;let n=Bn(t.value);if(n.ok)return{...e,details:n.details};if(n.omission.reason==="byte_limit"){let{details:r,...o}=e;return{...o,details_omitted:n.omission}}throw oc(n.omission.reason,n.omission.path)}function oc(e,t){let n=new TypeError(`createPmCliExpectedError options.context.details must be plain JSON (${e})`);return Object.defineProperty(n,"path",{value:t,enumerable:!1}),n}function fT(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new p(e,P_(t.exitCode??m.USAGE),$_(t.context));return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Vt(e){try{if(!(e instanceof Error)||e.name!==L_)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)&&typeof t.context=="object"&&t.context!==null&&!Array.isArray(t.context)}catch{return!1}}import{createRequire as W_}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]="64589e00-25ef-5d74-a94a-7d40455e1929")}catch{}})();var Wn=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,F_=new RegExp(`(?:\\b|(?<=_))(${Wn.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");function Yn(e,t,n){let r=t;for(;r>0&&e[r-1]==="\\";)r--;let o=n.length>1;if(o&&r===t)return;let i=o?(t-r)*2:t-r+1,s=1;for(;i%2===0;)s*=2,i/=2;let a=o?String.fromCharCode(Number.parseInt(n.slice(1),16)):n;return{index:r,end:t+n.length,identity:`${a}:${s}`,character:a,width:s}}function sc(e,t){let n=/["']|u(?:0022|0027)/gi;n.lastIndex=t.end;for(let r of e.matchAll(n)){let o=Yn(e,r.index,r[0]);if(o?.identity===t.identity)return o.end}return e.length}function j_(e,t,n,r){let o=e.pop();return o.character!==t.character||o.width!==t.width?r:e.length===0?n:void 0}function U_(e,t){let n=[{character:t.character==="{"?"}":"]",width:t.width}],r=/["'{}[\]]|u(?:0022|0027|007b|007d|005b|005d)/gi;r.lastIndex=t.end;let o;for(;(o=r.exec(e))!==null;){let i=Yn(e,o.index,o[0]);if(!i)continue;let s=i.character;if(s==="{"||s==="["){n.push({character:s==="{"?"}":"]",width:i.width});continue}if(s==="}"||s==="]"){let a=j_(n,i,i.end,e.length);if(a!==void 0)return a;continue}r.lastIndex=sc(e,i)}return e.length}function z_(e,t,n){let r=/^(\\*)(["'{[]|u(?:0022|0027|007b|005b))/i.exec(e.slice(t)),o=r?Yn(e,t+r[1].length,r[2]):void 0;return o?.character==="{"||o?.character==="["?U_(e,o):o?sc(e,o):n}function V_(e){let t=[],n=0;for(let r of e.matchAll(/u([\da-f]{4})/gi)){let o=r.index;for(;o>n&&e[o-1]==="\\";)o--;o!==r.index&&(t.push(e.slice(n,o),String.fromCharCode(Number.parseInt(r[1],16))),n=r.index+r[0].length)}return t.push(e.slice(n)),t.join("")}var ic="(?:\\s|\\\\+u(?:0009|000a|000d|0020))*",H_=new RegExp("^"+ic+"(?::|=|\\\\+u(?:003a|003d))"+ic,"iu");function q_(e,t,n){let r=V_(t);if(!Wn.test(r)&&!/\\u/iu.test(r))return;let o=e.slice(n),i=H_.exec(o);if(!i)return/^\s*\\+u/iu.test(o)?{index:n,start:n,unquotedEnd:e.length,replacement:"[scrubbed]"}:void 0;let s=n+i[0].length,a=/^[^\s,;]+/u.exec(e.slice(s));return a?{index:s,start:s,unquotedEnd:s+a[0].length,replacement:"[scrubbed]"}:void 0}function B_(e){let t=new Map,n=[];for(let r of e.matchAll(/["']|u(?:0022|0027)/gi)){let o=Yn(e,r.index,r[0]);if(!o)continue;let i=t.get(o.identity),s=o.end;if(t.set(o.identity,s),i===void 0)continue;let a=q_(e,e.slice(i,o.index),s);a&&n.push(a)}return n}function ac(e){let t=B_(e);for(let o of e.matchAll(F_)){let i=o.index+o[0].length;t.push({index:o.index,start:i-o[2].length,unquotedEnd:i,replacement:`${o[1]}=[scrubbed]`})}t.sort((o,i)=>o.index-i.index);let n=[],r=0;for(let o of t)o.index<r||(n.push(e.slice(r,o.index),o.replacement),r=z_(e,o.start,o.unquotedEnd));return n.push(e.slice(r)),n.join("")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="85813255-48e1-5b53-913e-27d433c3ff45")}catch{}})();var mc=new Set(["1","true","yes","on"]);function fc(){return!!(mc.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||K().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}var Y_=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,G_=/file:\/\/\/?[^\s"'`),;]+/giu,K_=/\b[A-Za-z]:\\[^\s"'`),;]+/g,X_=/\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,J_=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i;var Q_=["[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 cc(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 W(e,t){if(t&&J_.test(t)&&cc(e))return"[scrubbed_path]";let n=ac(Kt(e)).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(X_,"[scrubbed_ip]").replaceAll(G_,"[scrubbed_path]").replaceAll(K_,"[scrubbed_path]").replaceAll(Y_,(r,o)=>`${o}[scrubbed_path]`);return cc(n)?"[scrubbed_path]":n}function X(e){let t={};for(let[n,r]of Object.entries(e))Wn.test(n)||n.startsWith("sentry.message.parameter.")?t[n]="[scrubbed]":typeof r=="string"?t[n]=W(r,n):Array.isArray(r)?t[n]=r.map(o=>typeof o=="string"?W(o,n):o&&typeof o=="object"?X(o):o):r&&typeof r=="object"?t[n]=X(r):t[n]=r;return t}function Z_(e){for(let n of["filename","absPath","abs_path","module"]){let r=e[n];typeof r=="string"&&(e[n]=W(r,n))}let t=e.context_line;typeof t=="string"&&(e.context_line=W(t,"context_line"));for(let n of["pre_context","post_context"]){let r=e[n];Array.isArray(r)&&(e[n]=r.map(o=>typeof o=="string"?W(o,n):o))}e.vars&&typeof e.vars=="object"&&(e.vars=X(e.vars)),e.data&&typeof e.data=="object"&&(e.data=X(e.data))}var eh=W_(import.meta.url),th=()=>eh("@sentry/node"),Gn,dc=!1,nh=th,rh="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function Po(e){return/^\s*PmCliError:/.test(e)}function $o(e){let t=e.trim().toLowerCase();return t.length===0?!1:Q_.some(n=>t.includes(n))}function oh(e){return e.logger!=="console"?!1:typeof e.message=="string"&&$o(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(t=>typeof t.value=="string"&&$o(t.value))}function ih(e){if(e.logger!=="console")return!1;let t=n=>typeof n=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(n);return t(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(n=>t(n.value))}function sh(e,t){return t instanceof Error?Vt(t):!!(e.exception?.values?.some(n=>n.type==="PmCliError")||e.exception?.values?.some(n=>typeof n.value=="string"&&Po(n.value))||e.logger==="console"&&typeof e.message=="string"&&Po(e.message))}function pc(e){return e.category==="console"&&typeof e.message=="string"&&Po(e.message)}function _c(e){return e.category==="console"&&typeof e.message=="string"&&$o(e.message)}function ah(){return pr(import.meta.url,["../../.."])??"0.0.0"}function ch(){let e=process.env.SENTRY_ENVIRONMENT?.trim();if(e&&e.length>0)return e;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";let t=Je().source_context;return t==="user"?"production":t}var lc=.2;function hc(){let e=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!e)return lc;let t=Number(e);return!Number.isFinite(t)||t<0||t>1?lc:t}function dh(e){if(e.exception?.values){for(let t of e.exception.values)if(t.value&&(t.value=W(t.value,"value")),t.stacktrace?.frames)for(let n of t.stacktrace.frames)Z_(n)}}function yc(e){if(e.breadcrumbs)for(let t of e.breadcrumbs)t.message&&(t.message=W(t.message)),t.data&&typeof t.data=="object"&&(t.data=X(t.data))}function gc(e){if(e.contexts)for(let[t,n]of Object.entries(e.contexts))n&&typeof n=="object"&&(e.contexts[t]=X(n))}function uc(e,t){let n=e,r=n[t];r&&typeof r=="object"&&(n[t]=X(r))}function Fo(e){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(e==="automation"||e==="test"||e==="dogfood"||e==="user"))return e==="user"?"production":e}function wc(e){let t=Fo(e.tags?.["pm.source_context"]);t&&(e.environment=t)}function bc(e,t){let n=lh(e.extra);rc([e.contexts,e.extra,e.breadcrumbs]),uh(e.contexts,t),n!==void 0&&(e.extra.error_context=Qe(n))}function lh(e){if(!(typeof e!="object"||e===null||!Object.hasOwn(e,"error_context")))return e.error_context}function uh(e,t){if(typeof e!="object"||e===null||typeof t!="object"||t===null)return;let n=e,r=new Set(mh(t)),o=fh(t);for(let[i,s]of Object.entries(n))(r.has(i)||typeof s=="object"&&s!==null&&Object.hasOwn(s,"context"))&&(n[i]=o??{})}function mh(e){try{return[e.name,e.constructor?.name].filter(t=>typeof t=="string"&&t.length>0)}catch{return[]}}function fh(e){try{let t=Qe(e),n=Object.getOwnPropertyDescriptor(e,"context");return n!==void 0&&"value"in n&&(t.context=Qe(n.value)),t}catch{return}}var ph=(e,t)=>{if(sh(e,t?.originalException)||oh(e))return null;bc(e,t?.originalException),wc(e),ih(e)&&(e.level="warning",e.tags={...e.tags,"pm.diagnostic_class":"node_runtime_warning"}),e.message&&(e.message=W(e.message,"message")),e.transaction&&(e.transaction=W(e.transaction,"transaction")),dh(e),yc(e),uc(e,"extra"),gc(e);for(let n of["request","user","tags"])uc(e,n);return e},_h=e=>(bc(e),wc(e),e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(t=>!pc(t)&&!_c(t)),yc(e)),gc(e),e),hh=e=>X(e),yh=e=>{if(e.message=W(e.message),e.attributes){let t=Fo(e.attributes["pm.source_context"]);t&&(e.attributes["sentry.environment"]=t),e.attributes=X(e.attributes)}return e};function gh(e){let t=Fo(e["pm.source_context"]?.value);t&&(e["sentry.environment"]={type:"string",value:t})}function wh(e){for(let t of e[1])if(t[0].type==="log")for(let n of t[1].items){n.body=W(n.body);let r=n.attributes;if(r){gh(r);for(let[o,i]of Object.entries(r)){let s=X({[o]:i.value})[o];typeof s=="string"&&(r[o]={type:"string",value:s})}}}}var bh=e=>pc(e)||_c(e)?null:(e.message&&(e.message=W(e.message,"message")),e.data&&typeof e.data=="object"&&(e.data=X(e.data)),e);async function Ec(){if(dc)return Gn;if(dc=!0,fc())return;let e=nh(),t=process.env.SENTRY_DSN?.trim()||rh,n=ah();e.init({dsn:t,release:`pm-cli@${n}`,environment:ch(),tracesSampleRate:hc(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[e.extraErrorDataIntegration({depth:4,captureErrorCause:!1}),e.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":n,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend:ph,beforeSendTransaction:_h,beforeSendSpan:e.withStreamedSpan(hh),beforeSendLog:yh,beforeBreadcrumb:bh});let r=e.getClient();if(!r)return;let o=Je();return e.setTags({"pm.version":n,"pm.source_context":o.source_context,"pm.source_context_source":o.source_context_source}),e.setAttribute("pm.source_context",o.source_context),r.on("beforeEnvelope",wh),Gn=e,e}async function Eh(e){if(e!==!0||!mc.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||hc()===0||fc())return!1;try{return await Ec()!==void 0}catch{return Gn=void 0,!1}}function Oe(){return Gn}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e8ad404-2f8d-5d9b-9046-60178a70e5b2")}catch{}})();var Ht=class extends p{constructor(t,n,r){super(t,m.GENERIC_FAILURE,n),this.name="ExtensionCommandError",Object.defineProperty(this,"cause",{value:r,configurable:!0,writable:!0})}};function CT(e,t){let n=t.warnings[0]??"extension_command_handler_failed",r=t.errorMessage?.trim();return new Ht(`Command "${e}" failed in extension handler (${n}).${r?` ${r}`:""}`,{code:t.errorCode??"command_failed",nextSteps:t.remediation?[t.remediation]:void 0},t.cause)}function AT(e){return e instanceof p||e instanceof Error?e.message:"Unknown failure"}function Sh(e){if(typeof e!="object"||e===null||!("exitCode"in e))return;let t=e.exitCode;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function vh(e){let t=Math.trunc(e);return t>m.SUCCESS?t:m.GENERIC_FAILURE}function xT(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function RT(e,t){if(e instanceof Error)return e;let n=new Error(t),r=Sh(e);return r!==void 0&&(n.exitCode=vh(r)),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]="bd65294f-dfa5-53d2-9691-c630884f2a5f")}catch{}})();var Th=new Set(["init","config","completion","completion-statuses","completion-tags","completion-types"]),Ih=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"]),Ch=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"]),Ah=new Set(["test","test-all","test-runs","test-verify","trace-test","test-ping"]),xh=new Set(["health","validate","normalize","reindex","gc","telemetry","extension-doctor"]);function Rh(e){return e.trim().replaceAll(/\s+/g," ").toLowerCase()}function Sc(e){let t=e?.trim().toLowerCase();return t&&t.length>0?t:void 0}var kh=[{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")}],Oh=new Map([[m.USAGE,"invalid_command_usage"],[m.NOT_FOUND,"item_not_found"],[m.CONFLICT,"lock_conflict"],[m.DEPENDENCY_FAILED,"dependency_failed"]]);function De(e){let t=Rh(e),n=t.length>0?t.split(" "):["<unknown>"],r=n[0],o=n[n.length-1],i="other";return Th.has(r)?i="setup":Ih.has(r)?i="query":Ch.has(r)?i="mutation":Ah.has(r)?i="testing":r==="extension"?i="extension":xh.has(r)&&(i="diagnostics"),{command_path:t.length>0?t:"<unknown>",command_root:r,command_leaf:o,command_depth:n.length,command_family:i}}function jo(e){if(e.ok)return;let t=Sc(e.errorCode);if(t)return t;let n=(e.errorMessage??"").trim().toLowerCase();for(let o of kh)if(o.matches(n))return o.code;let r=Number.isFinite(e.exitCode)?Math.max(0,Math.trunc(e.exitCode)):void 0;return r!==void 0?Oh.get(r)??"command_failed":"command_failed"}function Ze(e){if(e.ok)return"success";let t=Sc(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]="10325dfb-128f-5d83-9163-061d8d8b29b6")}catch{}})();var Ne;function ye(e,t,n){if(n===void 0)return;let r=e;typeof r.setAttribute=="function"&&r.setAttribute(t,n)}function et(e,t,n){typeof n=="string"&&n.trim().length>0&&e.setTag(t,n)}function Dh(e,t,n){e.setTag("pm.ok",t),e.setTag("pm.command_ok",t),typeof n?.exit_code=="number"&&(e.setTag("pm.exit_code",String(n.exit_code)),e.setTag("pm.command_exit_code",String(n.exit_code))),et(e,"pm.error_code",n?.error_code),et(e,"pm.error_category",n?.error_category),et(e,"pm.command_resolution",n?.command_resolution),et(e,"pm.resolution_stage",n?.resolution_stage)}function Nh(e,t,n,r){ye(e,"pm.ok",t),ye(e,"pm.command_ok",t),ye(e,"pm.exit_code",n),ye(e,"pm.command_exit_code",n),ye(e,"pm.error_code",r?.error_code),ye(e,"pm.error_category",r?.error_category),ye(e,"pm.command_resolution",r?.command_resolution),ye(e,"pm.resolution_stage",r?.resolution_stage)}function Mh(e,t,n,r){let o=Oe();if(!o)return;let i=De(e);o.setTag("pm.command",e),o.setTag("pm.command_root",i.command_root),o.setTag("pm.command_family",i.command_family),et(o,"pm.version",r?.pm_version),et(o,"pm.source_context_source",r?.source_context_source),o.setTag("pm.extension.name",r?.extension?.name),o.setTag("pm.extension.version",r?.extension?.version),o.setTag("pm.extension.layer",r?.extension?.layer),typeof r?.source_context=="string"&&r.source_context.trim().length>0&&(o.setTag("pm.source_context",r.source_context),o.setAttribute("pm.source_context",r.source_context));let s=t.map(()=>"[redacted]");o.setContext("pm.command",{name:e,root:i.command_root,leaf:i.command_leaf,family:i.command_family,args:s,option_keys:Object.keys(n).sort(),source_context:r?.source_context,source_context_source:r?.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:r?.source_context}})}function Lh(e){let t=Oe();if(!t)return;let n=De(e);Ne=t.startInactiveSpan({op:"pm.command",name:`pm ${e}`,forceTransaction:!0,attributes:{"pm.command":e,"pm.command_root":n.command_root,"pm.command_family":n.command_family}})}function Ph(){Ne=void 0}function $h(e,t,n){if(!Ne)return;let r=e?"true":"false",o=typeof n?.exit_code=="number"?String(n.exit_code):void 0,i=Oe();i&&Dh(i,r,n),Nh(Ne,r,o,n),Ne.setStatus(e?{code:1}:{code:2,message:t??"command_failed"}),Ne.end(),Ne=void 0}var Fh="unclassified_runtime_error";function jh(e){let t=typeof e=="object"&&e!==null?e:void 0,n=typeof t?.exitCode=="number",r=n?Math.trunc(t?.exitCode):m.GENERIC_FAILURE;return{error_code:typeof t?.code=="string"&&t.code.length>0&&n?t?.code:Fh,exit_code:r}}function Uh(e){let t=jh(e);return{"pm.error_code":t.error_code,"pm.exit_code":String(t.exit_code)}}function zh(e){if(!Hh(e))return;let t=Oe();if(!t)return;let n=Uh(e);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=Qe(e.context)),t.captureException(e,{extra:r,tags:n})}else t.captureException(new Error(String(e)),{tags:n})}function Vh(e){let t=Oe();if(!t)return;let n=e.command_resolution??Ze({ok:!1,errorCode:e.error_code,errorCategory:e.error_category}),r=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":n,"pm.resolution_stage":r,"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":n,"pm.resolution_stage":r,"pm.source_context":e.source_context??"unknown"},extra:o})}function Hh(e){if(e instanceof Ht)return!0;if(e instanceof p||Vt(e)||e instanceof Error&&e.name==="AbortError"&&/(?:ctrl\+[cd]|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([m.SUCCESS,m.USAGE,m.NOT_FOUND,m.CONFLICT]).has(t)}return!0}async function qh(e=3e3){let t=Oe();if(t)try{await t.flush(e)}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]="bab18354-8e62-57c2-872b-f7ef47fcf6d6")}catch{}})();var Me=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,R="[/\\\\]+",Bh="[\\p{L}\\p{N}._@-]+",Le=Bh+"(?:"+R+Me+")*",Kn="(?:(?:home|users)"+R+Le+"|root"+R+Le+")",Wh="[/\\\\]"+Kn,Yh="[/\\\\]{2,}"+Kn,Gh="/?[a-z]:"+R+"users"+R+Le,Kh=Me+"(?: +"+Me+")*",Uo="(?:"+Kh+R+")?users"+R+Le,Xh="[/\\\\]{2,}"+Me+R+Uo,Jh="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+Me+")",Oc="[/\\\\]{2}[?.]"+R+"(?:unc"+R+Me+R+Uo+"|"+Jh+R+"users"+R+Le+")",Qh="file:(?:"+Oc+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+R+")(?:"+Kn+"|[a-z]:"+R+"users"+R+Le+")|[/\\\\]{2}(?:[a-z]:"+R+"users"+R+Le+"|"+Me+R+"(?:"+Kn+"|"+Uo+")))",Zh=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+Wh+"|"+Gh+"|"+Qh+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+Yh+"|"+Xh+"|"+Oc+")","giu"),vc=4,ey=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,ty=new TextDecoder("utf-8");function ny(e){return e.replace(/(?:%[a-f0-9]{2})+/giu,t=>ty.decode(Uint8Array.from(t.matchAll(/%([a-f0-9]{2})/giu),n=>Number.parseInt(n[1],16)))).replace(/%(?![a-f0-9]{2})[a-z0-9]{0,2}/giu,"\uFFFD")}function ry(e){return e.replace(/\\+(?:u([a-f0-9]{4})|x([a-f0-9]{2})|(\/))?/giu,(t,n,r,o)=>{let i=n??r;return i===void 0?o??t:String.fromCharCode(Number.parseInt(i,16))})}function oy(e){return e.normalize("NFKC").replace(/[\p{Bidi_Control}\u200b-\u200f\u2060-\u206f\ufeff]/gu,"").replace(/[\u2215\u2044]/gu,"/").replace(/[\u043e\u041e]/gu,"o").replace(/[\u0455\u0405]/gu,"s")}function iy(e,t){for(let[n,r]of[["percent_decode",ny],["json_unescape",ry],["unicode_fold",oy]]){let o=r(e);o!==e&&!t.includes(n)&&t.push(n),e=o}return e}function*sy(e,t,n){let r=e,o=[];for(let i=0;i<vc;i+=1){let s=r;if(r=iy(r,o),!n){t.lastIndex=0;for(let a of r.matchAll(t))n=!0,yield{index:0,normalizations:[...o]}}if(r===s)break;i===vc-1&&ey.test(r)&&(yield{index:0,normalizations:[...o],normalization_incomplete:!0})}}function*ay(e,t){let n=0;for(let r of e.split(`
107
- `)){t.lastIndex=0;let o=!1;for(let i of r.matchAll(t))o=!0,yield{index:n+i.index};for(let i of sy(r,t,o))yield{...i,index:n};n+=r.length+1}}var Tc="password|passphrase",Ic=/(?:(?!<|\$\{|\$\(|config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))[A-Za-z0-9!@#$%^&*._+\-=]{8,}|"(?!<|\$\{|\$\()[^"]{8,}"|'(?!<|\$\{|\$\()[^']{8,}')/,Cc="token|secret|password|passwd|api[_-]?key",Ac=/["']?([A-Za-z0-9+/=_-]{24,})/,Dc=[{name:"private-key",mutationRule:"private_key",regex:/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/g},{name:"github-token",mutationRule:"github_token",regex:/\b(?:gh[opsru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g},{name:"npm-token",mutationRule:"npm_token",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g},{name:"aws-access-key",mutationRule:"aws_access_key",regex:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g},{name:"google-api-key",mutationRule:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"slack-token",mutationRule:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"anthropic-api-key",mutationRule:"anthropic_api_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"openai-api-key",mutationRule:"openai_api_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"gitlab-token",mutationRule:"gitlab_token",regex:/\bglpat-[A-Za-z0-9_.-]{20,}\b/g},{name:"jwt-like-token",mutationRule:"jwt_like_token",regex:/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g},{name:"npm-auth-token-assignment",mutationRule:"npm_auth_token_assignment",regex:/_authToken\s*=\s*\S+/g},{name:"sentry-user-token",mutationRule:"sentry_user_token",regex:/\bsntryu_[A-Za-z0-9]{20,}\b/g},{name:"sentry-org-token",mutationRule:"sentry_org_token",regex:/\bsntrys_[A-Za-z0-9_-]{20,}\b/g},{name:"private-ip",mutationRule:"private_ip",regex:/\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},{name:"private-ssh-target",mutationRule:"private_ssh_target",regex:/\b(?:ssh|scp|rsync)\s+[A-Za-z0-9._-]+@(?: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},{name:"sshpass-inline-password",mutationRule:"sshpass_inline_password",regex:/\bsshpass\s+-p\s+["'][^"']{6,}["']/g},{name:"password-assignment",mutationRule:"password_assignment",regex:new RegExp(String.raw`\b(?:${Tc})\s*[:=]\s*`+Ic.source,"gi"),structured:{keys:Tc,value:Ic.source,element:!0}},{name:"absolute-home-path",mutationRule:"absolute_home_path",regex:Zh,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",regex:/\b[A-Za-z0-9._-]+@(?: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,excludeFiles:/^(?:tests\/|examples\/)/},{name:"high-entropy-assignment",mutationRule:"high_entropy_assignment",regex:new RegExp(String.raw`\b(?:${Cc})\s*[:=]\s*`+Ac.source,"gi"),structured:{keys:Cc,value:Ac.source},mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.",minimumEntropy:3.5}];function*Nc(e,t){if(e.mutationRule==="absolute_home_path"){yield*ay(t,e.regex);return}e.regex.lastIndex=0;for(let n of t.matchAll(e.regex))Lc(e,n)&&(yield{index:n.index});e.structured&&(yield*by(e,e.structured,t))}var xc=new Map,Rc=/[\r\n\u2028\u2029]/u;function cy(e){let t=`${e.keys}\0${e.value}\0${e.element===!0}`,n=xc.get(t);return n||(n={key:new RegExp(String.raw`\b(?:${e.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(e.value,"iy"),...e.element?{element:new RegExp(String.raw`<(?:${e.keys})(?:\s[^<>]*)?>([^<]*)<\/(?:${e.keys})\s*>`,"gi")}:{}},xc.set(t,n)),n}function Mc(e,t){let n=e[t];for(let r=t+1;r<e.length;r+=1){let o=e[r];if(o==="\\")r+=1;else if(o===n)return{end:r+1,terminated:!0}}return{end:e.length,terminated:!1}}function dy(e,t){return Mc(e,t).end}function ly(e,t,n){return e.at(-1)==="}"?n:t}function uy(e,t,n,r=n){let o=[],i=!1;for(let s=t;s<e.length;s+=1){let a=e[s];switch(a){case"[":case"{":o.push(a==="["?"]":"}"),i=a==="{";break;case"]":case"}":if(o.pop()!==a||o.length===0)return{found:!1,end:s+1};i=!1;break;case",":i=o.at(-1)==="}";break;case":":i=!1;break;case'"':case"'":if(!i&&ly(o,n,r)(s))return{found:!0,end:s};s=dy(e,s)-1;break;default:break}}return{found:!1,end:e.length}}var my=/\\(?:U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-7]{1,3}|[\s\S])/gu,fy={n:`
108
- `,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function kc(e,t){let n=e[0],r=e.slice(1,t?-1:void 0).replaceAll(my,o=>{let i=o[1];if((i==="u"||i==="x")&&o.length>2)return String.fromCharCode(Number.parseInt(o.slice(2),16));if(/^[0-7]$/u.test(i))return String.fromCharCode(Number.parseInt(o.slice(1),8));if(i==="U"&&o.length===10){let s=Number.parseInt(o.slice(2),16);return s<=1114111?String.fromCodePoint(s):"\uFFFD"}return fy[i]??i}).replaceAll(n,n==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," ");return`${n}${r}${t?n:""}`}var py=64;function _y(e,t,n){let r=e[t-1];if(!n)return r!==void 0&&/[\p{L}\p{N}_.-]/u.test(r)?"prefixed":"exact";if(r===n)return"exact";let o=Math.max(0,t-py);for(let i=t-1;i>=o;i-=1){let s=e[i];if(s===n)return"prefixed";if(s===`
109
- `||s==="\r"||s==='"'||s==="'")return"malformed"}return"malformed"}function hy(e,t,n){let r=(s,a)=>{t.lastIndex=a;let c=t.exec(s);return c!==null&&!Rc.test(c[0])&&Lc(e,c)?c:null},o=s=>{if(n[s]!=='"'&&n[s]!=="'")return;let{end:a,terminated:c}=Mc(n,s),d=n.slice(s,a);return d.includes("\\")?Rc.test(d)?[]:(n[s]==="'"?[kc(d,c),d]:[kc(d,c)]).map(l=>r(l,0)).filter(l=>l!==null):void 0},i=s=>{let a=o(s);if(a!==void 0)return a;let c=r(n,s);return c===null?[]:[c]};return{direct:s=>r(n,s)!==null,escaped:s=>(o(s)?.length??0)>0,accepts:s=>a=>i(a).some(c=>!(s&&/\s/u.test(c[0])))}}function*yy(e,t){e.lastIndex=0;for(let n of t.matchAll(e)){let r=n[1].trim();r.length>=8&&!r.startsWith("${")&&!r.startsWith("$(")&&(yield{index:n.index})}}function gy(e,t,n){return t<e.exact||n&&t<e.compact}function wy(e,t,n,r){return(n||e.escaped(r)&&!e.direct(r))&&t(r)}function*by(e,t,n){let r=cy(t),o=hy(e,r.value,n),i=new RegExp(r.key),s={exact:0,compact:0};for(let a=i.exec(n);a;a=i.exec(n)){let c=a[1],d=_y(n,a.index,c);if(d==="malformed")continue;let l=d==="prefixed",u=o.accepts(l),f=a.index+a[0].length,_=n[f];if(_==="["||_==="{"){if(gy(s,f,l))continue;let y=uy(n,f,u,o.accepts(!0));s[l?"compact":"exact"]=y.end,y.found&&(yield{index:a.index})}else wy(o,u,c,f)&&(yield{index:a.index})}r.element&&(yield*yy(r.element,n))}function Lc(e,t){if(e.minimumEntropy===void 0)return!0;let n=t[1],r=new Map;for(let i of n)r.set(i,(r.get(i)??0)+1);let o=0;for(let i of r.values()){let s=i/n.length;o-=s*Math.log2(s)}return o>=e.minimumEntropy}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6059407-bf03-5ae8-8b01-e3e7c5b28030")}catch{}})();var Ey=[{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"}],Vo=new Map(Ey.map(e=>[e.action,e]));function zo(e,t="$",n=new WeakSet){return typeof e=="string"?[{path:t,value:e}]:typeof e!="object"||e===null?[]:n.has(e)?[]:(n.add(e),Array.isArray(e)?e.flatMap((r,o)=>zo(r,`${t}[${o}]`,n)):Object.entries(e).flatMap(([r,o])=>zo(o,`${t}.${r}`,n)))}function Sy(e,t){let n=Nc(e,t),r=n.next().value;if(!r||e.mutationRule!=="absolute_home_path"||r.normalization_incomplete)return r;for(let o of n)if(o.normalization_incomplete)return{...r,normalizations:[...new Set([r.normalizations,o.normalizations].flatMap(i=>i??[]))],normalization_incomplete:!0};return r}function Pc(e){let t=[];for(let n of zo(e))for(let r of Dc){let o=Sy(r,n.value);if(o){let i={rule:r.mutationRule,path:n.path};o.normalizations&&(i.normalizations=o.normalizations),o.normalization_incomplete&&(i.normalization_incomplete=!0),t.push(i)}}return t.filter((n,r,o)=>o.findIndex(i=>i.rule===n.rule&&i.path===n.path)===r)}function vy(e){let t=e.author.trim()||"unknown";if(e.settings.require_attributed_author&&t.toLowerCase()==="unknown")throw new p("Mutation author is required by workspace policy.",m.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 n;try{n=Pc(e.payload)}catch{return{author:t,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(n.length===0)return{author:t,findings:n,warnings:[],override_applied:!1};let r=[...new Set(n.map(o=>o.rule))].sort().join(",");if(e.settings.secret_guard==="block"&&e.force!==!0)throw new p(`Mutation blocked by secret guard (${r}). No detected value was logged.`,m.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:n,warnings:[`secret_guard_detected:${n.length}:rules=${r}`,...e.settings.secret_guard==="block"&&e.force===!0?["secret_guard_force_override"]:[]],override_applied:e.settings.secret_guard==="block"&&e.force===!0}}function Ty(e){return Vo.has(e.trim().toLowerCase())}function Iy(){return[...Vo.keys()].sort((e,t)=>e.localeCompare(t))}function BT(e){return Vo.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]="5767332d-8094-55cd-96e9-47c5d20cd7df")}catch{}})();var Cy=/\b([a-z][a-z0-9]*)-(\d+)(?:-[a-z0-9]+)*\b/giu,Ay=/^(?:utf|iso|sha|tls|http|covid|match)$/iu;function Ho(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Fc(e){return[...new Set(Ho(e).match(/[\p{L}\p{N}]+/gu)??[])]}function $c(e){let t=Ho(e);return{normalized:t,tokens:Fc(t),issueCodes:[...new Set([...e.matchAll(Cy)].filter(n=>{let r=n[1],o=n.index,i=e.slice(o+n[0].length);return!Ay.test(r)&&(r===r.toUpperCase()||r.length<=2||o===0&&/^\s*(?::|—|–|\])/u.test(i))}).map(n=>n[0].toLowerCase()))]}}function xy(e,t){return Ry($c(e),$c(t))}function Ry(e,t){if(e.normalized===t.normalized)return{score:1,reason:"exact_title"};let n=new Set(e.issueCodes);return t.issueCodes.some(r=>n.has(r))?{score:.99,reason:"issue_code"}:{score:Xt(e.tokens,t.tokens),reason:"title_token_jaccard"}}import ky from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7cd1d62-16fe-5e5b-b382-64335fc5e403")}catch{}})();function Xn(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Oy(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,r)=>r.time-n.time)[0]?.value??e.updated_at}function jc(e,t){let n=Math.max(1,Math.trunc(t.threshold_hours)),r=(t.now??new Date).getTime(),o=Xn(t.in_progress_status),i=[];for(let s of e){if(Xn(String(s.status))!==o||(s.assignee?.trim().length??0)>0)continue;let a=Oy(s,t.last_history_activity?.(s)),c=Date.parse(a);if(!Number.isFinite(c))continue;let d=Math.max(0,Math.floor((r-c)/36e5));d>=n&&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:n,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 Dy(e,t,n){let r=new Map;return await Promise.all(t.filter(o=>Xn(String(o.status))===Xn(n.in_progress_status)&&(o.assignee?.trim().length??0)===0).map(async o=>{let i;try{i=await ft(ky.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&&r.set(o.id,s)})),jc(t,{...n,last_history_activity:o=>r.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]="ab644545-f072-53c0-9ebf-72a62c237a2f")}catch{}})();var Ny=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"}),My=/&(?:lt|gt|quot|#39|amp);/g;function Ly(e){return typeof e!="string"||!e.includes("&lt;")&&!e.includes("&gt;")?e:e.replace(My,t=>Ny[t])}function Py(e){return qo(e,new WeakMap)}function qo(e,t){if(typeof e=="string")return Ly(e);if(Array.isArray(e)){if(t.has(e))return t.get(e);let n=[];t.set(e,n);for(let r of e)n.push(qo(r,t));return n}if(e!==null&&typeof e=="object"){if(!$y(e))return e;if(t.has(e))return t.get(e);let n=e,r=Object.create(Object.getPrototypeOf(e));t.set(e,r);for(let[o,i]of Object.entries(n))Object.defineProperty(r,o,{value:qo(i,t),enumerable:!0,writable:!0,configurable:!0});return r}return e}function $y(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]="e7deff0d-d9c9-5250-b172-ab752ddd64a4")}catch{}})();function Fy(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]="bc9e1b59-21cb-5dda-91c0-36e123734cd3")}catch{}})();function Uc(e){return e.split(/[\s,|]+/).map(t=>t.trim()).filter(t=>t.startsWith("--"))}function jy(e){return Uc(e)[0]??null}function Uy(e,t){let n=jy(t);if(n===null)return!1;let r=o=>o.slice(2).replaceAll("-","_");return Uc(e).some(o=>!o.slice(2).includes("-")||n===o?!1:r(n)===r(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4b566486-120f-5aed-8d92-9e62ed996210")}catch{}})();function zy(e,t){if(e==null)return[];let n=t?.separators??/,/,r=e.split(n).map(i=>i.trim()).filter(i=>i.length>0),o=t?.unique!==!1?Array.from(new Set(r)):r;return t?.sort===!0?[...o].sort():o}import Bo from"node:fs/promises";import Jn 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]="12ee7de1-dff4-53f1-8d0d-d8b1c1ebea42")}catch{}})();function Vy(e){return"json_markdown"}function zc(e,t){return Jn.relative(e,t).replaceAll("\\","/")}function Hy(e){return String(e).replaceAll(/[^a-zA-Z0-9._-]+/g,"_").slice(0,120)}async function qy(e,t,n){e!==t&&ce(await Bo.readFile(t,"utf8"),{format:"json_markdown",requireSupportedFormat:!0,schema:n})}async function By(e,t,n="item_format:migrate",r=ee,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=Vy(t),l=Object.entries(r);for(let[u,f]of l){let _=Jn.join(e,f),y=[];try{y=await Bo.readdir(_)}catch{continue}let g=new Map;for(let w of y){let b=Jn.join(_,w),I=st(b);if(!I)continue;let A=Jn.extname(w),L=w.slice(0,w.length-A.length).trim();if(L.length===0)continue;let x=g.get(L)??{};x[I]=b,g.set(L,x)}let h=[...g.keys()].sort((w,b)=>w.localeCompare(b));for(let w of h){let b=g.get(w);c+=1;let I=b[d];if(!I)continue;let A=b[t]??I,L=A===b[t]?t:d;try{let x=await Bo.readFile(A,"utf8"),D=ce(x,{format:L,requireSupportedFormat:!0,schema:o,onWarning:Z=>a.push(`item_format_migration_parse_warning:${w}:${Z}`)});await qy(A,I,o);let Q=$e(e,u,w,t,r),ae=ut(D,{format:t,schema:o});await C(Q)!==ae&&(await T(Q,ae),a.push(...await z({path:Q,scope:"project",op:n})),i.add(w)),await rt(I),s.add(zc(e,I)),a.push(...await z({path:I,scope:"project",op:`${n}:remove`})),i.add(w)}catch(x){a.push(`item_format_migration_skipped:${zc(e,A)}:${Hy(x)}`)}}}return{target_format:t,scanned:c,migrated:[...i].sort((u,f)=>u.localeCompare(f)),removed:[...s].sort((u,f)=>u.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]="12c59406-7e00-5fe1-bd93-c1f9d8537f01")}catch{}})();var Wy=new Set(["completed","superseded"]);function Yy(e){return e!==void 0&&Wy.has(e)}function Gy(e){if(e.type.trim().toLowerCase()!=="plan")return!1;let t=e.plan_steps??[];return t.length>0&&t.every(n=>n.status==="completed")}import{createHash as Ky}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7cbbb50d-e9bc-5940-9ae6-6270e9c2fcbf")}catch{}})();var Xy=/^[a-z][a-z0-9_-]{0,63}$/u,Jy=new Set(["constructor","prototype"]),Vc="settings:section:write",Qy=240;function Qn(e){return`sha256:${Ky("sha256").update(Wo(e)).digest("hex")}`}function Wo(e){return Array.isArray(e)?`[${e.map(t=>Wo(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Wo(Object.getOwnPropertyDescriptor(e,t)?.value)}`).join(",")}}`:String(JSON.stringify(e))}function qc(e){if(!Xy.test(e)||Jy.has(e))throw new p(`Invalid settings section name "${e.slice(0,80)}". Use 1-64 lowercase letters, digits, underscores or hyphens, starting with a letter.`,m.USAGE,{code:"settings_section_name_invalid",field:"section",required:"Name the section after the package, for example lint or jev."});if(zi.includes(e))throw new p(`Settings section "${e}" is owned by core settings; extension sections must use another name.`,m.USAGE,{code:"settings_section_reserved",field:"section",value:e,required:"Read core settings with readSettings and change them with writeSettings or pm config."})}function Bc(e){let t;try{t=JSON.parse(e)}catch{t=void 0}if(typeof t!="object"||t===null||Array.isArray(t))throw new p("settings.json is not a JSON object, so no settings section can be read or written.",m.USAGE,{code:"settings_section_document_malformed",reason:t===void 0?"settings_json_malformed":"settings_json_not_object",nextSteps:["Repair .agents/pm/settings.json so it is a JSON object, then retry.","Run pm health to confirm the settings warning has cleared."]});return t}function Yo(e,t,n){let r;try{r=n===void 0?t:n(t)}catch(o){throw new p(`Settings section "${e}" is invalid: ${S(o).slice(0,Qy)}`,m.USAGE,{code:"settings_section_invalid",field:e,required:`Fix the "${e}" section of .agents/pm/settings.json so the owning package accepts it, then retry.`})}return r}function Wc(e){return typeof Reflect.get(e,"toJSON")=="function"}function Go(e){return e.length===0?"the value":e.join(".")}function Yc(e,t){return Object.values(Object.getOwnPropertyDescriptors(e)).every(n=>"value"in n&&(!t||n.enumerable===!0))}function Zy(e){if(Object.getPrototypeOf(e)!==Array.prototype||!Yc(e,!1))return!1;let t=Object.keys(e);return t.length===e.length&&t.every((n,r)=>n===String(r))&&Object.getOwnPropertyNames(e).length===e.length+1&&Object.getOwnPropertySymbols(e).length===0&&!Wc(e)}function eg(e){let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Yc(e,!0)&&Object.getOwnPropertySymbols(e).length===0&&!Wc(e)}function tg(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return null;let n=Go(t);return typeof e=="number"?Number.isFinite(e)?null:{detail:`${n} is a non-finite number`,representable:!0}:{detail:`${n} is ${typeof e}`,representable:typeof e!="bigint"&&t.length>0}}function Gc(e,t=[],n=new Set){if(typeof e!="object"||e===null)return tg(e,t);let r=Go(t);if(n.has(e))return{detail:`${r} is a circular reference`,representable:!1};if(!(Array.isArray(e)?Zy(e):eg(e)))return{detail:`${r} is not a plain JSON ${Array.isArray(e)?"array":"object"}`,representable:!0};n.add(e);for(let[o,i]of Object.entries(e)){let s=Gc(i,[...t,o],n);if(s!==null)return s}return n.delete(e),null}function Kc(e,t=[]){if(typeof e!="object"||e===null)return null;for(let[n,r]of Object.entries(e)){let o=[...t,n];if(n==="__proto__"||n==="prototype"&&t.at(-1)==="constructor")return Go(o);let i=Kc(r,o);if(i!==null)return i}return null}function Hc(e,t,n){return Yo(e,t,()=>{throw new Error(n)})}function ng(e,t){let n=Gc(t);if(n!==null){let o=n.representable?`the value would change when stored as JSON: ${n.detail}`:`the value is not representable as JSON: ${n.detail}`;return Hc(e,t,o)}let r=Kc(t);return r!==null?Hc(e,t,`${r} is a reserved key that settings history cannot record`):JSON.parse(JSON.stringify(t))}function Xc(e,t){return Object.hasOwn(e,t)?e[t]:void 0}async function rg(e,t,n={}){qc(t);let r=we(e);await Ee({path:r,scope:"project"});let o=await C(r),i=o===null?void 0:Xc(Bc(o),t);if(i===void 0)return{section:t,source:"default",value:n.defaultValue,revision:null};let s=Qn(i);return{section:t,source:"stored",value:Yo(t,structuredClone(i),n.validate),revision:s}}async function og(e,t,n,r={}){qc(t);let o=n===void 0?void 0:ng(t,Yo(t,n,r.validate)),i=we(e),s=await Y(e);try{let a=await vr({pmRoot:e,filePath:i,op:Vc,author:mt(r.author,s.author_default),lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,recordCreation:!1,mutate:c=>{if(c===null)throw new p("settings.json does not exist, so no settings section can be written.",m.NOT_FOUND,{code:"settings_section_document_missing",required:"Initialize the tracker with pm init, then retry."});let d=Bc(c),l=Xc(d,t),u=l===void 0?null:Qn(l);if(r.expectedRevision!==void 0&&r.expectedRevision!==u)throw new p(`Settings section "${t}" changed since it was read; read it again and reapply the change.`,m.CONFLICT,{code:"settings_section_revision_conflict",field:t,expected_revision:r.expectedRevision,current_revision:u,required:"Read the section again with readSettingsSection, then retry with its current revision."});let f={section:t,changed:!1,previous_revision:u,revision:o===void 0?null:Qn(o)};return nt(l,o)?{raw:c,result:f}:(o===void 0?delete d[t]:d[t]=o,{raw:`${JSON.stringify(d,null,2)}
110
- `,result:{...f,changed:!0}})}});return a.changed&&await z({path:i,scope:"project",op:Vc}),a.result}finally{rn(e)}}import ig from"node:readline/promises";import{stdin as sg,stdout as Jc}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]="88db9929-8e1d-56ad-9a5f-6cc0febadfb3")}catch{}})();var ag="PM_TELEMETRY_PROMPT",Qc=new Set(["0","false","no","off"]),cg=new Set(["init","completion","completion-statuses","completion-tags","completion-types"]);function dg(e){return typeof e!="string"?!1:Qc.has(e.trim().toLowerCase())}function lg(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t.length===0?!1:!Qc.has(t)}function ug(e,t){if(t.json===!0||t.quiet===!0||process.stdin.isTTY!==!0||process.stdout.isTTY!==!0||dg(process.env[ag])||lg(process.env.CI))return!0;let n=e.trim().toLowerCase();return n.length===0?!0:cg.has(n)}function mg(e){let t=e.trim().toLowerCase();return!(t==="n"||t==="no")}async function fg(e){let t=`pm telemetry helps improve reliability and usage diagnostics.
104
+ LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(i=>JSON.parse(String(i.metadata_json)));return n.close(),{source_cursor:r.source_cursor,items:o}}catch{return n?.close(),null}}async function bn(e){await Ie.rm(Be(e),{force:!0})}import N from"node:fs/promises";import v from"node:path";import{createHash as df,randomUUID as ua}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();var re=8,ma=500,lf="metadata-derived-index",uf="metadata-cache.json",mf="metadata-cache-bodies.json",ff="metadata-cache-collections.json",pf="metadata-cache-delta.json",_f="metadata-cache-manifest.json",aa=4,hf=["comments","notes","learnings","files","tests","test_runs","docs"];function fa(){return Tt(fe())}function Sn(e){let t={...e},n={};for(let r of hf)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function pa(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function _a(e,t,n,r){let o=df("sha256");o.update(`format:${e??"default"}`);let i=Object.entries(t).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}=${a}`).join(",");return o.update(`|types:${i}`),n&&o.update(`|schema:${JSON.stringify(n)}`),r.length>0&&o.update(`|extension_fields:${r.join(",")}`),o.digest("hex").slice(0,16)}function vn(e){return v.join(e,"runtime",uf)}function Tn(e){return v.join(e,"runtime",mf)}function In(e){return v.join(e,"runtime",ff)}function oo(e){return v.join(e,"runtime",pf)}function io(e){return v.join(e,"runtime",_f)}function Cn(e,t){let n=v.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var yf=24,B=new Map,An=new WeakMap;function so(e){return An.get(e)??e.source_cursor}function gf(e,t){let n=so(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){An.set(e,n);for(let[r,o]of Object.entries(t.changes))o.entry?e.entries[r]=o.entry:delete e.entries[r];e.directory_signatures=t.directory_signatures,e.source_cursor=t.source_cursor}}function wf(e,t){if(!e)return;let n=so(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){An.set(e,n);for(let[r,o]of Object.entries(t.changes))o.body?e.bodies[r]=o.body:delete e.bodies[r];e.source_cursor=t.source_cursor}}function bf(e,t){if(!e)return;let n=so(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){An.set(e,n);for(let[r,o]of Object.entries(t.changes))o.collections?e.collections[r]=o.collections:delete e.collections[r];e.source_cursor=t.source_cursor}}function Ef(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(gf(e,r),wf(t,r),bf(n,r))}function ro(e,t){B.size>=yf&&!B.has(e)&&Oi(B),B.set(e,t)}async function _e(e,t){let n;try{n=await N.stat(e)}catch{return B.delete(e),null}let r=B.get(e);if(r&&kt(r.signature,n.mtimeMs,n.ctimeMs,n.size))return B.delete(e),B.set(e,r),r.envelope;let o;try{o=t(await N.readFile(e,"utf8"))}catch{o=null}return ro(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function Sf(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==re||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=vn(e),i=await _e(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await _e(Cn(o,t),r);return s===null&&Nt(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function vf(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==re||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Tn(e),o=await _e(r,n);return t&&o?.context_fingerprint!==t?await _e(Cn(r,t),n):o}async function Tf(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==re||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=In(e),o=await _e(r,n);return t&&o?.context_fingerprint!==t?await _e(Cn(r,t),n):o}async function ao(e){let t=oo(e),n=await _e(t,r=>{let o=JSON.parse(r);return o.version!==re||typeof o.base_source_cursor!="string"||typeof o.source_cursor!="string"||typeof o.changes!="object"||o.changes===null?null:o});if(n)return{envelope:n,invalid:!1};try{return await N.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function co(e){let t=io(e),n=await _e(t,r=>{let o=JSON.parse(r);return o.version!==re||typeof o.context_fingerprint!="string"||typeof o.source_cursor!="string"||!Number.isInteger(o.entry_count)||o.entry_count<0||typeof o.directory_signatures!="object"||o.directory_signatures===null?null:o});if(n)return n;try{await N.stat(t),await We(e)}catch{}return null}async function Ot(e,t){await N.mkdir(v.dirname(e),{recursive:!0}),await T(e,JSON.stringify(t));try{let r=await N.stat(e);ro(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{B.delete(e)}let n=v.dirname(v.dirname(e));if(e===vn(n)||e===Tn(n)||e===In(n)){let r=Cn(e,t.context_fingerprint);await T(r,JSON.stringify(t));try{let c=await N.stat(r);ro(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{B.delete(r)}let o=v.dirname(e),i=v.extname(e),s=v.basename(e,i),a=(await N.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==v.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>v.join(o,c.name));if(a.length>aa){let c=(await Promise.all(a.map(async d=>{try{return{path:d,mtime:(await N.stat(d)).mtimeMs}}catch{return null}}))).filter(d=>d!==null);for(let d of c.sort((l,u)=>l.mtime-u.mtime).slice(0,Math.max(0,c.length-aa)))await N.rm(d.path,{force:!0}),B.delete(d.path)}}}function If(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function ha(e,t,n){return e===void 0||If(e,t,n)}function Nt(e,t){e&&!e.includes(t)&&e.push(t)}function kt(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function Cf(e,t,n){let r=v.join(e,t);try{let o=await N.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!P(o)&&Nt(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function Af(e,t){try{let n=await N.stat(v.join(e,t));return[t,{exists:!0,mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size}]}catch{return[t,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function En(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await Af(e,n))))}function Dt(e,t){return!e||Object.keys(e).length!==Object.keys(t).length?!1:Object.entries(t).every(([n,r])=>{let o=e[n];return o!==void 0&&o.exists===r.exists&&kt(o,r.mtime_ms,r.ctime_ms,r.size)})}function xf(e){return Gt.some(t=>e.toLowerCase().endsWith(t))}function Rf(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function kf(e,t,n){if(n)for(let r of await Ee({path:e,scope:"project"}))Nt(t,r)}function ca(e,t,n,r){if(e)return t&&n?n.collections:r}async function Of(e,t,n){let r=await N.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=st(e);await kf(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],d=!n.forceSourceRead&&c!==void 0&&kt(c,o,i,s),l=n.previousBodies[t],u=!n.forceSourceRead&&l!==void 0&&kt(l,o,i,s),f=n.previousCollections[t],_=!n.forceSourceRead&&f!==void 0&&kt(f,o,i,s);if(!(!d||n.includeBody&&!u||n.includeCollections&&!_))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:ca(n.includeCollections,_,f,void 0),bodyLength:c.body_length,body:n.includeBody?l.body:void 0};let y=await N.readFile(e,"utf8"),g=ce(y,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:w=>Nt(n.warnings,w)}),h=Sn(g.metadata);return Rf(n.state.misses,n.includeBody,n.includeCollections,d,u,_),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:d?c.metadata:h.light,heavyMetadata:ca(n.includeCollections,_,f,h.heavy),bodyLength:d?c.body_length:g.body.length,body:n.includeBody?g.body:void 0}}function Df(e,t,n,r){n.state.newEntries[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,metadata:r.lightMetadata,body_length:r.bodyLength},n.includeBody&&r.body!==void 0&&(n.state.newBodies[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,body:r.body}),n.includeCollections&&r.heavyMetadata!==void 0&&(n.state.newCollections[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,collections:r.heavyMetadata});let o=n.includeCollections?pa(r.lightMetadata,r.heavyMetadata):r.lightMetadata,i=n.state.documentsById.get(o.id),s={metadata:o,body:r.body,item_format:r.itemFormat,item_path:e};ha(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function Nf(e,t,n,r){try{let o=await Of(t,n,r);Df(t,n,r,o)}catch{Nt(r.warnings,`item_list_item_read_failed:${e}/${v.basename(t)}`)}}function Mf(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function Lf(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function Pf(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function $f(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function Ff(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!xf(s))continue;let a=v.join(o,s),c=v.relative(t.pmRoot,a);n.push(Nf(r,a,c,t)),n.length===32&&(await Promise.all(n),n.length=0)}await Promise.all(n)}async function jf(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Dt(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Ot(vn(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Ot(io(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let t=[...e.state.documentsById.values()].map(({candidate:n})=>({relativePath:v.relative(e.pmRoot,n.item_path),metadata:Sn(n.metadata).light,linkedFiles:n.metadata.files??[]}));t.length>=e.minimumIndexedItems?await ia({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:t}):await bn(e.pmRoot)}catch{}}async function Uf(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await Ot(Tn(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function zf(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await Ot(In(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function lo(e,t,n={}){let r=await co(e);return n.required!==!0&&(r===null||r.entry_count<ma)?async()=>{}:Se(e,lf,30,t,!1,!1,3e3)}async function Iv(e,t){let n=await co(e);if(n===null)return null;let r=await ao(e);if(r.invalid)return await We(e),null;let o=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.source_cursor:n.source_cursor,i=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.directory_signatures:n.directory_signatures;return t&&!Dt(i,await En(e,t))?null:{source_cursor:o,entry_count:n.entry_count}}function da(e,t){let n=v.relative(e,t);return n===""||n===".."||n.startsWith(`..${v.sep}`)||v.isAbsolute(n)?null:n}async function We(e){await Promise.all([vn(e),Tn(e),In(e),oo(e),io(e)].map(async t=>{await N.rm(t,{force:!0}),B.delete(t)})),await bn(e)}async function Vf(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await N.stat(e.mutation.itemPath),n=Sn(e.mutation.document.metadata),r={mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size};return{entry:{...r,metadata:n.light,body_length:e.mutation.document.body.length},body:{...r,body:e.mutation.document.body},collections:{...r,collections:n.heavy}}}function Hf(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function uo(e){let t=da(e.pmRoot,e.itemPath),n=e.previousItemPath?da(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await We(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=_a(e.preferredFormat,e.typeToFolder,e.schema,fa()),o=await co(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await ao(e.pmRoot);if(s.invalid)return await We(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=Hf(s.envelope,r,i),c=s.envelope?.context_fingerprint===r&&s.envelope.base_source_cursor===i?s.envelope.source_cursor:i;n!==void 0&&(a[n]={entry:null,body:null,collections:null}),a[t]=await Vf({mutation:e});let d=ua();return await Ot(oo(e.pmRoot),{version:re,context_fingerprint:r,base_source_cursor:i,source_cursor:d,directory_signatures:await En(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await sa({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:d,row:e.document===null?null:{relativePath:t,metadata:Sn(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await bn(e.pmRoot),[]}catch{return await We(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function qf(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function la(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function Bf(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function Wf(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=st(n);if(!o)continue;let i=e.includeCollections?pa(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);ha(s?.itemFormat,o,e.preferredFormat)&&t.set(i.id,{itemFormat:o,candidate:{metadata:i,body:e.includeBody?e.previousBodies[n]?.body:void 0,item_format:o,item_path:v.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function Yf(e){return e.forceSourceScan||_r()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Dt(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||la(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||la(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&Bf(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Mt(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=fa(),d=_a(t,n,o,c),l=await ao(e);l.invalid&&await We(e);let u=await Sf(e,d,i.cacheDiagnostics),f=s?await vf(e,d):null,_=a?await Tf(e,d):null;Ef(u,f,_,l.envelope);let y=Mf(u,d),g=Lf(f,d),h=Pf(_,d),w=[...new Set(Object.values(n))],b=await En(e,w),I=Object.keys(y),A=Math.max(1,Math.floor(i.derivedIndexMinimumItems??ma));if(Yf({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:d,existingCache:u,existingBodyCache:f,existingCollectionsCache:_,directorySignatures:b,entryKeys:I,minimumIndexedItems:A,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:h}))return Wf({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:y,previousBodies:g,previousCollections:h});let L=await Promise.all(w.map(Wt=>Cf(e,Wt,r))),x=_r(),D=$f(),Q={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:x,previousEntries:y,previousBodies:g,previousCollections:h,state:D};await Ff(L,Q);let ae=await En(e,w),Z=Dt(b,ae)?ae:{},H=D.misses.metadata||Object.keys(y).length!==Object.keys(D.newEntries).length||!Dt(u?.directory_signatures,Z)||u===null?ua():u.source_cursor;return await jf({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCache:u,previousEntries:y,directorySignatures:Z,state:D,minimumIndexedItems:A}),s&&await Uf({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingBodyCache:f,previousBodies:g,state:D}),a&&await zf({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCollectionsCache:_,previousCollections:h,state:D}),qf(D)}async function ya(e,t,n,r,o){return(await Mt(e,t,n,r,o,{includeBody:!1})).map(i=>({metadata:i.metadata,body:i.body??""}))}async function ga(e,t,n,r,o){return(await Mt(e,t,n,r,o,{includeBody:!1,includeCollections:!1})).map(i=>({metadata:i.metadata,body:i.body??""}))}import he from"node:fs/promises";import{statSync as Gf}from"node:fs";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();function Kf(e,t){let n=-1,r=structuredClone(pt);for(let[a,c]of e.entries()){if(r=qr(r,c.patch,a+1,c.op),r.metadata.id!==void 0&&r.metadata.id!==t)throw new p(`History belongs to item ${String(r.metadata.id)}, expected ${t}.`,m.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});r.metadata.id===t&&Array.isArray(r.metadata.tags)&&(n=a)}let o=It(e,!0),i=n<0||o===null?null:o+n+1,s=i===null?void 0:String(i);if(n>=0&&s===void 0){let a=e[n].ts;Ys(a,e).historyIndex===n&&(s=a)}return{version:i,target:s}}async function wa(e,t,n){let r=new Set([le(t,n),Ve(t)]);for(let o of r){let i=te(e,o);if(!Gf(i,{throwIfNoEntry:!1})?.isFile())continue;let s=await ft(i,o),a=-1;if(s.forEach((_,y)=>{_.op==="delete"&&(a=y)}),a<0)continue;let c=Gs(s,s.length-1);if(Object.keys(c.metadata).length!==0)continue;let{version:d,target:l}=Kf(s,o),u=l===void 0?["history",o,"--verify"]:["get",o,"--at",l],f=q(u);return new p(`Item ${o} was deleted at ${s[a].ts}; its history is retained.`,m.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:o,tombstone:{deleted:!0,deleted_at:s[a].ts,recoverable:l!==void 0,last_materialized_version:d},nextSteps:[f,...l===void 0?["Recover the pre-compaction history from version control."]:[q(["restore",o,l])]],recovery:{suggested_retry:f,suggested_retry_args:u}})}}import{AsyncLocalStorage as Xf}from"node:async_hooks";import ba 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]="c343ed33-0135-5d3a-94a4-67314b295168")}catch{}})();var Ea=new Xf;function Uv(e,t){return Ea.run({...e,pmRoot:ba.resolve(e.pmRoot)},t)}function Sa(e,t){let n=Ea.getStore();return n?.pmRoot===ba.resolve(e)&&n.itemId===t?{bulk_checkpoint:n.checkpointId}:void 0}import mo from"node:path";import{isUtf8 as Jf}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bc3df8a-c200-52a0-8227-0deda053a955")}catch{}})();async function Qf(e){try{return await he.access(e),!0}catch{return!1}}function Zf(e,t){e&&(e.includes(t)||e.push(t))}function fo(e){return e??Tt(fe())}function ep(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Ye(e,t,n="pm-",r,o=ee){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=le(t,n),c=Ve(t),d=[...new Set([s,a,c])].filter(f=>f.length>0),l=Object.entries(o),u=ep(r);for(let f of d){let _=new Map;for(let[y]of l)for(let g of u){let h=$e(e,y,f,g,o);await Qf(h)&&_.set(h,_.get(h)??{id:f,type:y,itemPath:h,item_format:g})}if(_.size>1){let y=[..._.keys()].map(g=>mo.relative(e,g).split(mo.sep).join("/")).sort();throw new p(`Item ${f} has ambiguous identity across ${y.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,m.CONFLICT,{code:"item_identity_ambiguous",item_id:f,paths:y})}for(let y of _.values())return y}return null}async function Lt(e,t={}){let n=await tp(e,t);if(n.error!==null)throw n.error;return{raw:n.raw,document:n.document}}async function tp(e,t={}){let n=await he.readFile(e.itemPath);if(!Jf(n))throw new p("Item contains invalid UTF-8; preserve a binary backup before recovering it.",m.CONFLICT,{code:"item_document_encoding_invalid",item_id:e.id,item_path:e.itemPath,byte_length:n.length,empty:!1});let r=n.toString("utf8");await Ee({path:e.itemPath,scope:"project"});let o;try{o=ce(r,{format:e.item_format,requireSupportedFormat:!0,schema:t.schema,extensionFieldNames:fo(t.extensionFieldNames),onWarning:i=>Zf(t.warnings,i)})}catch(i){if(i instanceof p&&i.code==="item_format_version_unsupported")throw new p(`Item ${e.id}: ${i.message}`,i.exitCode,{...i.context,item_id:e.id,item_path:e.itemPath});if(i instanceof p&&i.code==="item_document_invalid")return{raw:r,document:null,error:new p(`Cannot read ${e.id} at ${e.itemPath}${n.length===0?" (zero-length file)":""}: ${i.message}`,i.exitCode,{...i.context,item_id:e.id,item_path:e.itemPath,byte_length:n.length,empty:n.length===0,nextSteps:[`Run pm history ${e.id} --full, then pm restore ${e.id} <version> to recover a recorded state.`]})};throw i}return{raw:r,document:o,error:null}}async function Ta(e,t,n=ee,r,o){await on(e);let i=await ya(e,t,n,r,o);return hn(i.length),i.map(s=>s.metadata)}async function np(e,t,n=ee,r,o){await on(e);let i=await ga(e,t,n,r,o);return hn(i.length),i.map(s=>s.metadata)}async function y0(e,t,n=ee,r,o,i={}){await on(e);let s=await Mt(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan});return hn(s.length),s.map(a=>({...a.metadata,body:a.body}))}function po(e){return{async get(t){let n=await Ye(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Lt(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>Ta(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function rp(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await he.readdir(mo.join(e,o));for(let s of i)for(let a of Gt)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function op(e,t,n,r){let o=le(t,n),i=await rp(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(a=>({id:a,distance:be(a,o,s)})).filter(a=>a.distance!==null).sort((a,c)=>a.distance-c.distance).slice(0,3).map(a=>a.id)}async function Ia(e,t,n,r){let o=await wa(e,t,n);if(o)return o;let i=await op(e,t,n,r),s=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return i.length>0&&s.unshift(`Did you mean one of: ${i.join(", ")}?`),new p(`Item ${t} not found`,m.NOT_FOUND,{code:"item_not_found",id:t,nextSteps:s})}function ip(e,t){return e==="claim"||t===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function Ca(e){let t=e.typeToFolder??it(e.settings,fe()).type_to_folder,n=await Ye(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await Ia(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await wr(e.pmRoot,n.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms,{waitPolicy:"progress"}),o=r.release;try{let i=[],{raw:s,document:a}=await Lt(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:i}),c=a.metadata.assignee?.trim(),d=a.metadata.claim_principal?.trim()||c,l=Er(e.author),u=Hi(e.settings);if(c&&d!==l&&!e.force&&!ip(e.op,e.bypassAssigneeConflict)){if(u.ownership_enforcement==="strict")throw new p(`Item ${n.id} is assigned to ${c}. Use --force to override.`,m.CONFLICT);u.ownership_enforcement==="warn"&&i.push(`ownership_warning:assignee_conflict:${n.id}:${c}`)}return{typeToFolder:t,located:n,originalRaw:s,document:a,warnings:i,releaseLock:o,lease:r}}catch(i){throw await o(),i}}async function Aa(e,t,n,r){return e.fence(async()=>{let o;try{o=await he.readFile(t.itemPath,"utf8")}catch(i){if(!P(i))throw i;o=null}if(o!==n)throw new p(`Item ${t.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,m.CONFLICT,{code:"stale_revision",item_id:t.id,reason:o===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return r()})}function sp(e,t,n){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:t,effectiveSerializedAfter:n,skipItemWrite:!1};let r=e.result;return{effectiveTargetItemPath:typeof r.target_item_path=="string"&&r.target_item_path.trim().length>0?r.target_item_path:t,effectiveSerializedAfter:typeof r.contents=="string"?r.contents:n,skipItemWrite:r.skip_write===!0}}async function xa(e){try{let t=await Ye(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return{document:cr};let n=ce(await he.readFile(t.itemPath,"utf8"),{format:t.item_format,requireSupportedFormat:!0,schema:e.settings.schema,extensionFieldNames:fo(e.extensionFieldNames)});return n.metadata.id===e.embeddedId?{document:n}:{document:e.fallback,revision:va}}catch{return{document:e.fallback,revision:va}}}var va="unreadable-after-storage-override";async function ap(e){let t=await Zt("item_store_delete",e),n=t.handled&&typeof t.result=="object"&&t.result!==null?t.result:{};return{effectiveItemPath:typeof n.item_path=="string"&&n.item_path.trim().length>0?n.item_path:e.item_path,skipDelete:n.skip_delete===!0,warnings:t.warnings}}async function cp(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await T(e.originalItemPath,e.originalRaw),await he.rm(e.effectiveTargetItemPath,{force:!0});return}await T(e.originalItemPath,e.originalRaw)}}async function _o(e){Fi(e.op);let t=await Ca({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:n,located:r,originalRaw:o,document:i,warnings:s,releaseLock:a,lease:c}=t;try{Zr(e.pmRoot,i,r.id);let d=je(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=je(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(l);if(e.skipNoop===!0&&u.changedFields.length===0)return{item:d.metadata,body:d.body,changedFields:[],warnings:[...s,...u.warnings??[]]};let f={...e.resolveHistoryContext?.(),...Sa(e.pmRoot,r.id),...ta(e.pmRoot,[r.id,i.metadata.id])},_=Math.max(yr(d.metadata),yr(l.metadata));qi(fr(e.pmRoot),_),_>$i(l.metadata)&&(l.metadata.pm_format_version=_,u.changedFields.push("pm_format_version")),l.metadata.updated_at=$();let y=je(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=await Br({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:d,after:y});await Qt({pm_root:e.pmRoot,operation:e.op,before:d,after:y,changed_fields:u.changedFields,sdk:po({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let h=await un({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),w="toon",b=ut(y,{format:w,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),I=$e(e.pmRoot,y.metadata.type,r.id,w,n),A=te(e.pmRoot,r.id),L=await Aa(c,r,o,async()=>{let Z=await Zt("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:I,history_path:A,item_format:w,before:d,after:y,contents:b}),{effectiveTargetItemPath:H,effectiveSerializedAfter:Wt,skipItemWrite:tt}=sp(Z,I,b),Wd=await lo(e.pmRoot,e.author),hi=[];try{tt||await T(H,Wt),!tt&&H!==r.itemPath&&await he.rm(r.itemPath);let Gd=tn({nowIso:y.metadata.updated_at,author:e.author,op:e.op,before:d,after:y,message:e.message,context:g.decisions.length===0?Object.keys(f).length===0?void 0:f:{...f,workflow_policies:g.decisions}});try{await nn(A,Gd)}catch(Kd){throw await cp({skipItemWrite:tt,effectiveTargetItemPath:H,originalItemPath:r.itemPath,originalRaw:o}),Kd}tt||(hi=await uo({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:H,previousItemPath:r.itemPath,document:y}))}finally{await Wd()}let Yd=tt||H!==I||Wt!==b;return{derivedIndexWarnings:hi,effectiveTargetItemPath:H,overrideWarnings:Z.warnings,stored:Yd?await xa({pmRoot:e.pmRoot,settings:e.settings,id:r.id,typeToFolder:n,extensionFieldNames:e.extensionFieldNames,fallback:y,embeddedId:y.metadata.id}):{document:y}}}),{derivedIndexWarnings:x,effectiveTargetItemPath:D,stored:Q}=L;to(e.pmRoot,Q.document,r.id,[y.metadata.id],Q.revision);let ae=[...await z({path:D,scope:"project",op:e.op,item_id:y.metadata.id,item_type:y.metadata.type,before:d,after:y,changed_fields:u.changedFields}),...await z({path:A,scope:"project",op:`${e.op}:history`,item_id:y.metadata.id,item_type:y.metadata.type,before:d,after:y,changed_fields:u.changedFields})];return Jt({id:y.metadata.id,op:e.op,item_type:y.metadata.type,previous_status:d.metadata.status,status:y.metadata.status,previous:dt(d.metadata,u.changedFields),current:dt(y.metadata,u.changedFields),changed_fields:u.changedFields}),{item:y.metadata,body:y.body,changedFields:u.changedFields,warnings:[...s,...u.warnings??[],...g.warnings,...h.warnings,...L.overrideWarnings,...x,...ae]}}finally{await a()}}async function dp(e){let{historyContext:t,...n}=e;return _o({...n,resolveHistoryContext:()=>t})}async function g0(e){return _o(e)}async function lp(e){return _o(e)}async function up(e){let t=await Ca({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:n,originalRaw:r,document:o,warnings:i,releaseLock:s,lease:a}=t;try{Zr(e.pmRoot,o,n.id);let c=fo(void 0),d=je(o,{schema:e.settings.schema,extensionFieldNames:c}),l=await Br({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:d,after:null,dryRun:e.dryRun});await Qt({pm_root:e.pmRoot,operation:"delete",before:d,after:null,changed_fields:["deleted"],sdk:po({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let u=await un({pmRoot:e.pmRoot,settings:e.settings,itemId:n.id,commandLabel:"delete"}),f=$(),_=cr,y=tn({nowIso:f,author:e.author,op:"delete",before:d,after:_,message:e.message,context:l.decisions.length===0?void 0:{workflow_policies:l.decisions}}),g=te(e.pmRoot,n.id),h=()=>ap({op:"delete",pm_root:e.pmRoot,item_id:n.id,item_path:n.itemPath,history_path:g,before:d});if(e.dryRun===!0){let x=await h();return{item:d.metadata,changedFields:["deleted"],targetPath:x.effectiveItemPath,warnings:[...i,...l.warnings,...u.warnings,...x.warnings]}}let w=await Aa(a,n,r,async()=>{let{effectiveItemPath:x,skipDelete:D,warnings:Q}=await h(),ae=await lo(e.pmRoot,e.author),Z=[];try{D||await he.rm(x);try{await nn(g,y)}catch(H){throw D||await T(x,r),H}D||(Z=await uo({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:x,document:null}))}finally{await ae()}return{derivedIndexWarnings:Z,effectiveItemPath:x,overrideWarnings:Q,stored:D||x!==n.itemPath?await xa({pmRoot:e.pmRoot,settings:e.settings,id:n.id,typeToFolder:t.typeToFolder,fallback:_,embeddedId:o.metadata.id}):{document:_}}}),{derivedIndexWarnings:b,effectiveItemPath:I,stored:A}=w;to(e.pmRoot,A.document,n.id,[o.metadata.id],A.revision);let L=[...await z({path:I,scope:"project",op:"delete",item_id:d.metadata.id,item_type:d.metadata.type,before:d,after:_,changed_fields:["deleted"]}),...await z({path:g,scope:"project",op:"delete:history",item_id:d.metadata.id,item_type:d.metadata.type,before:d,after:_,changed_fields:["deleted"]})];return Jt({id:d.metadata.id,op:"delete",item_type:d.metadata.type,previous_status:d.metadata.status,previous:dt(d.metadata,Object.keys(d.metadata)),changed_fields:["deleted"]}),{item:d.metadata,changedFields:["deleted"],warnings:[...i,...l.warnings,...u.warnings,...w.overrideWarnings,...b,...L]}}finally{await s()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b58b44d-819c-5115-b011-f9dfa8e2ab41")}catch{}})();var mp=3e4,Pt=class extends Error{status;constructor(t,n){super(t),this.name="SearchHttpError",this.status=n}};function Ce(e,t,n=mp){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} timeout must be a positive finite number`);return Math.floor(r)}function Ae(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 fp(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${S(t)})`}}async function xn(e){let t=new AbortController,n=setTimeout(()=>{t.abort()},e.timeoutMs);try{let r;try{r=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: ${S(o)}`)}if(!r.ok){let o=await fp(r),i=o.length>0?`: ${o}`:"";throw new Pt(`${e.requestLabel} failed with status ${r.status} ${r.statusText}${i}`,r.status)}try{return await r.json()}catch(o){throw new Error(`${e.responseLabel} JSON parse failed: ${S(o)}`)}}finally{clearTimeout(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]="5452a392-2477-5028-8aa8-521c6b245f52")}catch{}})();function T0(e,t){let n=E(e);if(!n)return"unconfigured";let r=E(t);return r&&r.toLowerCase()===n.toLowerCase()?"configured":"auto-detected"}function pp(e){let t=at(e),n=t.toLowerCase();return n.endsWith("/embeddings")?t:n.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function ka(e){let t=e.search?.embedding_model;return E(t)||null}function _p(e){let t=E(e.providers?.openai?.base_url),n=E(e.providers?.openai?.model);if(!t||!n)return null;let r=ka(e),o=E(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:r??n,...o?{api_key:o}:{}}}function hp(e){let t=E(e.providers?.ollama?.base_url),n=E(e.providers?.ollama?.model);if(!t||!n)return null;let r=ka(e);return{name:"ollama",base_url:t,model:r??n}}function Oa(e){let t=(Array.isArray(e)?e:[e]).map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new Error("Embedding input must include at least one non-empty string");return t}function yp(e){let t=[],n=[],r=new Map;for(let o of e){let i=r.get(o);if(i===void 0){let s=t.length;t.push(o),r.set(o,s),n.push(s);continue}n.push(i)}return{uniqueInputs:t,originalToUniqueIndex:n}}function gp(e){let t=e.map((n,r)=>({embedding:n.embedding,index:n.index,position:r}));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,r)=>{let o=n.index-r.index;return o!==0?o:n.position-r.position})}return t}function Rn(e){let t=_p(e),n=hp(e),r=[t,n].filter(s=>s!==null),o=E(e.search?.provider),i=o?o.toLowerCase():null;return{active:(i?r.find(s=>s.name===i):void 0)??r[0]??null,available:r}}function Ra(e){let t=at(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:pp(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function wp(e,t){let n=Oa(t);return e.name==="openai"?{target:Ra(e),method:"POST",headers:{"content-type":"application/json",...e.api_key?{authorization:`Bearer ${e.api_key}`}:{}},body:{model:e.model,input:n.length===1?n[0]:n}}:{target:Ra(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:n}}}function bp(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 gp(o).map((i,s)=>{let a=i.embedding;if(!Fe(a))throw new Error(`OpenAI embedding response entry at index ${s} is missing a numeric embedding vector`);return[...a]})}let n=t.embedding;if(Fe(n))return[[...n]];let r=t.embeddings;if(Array.isArray(r)&&r.length>0)return r.map((o,i)=>{if(!Fe(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 Da(e,t,n={}){let r=Ce(n.timeout_ms,"Embedding request"),o=Ae(n.fetcher,"Embedding request"),i=Oa(t),s=yp(i),a=wp(e,s.uniqueInputs),c=await xn({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:r,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),d=bp(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(l=>[...d[l]])}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d563454-0999-5df5-afb9-58503b409436")}catch{}})();var kn=["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 yo(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...kn];let n=new Set(kn),r=Array.from(new Set(t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0&&n.has(o))));return r.length>0?r:[...kn]}var Ep=8e3,Sp=3200,xe="...[semantic corpus truncated]",vp="search_embedding_corpus_max_characters_invalid:using_provider_default";function ie(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function Tp(e){return(e.reminders??[]).map(t=>ie([t.at,t.text]))}function Ip(e){return(e.events??[]).map(t=>ie([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 Cp(e,t){e.push(t.title,t.body,t.status,t.owner,t.evidence,t.blocked_reason,t.superseded_by);for(let n of t.linked_items??[])e.push(`${n.kind} ${n.id}`,n.note);for(let n of t.files??[])e.push(n.path,n.note);for(let n of t.tests??[])e.push(n.command,n.path,n.note);for(let n of t.docs??[])e.push(n.path,n.note)}function Ap(e,t){for(let n of t.plan_decisions??[])e.push(n.decision,n.rationale,n.evidence);for(let n of t.plan_discoveries??[])e.push(n.text);for(let n of t.plan_validation??[])e.push(n.text,n.command,n.expected)}function A0(e){let t=[];t.push(e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context);for(let n of e.plan_steps??[])Cp(t,n);return Ap(t,e),t.filter(n=>typeof n=="string"&&n.length>0).join(" ")}function xp(e){let t=(e.plan_steps??[]).map(i=>ie([i.order,i.id,i.title,i.body,i.status,i.owner,i.evidence,i.blocked_reason,i.superseded_by,(i.linked_items??[]).map(s=>ie([s.kind,s.id,s.note])).join(" "),(i.files??[]).map(s=>ie([s.path,s.note])).join(" "),(i.tests??[]).map(s=>ie([s.command,s.path,s.note])).join(" "),(i.docs??[]).map(s=>ie([s.path,s.note])).join(" ")])),n=(e.plan_decisions??[]).map(i=>ie([i.decision,i.rationale,i.evidence,i.step_id])),r=(e.plan_discoveries??[]).map(i=>ie([i.text,i.step_id])),o=(e.plan_validation??[]).map(i=>ie([i.text,i.command,i.expected]));if([e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context,...t,...n,...r,...o].some(i=>i!==void 0))return{mode:e.plan_mode,scope:e.plan_scope,harness:e.plan_harness,resume_context:e.plan_resume_context,steps:t,decisions:n,discoveries:r,validation:o}}function ho(e){return(e??[]).flatMap(t=>Object.prototype.toString.call(t)==="[object Object]"&&typeof t.text=="string"?[t.text]:[])}function oe(e){return typeof e=="string"&&e.trim().length>0}var Rp={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=>oe(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>oe(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>oe(e.metadata.goal)?e.metadata.goal:void 0,value:e=>oe(e.metadata.value)?e.metadata.value:void 0,why_now:e=>oe(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>oe(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=>oe(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>oe(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>oe(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>oe(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>ho(e.metadata.comments),notes:e=>ho(e.metadata.notes),learnings:e=>ho(e.metadata.learnings),reminders:e=>Tp(e.metadata),events:e=>Ip(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>xp(e.metadata)};function Na(e,t={}){let n=t.fields??kn,r={};for(let o of n){let i=Rp[o];if(!i)continue;let s=i(e);s!==void 0&&(r[o]=s)}return r}function kp(e){return e?.trim().toLowerCase()==="ollama"?Sp:Ep}function Ge(e,t){let n=kp(e),r=ki(t);return r!==null?{maxCharacters:r,warning:null}:{maxCharacters:n,warning:t==null?null:vp}}function go(e,t={}){let n=JSON.stringify(Na(e,{fields:t.fields})),r=Ge(t.providerName,t.maxCharacters).maxCharacters;if(n.length<=r)return n;if(r<=xe.length)return xe.slice(0,r);let o=Math.max(0,r-xe.length);return`${n.slice(0,o)}${xe}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67bae1a1-19d1-50ea-816f-4b68e6bb69d9")}catch{}})();function Op(e,t,n){let r=e.search.embedding_batch_size,o=e.search.embedding_timeout_ms,i=e.search.scanner_max_batch_retries,s=Number.isFinite(r)&&r>0?Math.max(1,Math.floor(r)):1,a=Number.isFinite(o)&&o>0?Math.max(1,Math.floor(o)):3e4,c=Number.isFinite(i)&&i>=0?Math.floor(i):0;return{batchSize:s,timeoutMs:a,maxRetries:c,maxRequestBytes:n,maxInputCharacters:t}}function Dp(e,t,n,r){let o=[],i=[],s=Buffer.byteLength(JSON.stringify({model:e.model,input:[]})),a=s;for(let c of t){let d=Buffer.byteLength(JSON.stringify(c.trim()));if(s+d>r)throw new RangeError(`Embedding input exceeds request byte ceiling ${r}; lower search.embedding_corpus_max_characters or raise maxRequestBytes`);let l=i.length>0?1:0;(i.length>=n||a+l+d>r)&&(o.push(i),i=[],a=s),a+=d+(i.length>0?1:0),i.push(c)}return o.push(i),o}function Np(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let n=Math.max(0,t-xe.length);return`${e.slice(0,n)}${xe}`.slice(0,t)}function Ma(e){let t=S(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function Mp(e,t,n,r,o,i){let s=`Embedding batch ${t} failed after ${o} attempt(s): ${S(i)}`,a=`provider=${e.name} model=${e.model} batch_size=${n} timeout_ms=${r}`;return Ma(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})`}function Lp(e){return e instanceof Pt?e.status===413?"payload_too_large":null:Ma(e)?"timeout":null}async function wo(e,t,n,r,o,i,s){let a=null;for(let c=0;c<=o;c+=1)try{s.requests+=1;let d=await Da(e,t,{timeout_ms:r});return c>0&&i.push(`search_embedding_batch_retry_succeeded:batch=${n}:attempt=${c+1}:size=${t.length}`),s.successful_batches+=1,s.batch_size_histogram[t.length]=(s.batch_size_histogram[t.length]??0)+1,d}catch(d){a=d;let l=Lp(d);if(l!==null&&t.length>1){s.split_batches+=1;let u=Math.ceil(t.length/2),f=t.slice(0,u),_=t.slice(u);return i.push(`search_embedding_batch_split_after_${l}:batch=${n}:size=${t.length}:parts=${f.length}|${_.length}`),[...await wo(e,f,`${n}.1`,r,o,i,s),...await wo(e,_,`${n}.2`,r,o,i,s)]}if(c<o){s.retries+=1;let u=Math.min(1e3*2**c,8e3);await new Promise(f=>setTimeout(f,u))}}throw new Error(Mp(e,n,t.length,r,o+1,a))}async function bo(e,t,n,r={}){if(n.length===0)return{vectors:[],warnings:[]};let o=performance.now(),i=r.maxRequestBytes??262144;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError("maxRequestBytes must be a positive safe integer");let s={provider:e.name,model:e.model,max_request_bytes:i,limit_source:r.maxRequestBytes===void 0?"default":"caller",planned_batches:0,requests:0,successful_batches:0,split_batches:0,retries:0,batch_size_histogram:{},elapsed_ms:0,inputs_per_second:0},a=[],c=Ge(e.name,t.search.embedding_corpus_max_characters);c.warning&&a.push(c.warning);let d=Op(t,c.maxCharacters,i),l=0,u=n.map(g=>{if(g.trim().length===0)throw new TypeError("Embedding inputs must be non-empty strings");let h=Np(g,d.maxInputCharacters);return h.length<g.length&&(l+=1),h});l>0&&a.push(`search_embedding_input_truncated:count=${l}:max_characters=${d.maxInputCharacters}`);let f=Dp(e,u,d.batchSize,d.maxRequestBytes);s.planned_batches=f.length;let _=[],y=0;for(let g=0;g<f.length;g+=1){let h=f[g];r.onProgress?.({batch_index:g+1,batch_total:f.length,batch_size:h.length,completed_inputs:y,total_inputs:u.length,phase:"start"}),_.push(...await wo(e,h,String(g+1),d.timeoutMs,d.maxRetries,a,s)),y+=h.length,r.onProgress?.({batch_index:g+1,batch_total:f.length,batch_size:h.length,completed_inputs:y,total_inputs:u.length,phase:"complete"})}return s.elapsed_ms=Math.max(1,performance.now()-o),s.inputs_per_second=n.length*1e3/s.elapsed_ms,{vectors:_,warnings:a,receipt:s}}import{mkdir as Pp,readFile as $p,stat as vo,unlink as Fp}from"node:fs/promises";import{basename as La,dirname as Eo,isAbsolute as jp,join as Up,resolve as To}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]="4f917418-051d-5458-9080-fa23cd36c4d1")}catch{}})();var Io="pm_items",zp=/[^a-zA-Z0-9_-]/g,Vp=128,Hp=".pm-cli-local-vectors",So=1,Re=new Map;function Ft(e){return(E(e.collection_name)??Io).replaceAll(zp,"_").slice(0,Vp)}function On(e){if(!Fe(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function $a(e){if(!Number.isFinite(e)||e<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(e)}function qp(e){let t=e.result;if(!Array.isArray(t))throw new TypeError("Qdrant query response must include a result array");let n=t.map((r,o)=>{let i=r.id,s=typeof i=="number"?String(i):i,a=E(s);if(!a)throw new Error(`Qdrant query response entry at index ${o} is missing a non-empty id`);let c=r.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=r.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 n.sort((r,o)=>r.score!==o.score?o.score-r.score:r.id.localeCompare(o.id)),n}function Co(e){let t=E(e.result?.status);if(t)return{status:t};let n=E(e.status);if(n)return{status:n};throw new Error("Qdrant upsert response must include status metadata")}async function $t(e,t,n,r,o){return await xn({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:n,fetcher:r,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function Bp(e){let t=E(e.vector_store?.qdrant?.url);if(!t)return null;let n=E(e.vector_store?.collection_name),r=E(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...n&&n!==Io?{collection_name:n}:{},...r?{api_key:r}:{}}}function Wp(e){let t=To(e),n=Eo(t);return La(t)==="pm"&&La(n)===".agents"?Eo(n):t}function Yp(e,t){return!t||jp(e)?e:To(Wp(t),e)}function Gp(e,t){let n=E(e.vector_store?.lancedb?.path);if(!n)return null;let r=E(e.vector_store?.collection_name);return{name:"lancedb",path:Yp(n,t),...r&&r!==Io?{collection_name:r}:{}}}function Kp(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector upsert records must include at least one entry");return e.map((t,n)=>{let r=E(t.id);if(!r)throw new Error(`Vector upsert record at index ${n} is missing a non-empty id`);let o=On(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 ${n} must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}})}function Xp(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector delete ids must include at least one entry");let t=e.map((r,o)=>{let i=E(r);if(!i)throw new Error(`Vector delete id at index ${o} is missing a non-empty value`);return i}).sort((r,o)=>r.localeCompare(o)),n=[];for(let r of t)n.at(-1)!==r&&n.push(r);return n}function Jp(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function Qp(e){return e.replace(/\/points\?wait=true$/,"")}function Dn(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function Nn(e,t){return Ke(e,t)}function Ke(e,t){return Up(To(e),Hp,`${t}.json`)}function Zp(e,t,n){let r=E(e.id);if(!r)throw new Error(`LanceDB local snapshot '${n}' record at index ${t} is missing a non-empty id`);let o=On(e.vector),i=e.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`LanceDB local snapshot '${n}' record '${r}' must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}}function e_(e,t,n){let r;try{r=JSON.parse(n)}catch(a){throw new Error(`LanceDB local snapshot at '${e}' is not valid JSON: ${S(a)}`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`LanceDB local snapshot at '${e}' must be a JSON object`);if(r.version!==So)throw new Error(`LanceDB local snapshot at '${e}' must include version=${So}`);let o=E(r.table);if(!o)throw new Error(`LanceDB local snapshot at '${e}' must include a non-empty table value`);if(o!==t)throw new Error(`LanceDB local snapshot at '${e}' table mismatch: expected '${t}', received '${o}'`);let i=r.records;if(!Array.isArray(i))throw new TypeError(`LanceDB local snapshot at '${e}' must include a records array`);let s=new Map;for(let a=0;a<i.length;a+=1){let c=Zp(i[a],a,e);s.set(c.id,c)}return s}async function t_(e){try{let t=await vo(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!P(t))throw t;return null}}function n_(e,t){if(!t)return null;if(t.mtimeMs===null&&t.size===null&&t.records.size===0)return t.records;let n=new Map;return Re.set(e,{records:n,mtimeMs:null,size:null}),n}function r_(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ao(e,t){let n=Nn(e,t),r=Ke(e,t),o=await t_(r),i=Re.get(n);if(!o){let a=n_(n,i);if(a)return a}if(r_(i,o))return i.records;let s=new Map;try{let a=await $p(r,"utf8");s=e_(r,t,a)}catch(a){if(!P(a))throw a}return Re.set(n,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function o_(e){let t=[...e.values()];return t.sort((n,r)=>n.id.localeCompare(r.id)),t.map(n=>({id:n.id,vector:[...n.vector],...n.payload?{payload:n.payload}:{}}))}async function Fa(e){try{await Fp(e)}catch(t){if(!P(t))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${S(t)}`)}}async function ja(e,t,n){let r=Ke(e,t);if(n.size===0){await Fa(r);return}let o=Eo(r);try{await Pp(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${S(s)}`)}let i=`${JSON.stringify({version:So,table:t,records:o_(n)})}
105
+ `;try{await T(r,i)}catch(s){throw new Error(`LanceDB local snapshot write failed at '${r}': ${S(s)}`)}}async function i_(e,t){let n=Nn(e,t),r=Ke(e,t);await Fa(r),Re.delete(n)}function Pa(e){let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.sqrt(t)}function s_(e,t){let n=0;for(let i=0;i<e.length;i+=1)n+=e[i]*t[i];let r=Pa(e),o=Pa(t);return r===0||o===0?0:n/(r*o)}function Mn(e,t){let n=Bp(e),r=Gp(e,t),o=[n,r].filter(a=>a!==null),i=E(e.vector_store?.adapter),s=i?i.toLowerCase():null;return{active:(s?o.find(a=>a.name===s):void 0)??o[0]??null,available:o}}function Ln(e){let t=Ft(e);if(e.name==="qdrant"){let o=at(e.url),i=encodeURIComponent(t);return{store:"qdrant",query_target:`${o}/collections/${i}/points/search`,upsert_target:`${o}/collections/${i}/points?wait=true`}}let n=encodeURIComponent(e.path),r=encodeURIComponent(t);return{store:"lancedb",query_target:`lancedb://${n}#${r}`,upsert_target:`lancedb://${n}#${r}`}}function a_(e,t,n){let r=Ln(e),o=On(t),i=$a(n);return e.name==="qdrant"?{target:r,method:"POST",headers:Dn(e),body:{vector:o,limit:i,with_payload:!0}}:{target:r,method:"LOCAL",headers:{},body:{table:Ft(e),vector:o,limit:i}}}function c_(e,t){let n=Ln(e),r=Kp(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Dn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ft(e),records:r}}}function d_(e,t){let n=Ln(e),r=Xp(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Dn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ft(e),ids:r}}}async function j0(e,t,n,r={}){let o=a_(e,t,n);if(o.method==="LOCAL"){let c=e,d=o.body,l=await Ao(c.path,d.table);if(l.size===0)return[];let u=On(d.vector),f=$a(d.limit),_=[],y=0;for(let g of l.values()){if(g.vector.length!==u.length){y++;continue}_.push({id:g.id,score:s_(u,g.vector),...g.payload?{payload:g.payload}:{}})}return y>0&&r.warnings&&r.warnings.push(`vector_dimension_mismatch:${y} records skipped (expected ${u.length} dimensions)`),_.sort((g,h)=>g.score!==h.score?h.score-g.score:g.id.localeCompare(h.id)),_.slice(0,f)}let i=Ce(r.timeout_ms,"Vector request"),s=Ae(r.fetcher,"Vector request"),a=await $t(o.target.query_target,{method:"POST",headers:o.headers,body:o.body},i,s,"query");return qp(a)}async function xo(e,t,n={}){let r=c_(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=Nn(a.path,c.table),l=await Ao(a.path,c.table);for(let _ of c.records)l.set(_.id,_);await ja(a.path,c.table,l);let u=Ke(a.path,c.table),f=await vo(u);return Re.set(d,{records:l,mtimeMs:f.mtimeMs,size:f.size}),{status:"ok"}}let o=Ce(n.timeout_ms,"Vector request"),i=Ae(n.fetcher,"Vector request"),s=await $t(r.target.upsert_target,{method:"POST",headers:r.headers,body:r.body},o,i,"upsert");return Co(s)}async function Pn(e,t,n={}){let r=d_(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=Nn(a.path,c.table),l=await Ao(a.path,c.table);if(l.size===0)return{status:"ok"};for(let u of c.ids)l.delete(u);if(await ja(a.path,c.table,l),l.size===0)Re.delete(d);else{let u=Ke(a.path,c.table),f=await vo(u);Re.set(d,{records:l,mtimeMs:f.mtimeMs,size:f.size})}return{status:"ok"}}let o=Ce(n.timeout_ms,"Vector request"),i=Ae(n.fetcher,"Vector request"),s=await $t(Jp(r.target.upsert_target),{method:"POST",headers:r.headers,body:r.body},o,i,"delete");return Co(s)}async function Ua(e,t=[],n={},r){if(e.name==="lancedb")return await i_(e.path,Ft(e)),{status:"ok"};if(r!==void 0){if(!Number.isInteger(r)||r<=0)throw new Error("Vector reset dimension must be a positive integer when provided");let i=Ln(e),s=Qp(i.upsert_target),a=Ce(n.timeout_ms,"Vector request"),c=Ae(n.fetcher,"Vector request"),d=Dn(e);try{await $t(s,{method:"DELETE",headers:d,body:{}},a,c,"delete")}catch(u){if(!S(u).includes("failed with status 404"))throw u}let l=await $t(s,{method:"PUT",headers:d,body:{vectors:{size:r,distance:"Cosine"}}},a,c,"upsert");return Co(l)}let o=t.map(i=>i.trim()).filter(i=>i.length>0);return o.length===0?{status:"ok"}:await Pn(e,o,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]="f8acaac5-64f7-5e22-987e-4eb12a1aa1cf")}catch{}})();function $n(e,t){let n=E(e),r=E(t);return!n||!r?null:{provider:n,model:r}}function za(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=$n(e.provider,e.model),n=e.vector_dimension;if(!t||typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error("Vectorization embedding metadata must include provider, model, and positive vector_dimension");return{...t,vector_dimension:n}}function Ro(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 ko(e,t){return!e||e.provider!==t.provider||e.model!==t.model}function Oo(e,t){return!!(e&&e.vector_dimension!==t)}function Do(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 r=1;r<e.length;r+=1)if(e[r]?.length!==n)throw new Error(`${t} returned mixed vector dimensions`);return n}import No 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]="7113dff5-c8e0-5ba6-b0ae-2ff849ed94df")}catch{}})();var l_=["index/manifest.json","search/embeddings.jsonl"],Ha="search/vectorization-status.json";function u_(e,t){return`search_cache_invalidation_failed:${e}:${String(t)}`}function Xe(e){return[...new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function qa(e){return typeof e=="string"&&e.trim().length>0&&Number.isFinite(Date.parse(e))}function Ba(e){let t=new Map;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!qa(r)||t.set(o,r)}return Object.fromEntries([...t.entries()].sort((n,r)=>n[0].localeCompare(r[0])))}async function Wa(e){let t=No.join(e,Ha),n=await C(t);if(n===null||n.trim().length===0)return{entries:{},embedding:null,warnings:[]};let r;try{r=JSON.parse(n)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}if(typeof r!="object"||r===null||r.version!==1||!Array.isArray(r.items))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let o=new Map;for(let s of r.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||!qa(c))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};o.set(a.trim(),c)}let i=null;try{i=za(r.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 Ya(e,t,n){let r=Ba(t),o=No.join(e,Ha),i=`${JSON.stringify({version:1,generated_at:$(),...n?{embedding:n}:{},items:Object.entries(r).map(([s,a])=>({id:s,updated_at:a}))},null,2)}
106
+ `;await T(o,i)}function m_(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function f_(e){let t=$n(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function jt(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function p_(e,t,n){if(!n.settings&&!await j(we(e)))return jt(t,"search_semantic_refresh_skipped:settings_not_initialized");let r;try{if(n.settings)r=n.settings;else{let a=await Ue(e),c=a.warnings.find(d=>d.startsWith("settings_read_"));if(c)return jt(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);r=a.settings}}catch(a){return jt(t,`search_semantic_refresh_skipped:settings_read_failed:${S(a)}`)}let o=n.apply_runtime_defaults?He(r).settings:r,i=Rn(o).active;if(!i)return jt(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=Mn(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:jt(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function __(e,t,n,r,o,i){let s=[],a=new Set,c=new Set,d=[];for(let l of r){let u=await Ye(e,l,t,n,o);if(!u){c.add(l);continue}try{let f=await Lt(u,{schema:i});d.push({id:f.document.metadata.id,document:f.document})}catch(f){a.add(u.id),s.push(`search_semantic_refresh_item_read_failed:${u.id}:${S(f)}`)}}return d.sort((l,u)=>l.id.localeCompare(u.id)),{documents:d,missingIds:Xe(c),skippedIds:Xe(a),warnings:s}}async function h_(e,t,n){let r=Ge(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=yo(e),i=n.map(a=>go(a.document,{providerName:t.name,maxCharacters:r,fields:o})),s=await bo(t,e,i);return{vectors:s.vectors,vector_dimension:Do(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function y_(e,t,n){return await xo(e,t.map((r,o)=>({id:r.id,vector:n[o],payload:m_(r.document.metadata)}))),{refreshed:t.map(r=>r.id),skipped:[],warnings:[]}}async function g_(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await Pn(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(n){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${S(n)}`]}}}async function w_(e){let t=[],n=[];for(let r of l_){let o=No.join(e,r);try{if(!await j(o))continue;await rt(o),t.push(r)}catch(i){n.push(u_(r,i))}}return{invalidated:t,warnings:n}}async function Va(e,t,n={}){let r=Xe(t);if(r.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await p_(e,r,n);if(!("settings"in o))return o;let i=it(o.settings,fe()),s=await __(e,o.settings.id_prefix,o.settings.item_format,r,i.type_to_folder,o.settings.schema),a=s.documents.length>0||s.missingIds.length>0?await Wa(e):{entries:{},embedding:null,warnings:[]},c=f_(o.provider),d=a.entries,l={refreshed:[],skipped:[],warnings:[]},u=a.embedding;if(s.documents.length>0)if(a.embedding&&ko(a.embedding,c))l={refreshed:[],skipped:s.documents.map(h=>h.id),warnings:["search_semantic_refresh_requires_reindex:embedding_identity_changed"]};else try{let h=await h_(o.settings,o.provider,s.documents);if(Oo(a.embedding,h.vector_dimension))l={refreshed:[],skipped:s.documents.map(w=>w.id),warnings:[...h.warnings,"search_semantic_refresh_requires_reindex:vector_dimension_changed"]};else{u=Ro(c,h.vector_dimension);let w=await y_(o.vectorStore,s.documents,h.vectors);l={refreshed:w.refreshed,skipped:w.skipped,warnings:[...h.warnings,...w.warnings]}}}catch(h){l={refreshed:[],skipped:s.documents.map(w=>w.id),warnings:[`search_semantic_refresh_failed:${S(h)}`]}}let f=await g_(o.vectorStore,s.missingIds),_=new Set(l.refreshed),y=Object.fromEntries(s.documents.filter(h=>_.has(h.id)).map(h=>[h.id,h.document.metadata.updated_at])),g=[];if(Object.keys(y).length>0||s.missingIds.length>0){let h={...d,...Ba(y)};for(let w of s.missingIds)delete h[w];try{await Ya(e,h,u)}catch(w){g.push(`search_vectorization_status_ledger_write_failed:${S(w)}`)}g.push(...a.warnings)}return{refreshed:Xe([...l.refreshed,...f.refreshed]),skipped:Xe([...s.skippedIds,...l.skipped,...f.skipped]),warnings:[...s.warnings,...l.warnings,...f.warnings,...g]}}function b_(e,t){let n=t?He(e).settings:e;return!!(Rn(n).active&&Mn(n).active)}async function E_(e,t,n={}){let r=await w_(e),o=Xe(t);if(o.length===0)return{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:r.warnings};if(!await j(we(e))){let c=await Va(e,o);return{invalidated:r.invalidated,refreshed:c.refreshed,skipped:c.skipped,warnings:[...r.warnings,...c.warnings]}}let i;try{let c=await Ue(e),d=c.warnings.find(l=>l.startsWith("settings_read_"));if(d)return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:[...r.warnings,`search_semantic_refresh_skipped:settings_read_failed:${d}`]};i=c.settings}catch(c){return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:[...r.warnings,`search_semantic_refresh_skipped:settings_read_failed:${S(c)}`]}}if(i.search.mutation_refresh_policy==="cache_only")return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:r.warnings};let s=i.search.mutation_refresh_policy==="semantic_auto";if(n.background&&b_(i,s))return await Ws(e,o),{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:[...r.warnings,"search_semantic_refresh_scheduled_background"],scheduled:!0};let a=await Va(e,o,{settings:i,apply_runtime_defaults:s});return{invalidated:r.invalidated,refreshed:a.refreshed,skipped:a.skipped,warnings:[...r.warnings,...a.warnings]}}import{createHash as S_}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="225abd7e-ddd7-5597-818d-efadc974b7e3")}catch{}})();var v_=new Set(["1","true","yes","on"]),Fn=["user","automation","test","dogfood"],Ga=new Set(Fn);function Je(e={},t=process.env,n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let r=(t.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();if(Ga.has(r))return{source_context:r,source_context_source:"env_override"};let o=r?"env_override_rejected":"inferred";return jn(t)?{source_context:"test",source_context_source:o}:{source_context:!n||Ut("CI",t)||e.json===!0||e.quiet===!0?"automation":"user",source_context_source:o}}function jn(e=process.env){return typeof e.VITEST=="string"||typeof e.VITEST_WORKER_ID=="string"||typeof e.NODE_TEST_CONTEXT=="string"||(e.NODE_ENV??"").trim().toLowerCase()==="test"}var Un=new Set(["stats","ops stats","list","get","next","context","activity","aggregate"]);function Ka(e,t,n=process.env){let r=n.PM_TELEMETRY_READ_SAMPLE_RATE?.trim();if(!r||!t||!Un.has(e))return 1;let o=Number(r);return Number.isFinite(o)&&o>0&&o<=1?o:1}function Ut(e,t){return v_.has((t[e]??"").trim().toLowerCase())}function U(e=process.env){let t=(e.PM_TELEMETRY_ENDPOINT??"").trim(),n=URL.canParse(t)?new URL(t).protocol:"";return n==="http:"||n==="https:"?{endpoint:t,invalid:!1}:{endpoint:null,invalid:t.length>0}}function zt(e,t=U().endpoint){if(t===null)return e;let n=S_("sha256").update(t).digest("hex").slice(0,16);return e.replace(/\.(jsonl|json)$/u,`.${n}.$1`)}function T_(e){return e.replaceAll(/(\/\/)[^/?#\s]*@/gu,"$1")}function zn(e){let t=e.trim();if(!URL.canParse(t))return T_(t).replace(/[?#].*$/su,"");let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}function Vn(e){return e.replaceAll(/\b[a-z][a-z\d+.-]*:\/\/[^\s"'<>]+/giu,t=>zn(t))}function aT(e,t=process.env){return U(t).endpoint??e}function K(e=process.env){let t=Ut("DO_NOT_TRACK",e),n=U(e),r=(e.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase(),o=jn(e)&&!Ga.has(r)&&!Ut("PM_TELEMETRY_SEND_TEST_EVENTS",e);return{telemetry_disabled:t||o||n.invalid||Ut("PM_TELEMETRY_DISABLED",e)||Ut("PM_NO_TELEMETRY",e),do_not_track:t,test_suppressed:o,endpoint_override:n.endpoint===null?null:zn(n.endpoint),endpoint_override_invalid:n.invalid}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a483f454-e261-5232-bae0-da3cdb8c0518")}catch{}})();var ke=Object.freeze({max_bytes:4096,max_depth:8}),Xa=160,I_=new Set(["not_plain_object","unsupported_value","non_finite_number","malformed_unicode","reserved_key","depth_limit","byte_limit","diagnostic_budget"]),Qa=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,C_=new Set(["__proto__"]),M=class extends Error{reason;path;constructor(t,n){super(t),this.reason=t,this.path=n}};function Lo(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function A_(e,t){return/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Za(e){if(Buffer.byteLength(e,"utf8")<=Xa)return e;let t="",n=Buffer.byteLength("\u2026","utf8");for(let r of e){if(n+=Buffer.byteLength(r,"utf8"),n>Xa)break;t+=r}return`${t}\u2026`}function Hn(e,t,n){if(e.bytes+=t,!(e.bytes<=ke.max_bytes))throw new M("byte_limit",n)}function ec(e,t,n){if(e.bytes+t>ke.max_bytes)throw new M("byte_limit",n)}function Mo(e,t,n){let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||!("value"in r))throw new M("unsupported_value",n);return r.value}function x_(e,t,n){if(typeof e=="number"&&!Number.isFinite(e))throw new M("non_finite_number",t);if(typeof e=="string"&&(ec(n,e.length+2,t),Qa.test(e)))throw new M("malformed_unicode",t);if(e!==null&&!["boolean","number","string"].includes(typeof e))throw new M("unsupported_value",t);return Hn(n,Buffer.byteLength(JSON.stringify(e),"utf8"),t),e}function tc(e,t,n,r){if(typeof e!="object"||e===null)return x_(e,t,r);if(n>=ke.max_depth)throw new M("depth_limit",t);if(Array.isArray(e)){let o=Mo(e,"length",t);if(typeof o!="number"||!Number.isSafeInteger(o)||o<0)throw new M("unsupported_value",t);Hn(r,o>0?o+1:2,t);let i=[];for(let s=0;s<o;s+=1){let a=`${t}[${s}]`;i.push(tc(Mo(e,String(s),a),a,n+1,r))}return i}if(!Lo(e))throw new M("unsupported_value",t);return nc(e,t,n+1,r)}function nc(e,t,n,r){let o=Object.keys(e);Hn(r,o.length>0?o.length+1:2,t);let i={};for(let s of o){ec(r,s.length+3,t);let a=A_(t,s);if(C_.has(s))throw new M("reserved_key",a);if(Qa.test(s))throw new M("malformed_unicode",a);Hn(r,Buffer.byteLength(JSON.stringify(s),"utf8")+1,a),i[s]=tc(Mo(e,s,a),a,n,r)}return i}function R_(e){try{if(e instanceof M)return e}catch{}return new M("unsupported_value","details")}function Bn(e){let t=ke.max_bytes,n={bytes:0};try{if(!Lo(e))throw new M("not_plain_object","details");return{ok:!0,details:nc(e,"details",0,n),byte_length:n.bytes}}catch(r){let o=R_(r);return{ok:!1,omission:o.reason==="byte_limit"?{reason:"byte_limit",byte_limit:t}:{reason:o.reason,path:Za(o.path),byte_limit:t}}}}function k_(e){return Bn(e).ok}function rc(e){if(e===void 0)return;let t=Bn(e);return t.ok?{details:t.details}:{details_omitted:t.omission}}function qn(){return{reason:"unsupported_value",path:"details",byte_limit:ke.max_bytes}}function Ja(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n?n.value:void 0}function O_(e){if(!Lo(e))return;let t=Ja(e,"reason");if(typeof t!="string"||!I_.has(t))return;let n=Ja(e,"path"),r=typeof n=="string"?Za(n):void 0;return{reason:t,...r===void 0?{}:{path:r},byte_limit:ke.max_bytes}}function oc(e){let t={};try{if(typeof e!="object"||e===null||Array.isArray(e))return t;for(let[n,r]of Object.entries(Object.getOwnPropertyDescriptors(e)))r.enumerable&&("value"in r?Object.defineProperty(t,n,{value:r.value,enumerable:!0,writable:!0,configurable:!0}):n==="details"&&(t.details_omitted=qn()));return t}catch{return{}}}function ic(e){if(!(typeof e!="object"||e===null))try{let t=Object.getOwnPropertyDescriptor(e,"details");if(t!==void 0&&!("value"in t))return{details_omitted:qn()};if(t!==void 0&&t.value!==void 0)return rc(t.value);let n=Object.getOwnPropertyDescriptor(e,"details_omitted"),r=n!==void 0&&"value"in n?O_(n.value):void 0;return r===void 0?void 0:{details_omitted:r}}catch{return{details_omitted:qn()}}}var sc=new Set(["details","details_omitted"]);function D_(e){let t={};for(let n of Object.keys(e)){if(sc.has(n)||n==="toJSON")continue;let r=Object.getOwnPropertyDescriptor(e,n);r!==void 0&&"value"in r&&Object.defineProperty(t,n,{value:r.value,enumerable:!0,writable:!0,configurable:!0})}return t}function N_(e){if(typeof e!="object"||e===null)return e;try{return Array.isArray(e)?e:{...D_(e),...ic(e)}}catch{return{details_omitted:qn()}}}function Qe(e){let t={};for(let[n,r]of Object.entries(oc(e)))sc.has(n)||n==="toJSON"||(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0});return t}var M_=12,L_=new Set(["context","error_context"]),P_=new Set(["arguments"]);function ac(e){let t=new WeakSet,n=(r,o)=>{if(typeof r!="object"||r===null||o>M_||t.has(r))return;t.add(r);let i=r,s;try{s=Object.keys(i)}catch{return}for(let a of s){let c=Object.getOwnPropertyDescriptor(i,a);if(c===void 0||!("value"in c))continue;let d=c.value,l=L_.has(a)?{}:P_.has(a)?[]:d;l!==d&&(i[a]=l),n(l,o+1)}};n(e,0)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e82bc812-181f-57ab-a29a-61703e8bec1b")}catch{}})();function Po(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function pT(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!Po(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return Po(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&Po(t.feasible_tokens)&&t.reason===void 0;case"unavailable":return t.minimum_feasible_tokens===null&&t.feasible_tokens===null&&["query_cost_limit","search_limit","output_constraints"].includes(t.reason);default:return!1}}var $_="PmCliError";function _T(e){if(!Vt(e)||e.code!=="item_already_exists"||e.exitCode!==m.CONFLICT)return!1;let t=e.context;return typeof t=="object"&&t!==null&&t.code==="item_already_exists"&&typeof t.id=="string"&&t.id.trim().length>0&&typeof t.path=="string"&&t.path.trim().length>0}function F_(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=m.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function j_(e){if(e==null)return{};if(!Object.hasOwn(e,"details"))return e;let t=Object.getOwnPropertyDescriptor(e,"details");if(!("value"in t))throw cc("unsupported_value","details");if(t.value===void 0)return e;let n=Bn(t.value);if(n.ok)return{...e,details:n.details};if(n.omission.reason==="byte_limit"){let{details:r,...o}=e;return{...o,details_omitted:n.omission}}throw cc(n.omission.reason,n.omission.path)}function cc(e,t){let n=new TypeError(`createPmCliExpectedError options.context.details must be plain JSON (${e})`);return Object.defineProperty(n,"path",{value:t,enumerable:!1}),n}function hT(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new p(e,F_(t.exitCode??m.USAGE),j_(t.context));return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Vt(e){try{if(!(e instanceof Error)||e.name!==$_)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)&&typeof t.context=="object"&&t.context!==null&&!Array.isArray(t.context)}catch{return!1}}import{createRequire as G_}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]="64589e00-25ef-5d74-a94a-7d40455e1929")}catch{}})();var Wn=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,U_=new RegExp(`(?:\\b|(?<=_))(${Wn.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");function Yn(e,t,n){let r=t;for(;r>0&&e[r-1]==="\\";)r--;let o=n.length>1;if(o&&r===t)return;let i=o?(t-r)*2:t-r+1,s=1;for(;i%2===0;)s*=2,i/=2;let a=o?String.fromCharCode(Number.parseInt(n.slice(1),16)):n;return{index:r,end:t+n.length,identity:`${a}:${s}`,character:a,width:s}}function lc(e,t){let n=/["']|u(?:0022|0027)/gi;n.lastIndex=t.end;for(let r of e.matchAll(n)){let o=Yn(e,r.index,r[0]);if(o?.identity===t.identity)return o.end}return e.length}function z_(e,t,n,r){let o=e.pop();return o.character!==t.character||o.width!==t.width?r:e.length===0?n:void 0}function V_(e,t){let n=[{character:t.character==="{"?"}":"]",width:t.width}],r=/["'{}[\]]|u(?:0022|0027|007b|007d|005b|005d)/gi;r.lastIndex=t.end;let o;for(;(o=r.exec(e))!==null;){let i=Yn(e,o.index,o[0]);if(!i)continue;let s=i.character;if(s==="{"||s==="["){n.push({character:s==="{"?"}":"]",width:i.width});continue}if(s==="}"||s==="]"){let a=z_(n,i,i.end,e.length);if(a!==void 0)return a;continue}r.lastIndex=lc(e,i)}return e.length}function H_(e,t,n){let r=/^(\\*)(["'{[]|u(?:0022|0027|007b|005b))/i.exec(e.slice(t)),o=r?Yn(e,t+r[1].length,r[2]):void 0;return o?.character==="{"||o?.character==="["?V_(e,o):o?lc(e,o):n}function q_(e){let t=[],n=0;for(let r of e.matchAll(/u([\da-f]{4})/gi)){let o=r.index;for(;o>n&&e[o-1]==="\\";)o--;o!==r.index&&(t.push(e.slice(n,o),String.fromCharCode(Number.parseInt(r[1],16))),n=r.index+r[0].length)}return t.push(e.slice(n)),t.join("")}var dc="(?:\\s|\\\\+u(?:0009|000a|000d|0020))*",B_=new RegExp("^"+dc+"(?::|=|\\\\+u(?:003a|003d))"+dc,"iu");function W_(e,t,n){let r=q_(t);if(!Wn.test(r)&&!/\\u/iu.test(r))return;let o=e.slice(n),i=B_.exec(o);if(!i)return/^\s*\\+u/iu.test(o)?{index:n,start:n,unquotedEnd:e.length,replacement:"[scrubbed]"}:void 0;let s=n+i[0].length,a=/^[^\s,;]+/u.exec(e.slice(s));return a?{index:s,start:s,unquotedEnd:s+a[0].length,replacement:"[scrubbed]"}:void 0}function Y_(e){let t=new Map,n=[];for(let r of e.matchAll(/["']|u(?:0022|0027)/gi)){let o=Yn(e,r.index,r[0]);if(!o)continue;let i=t.get(o.identity),s=o.end;if(t.set(o.identity,s),i===void 0)continue;let a=W_(e,e.slice(i,o.index),s);a&&n.push(a)}return n}function uc(e){let t=Y_(e);for(let o of e.matchAll(U_)){let i=o.index+o[0].length;t.push({index:o.index,start:i-o[2].length,unquotedEnd:i,replacement:`${o[1]}=[scrubbed]`})}t.sort((o,i)=>o.index-i.index);let n=[],r=0;for(let o of t)o.index<r||(n.push(e.slice(r,o.index),o.replacement),r=H_(e,o.start,o.unquotedEnd));return n.push(e.slice(r)),n.join("")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="85813255-48e1-5b53-913e-27d433c3ff45")}catch{}})();var hc=new Set(["1","true","yes","on"]);function yc(){return!!(hc.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||K().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}var K_=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,X_=/file:\/\/\/?[^\s"'`),;]+/giu,J_=/\b[A-Za-z]:\\[^\s"'`),;]+/g,Q_=/\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,Z_=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i;var eh=["[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 mc(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 W(e,t){if(t&&Z_.test(t)&&mc(e))return"[scrubbed_path]";let n=uc(Kt(e)).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(Q_,"[scrubbed_ip]").replaceAll(X_,"[scrubbed_path]").replaceAll(J_,"[scrubbed_path]").replaceAll(K_,(r,o)=>`${o}[scrubbed_path]`);return mc(n)?"[scrubbed_path]":n}function X(e){let t={};for(let[n,r]of Object.entries(e))Wn.test(n)||n.startsWith("sentry.message.parameter.")?t[n]="[scrubbed]":typeof r=="string"?t[n]=W(r,n):Array.isArray(r)?t[n]=r.map(o=>typeof o=="string"?W(o,n):o&&typeof o=="object"?X(o):o):r&&typeof r=="object"?t[n]=X(r):t[n]=r;return t}function th(e){for(let n of["filename","absPath","abs_path","module"]){let r=e[n];typeof r=="string"&&(e[n]=W(r,n))}let t=e.context_line;typeof t=="string"&&(e.context_line=W(t,"context_line"));for(let n of["pre_context","post_context"]){let r=e[n];Array.isArray(r)&&(e[n]=r.map(o=>typeof o=="string"?W(o,n):o))}e.vars&&typeof e.vars=="object"&&(e.vars=X(e.vars)),e.data&&typeof e.data=="object"&&(e.data=X(e.data))}var nh=G_(import.meta.url),rh=()=>nh("@sentry/node"),Gn,fc=!1,oh=rh,ih="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function $o(e){return/^\s*PmCliError:/.test(e)}function Fo(e){let t=e.trim().toLowerCase();return t.length===0?!1:eh.some(n=>t.includes(n))}function sh(e){return e.logger!=="console"?!1:typeof e.message=="string"&&Fo(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(t=>typeof t.value=="string"&&Fo(t.value))}function ah(e){if(e.logger!=="console")return!1;let t=n=>typeof n=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(n);return t(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(n=>t(n.value))}function ch(e,t){return t instanceof Error?Vt(t):!!(e.exception?.values?.some(n=>n.type==="PmCliError")||e.exception?.values?.some(n=>typeof n.value=="string"&&$o(n.value))||e.logger==="console"&&typeof e.message=="string"&&$o(e.message))}function gc(e){return e.category==="console"&&typeof e.message=="string"&&$o(e.message)}function wc(e){return e.category==="console"&&typeof e.message=="string"&&Fo(e.message)}function dh(){return pr(import.meta.url,["../../.."])??"0.0.0"}function lh(){let e=process.env.SENTRY_ENVIRONMENT?.trim();if(e&&e.length>0)return e;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";let t=Je().source_context;return t==="user"?"production":t}var pc=.2;function bc(){let e=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!e)return pc;let t=Number(e);return!Number.isFinite(t)||t<0||t>1?pc:t}function uh(e){if(e.exception?.values){for(let t of e.exception.values)if(t.value&&(t.value=W(t.value,"value")),t.stacktrace?.frames)for(let n of t.stacktrace.frames)th(n)}}function Ec(e){if(e.breadcrumbs)for(let t of e.breadcrumbs)t.message&&(t.message=W(t.message)),t.data&&typeof t.data=="object"&&(t.data=X(t.data))}function Sc(e){if(e.contexts)for(let[t,n]of Object.entries(e.contexts))n&&typeof n=="object"&&(e.contexts[t]=X(n))}function _c(e,t){let n=e,r=n[t];r&&typeof r=="object"&&(n[t]=X(r))}function jo(e){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(e==="automation"||e==="test"||e==="dogfood"||e==="user"))return e==="user"?"production":e}function vc(e){let t=jo(e.tags?.["pm.source_context"]);t&&(e.environment=t)}function Tc(e,t){let n=mh(e.extra);ac([e.contexts,e.extra,e.breadcrumbs]),fh(e.contexts,t),n!==void 0&&(e.extra.error_context=Qe(n))}function mh(e){if(!(typeof e!="object"||e===null||!Object.hasOwn(e,"error_context")))return e.error_context}function fh(e,t){if(typeof e!="object"||e===null||typeof t!="object"||t===null)return;let n=e,r=new Set(ph(t)),o=_h(t);for(let[i,s]of Object.entries(n))(r.has(i)||typeof s=="object"&&s!==null&&Object.hasOwn(s,"context"))&&(n[i]=o??{})}function ph(e){try{return[e.name,e.constructor?.name].filter(t=>typeof t=="string"&&t.length>0)}catch{return[]}}function _h(e){try{let t=Qe(e),n=Object.getOwnPropertyDescriptor(e,"context");return n!==void 0&&"value"in n&&(t.context=Qe(n.value)),t}catch{return}}var hh=(e,t)=>{if(ch(e,t?.originalException)||sh(e))return null;Tc(e,t?.originalException),vc(e),ah(e)&&(e.level="warning",e.tags={...e.tags,"pm.diagnostic_class":"node_runtime_warning"}),e.message&&(e.message=W(e.message,"message")),e.transaction&&(e.transaction=W(e.transaction,"transaction")),uh(e),Ec(e),_c(e,"extra"),Sc(e);for(let n of["request","user","tags"])_c(e,n);return e},yh=e=>(Tc(e),vc(e),e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(t=>!gc(t)&&!wc(t)),Ec(e)),Sc(e),e),gh=e=>X(e),wh=e=>{if(e.message=W(e.message),e.attributes){let t=jo(e.attributes["pm.source_context"]);t&&(e.attributes["sentry.environment"]=t),e.attributes=X(e.attributes)}return e};function bh(e){let t=jo(e["pm.source_context"]?.value);t&&(e["sentry.environment"]={type:"string",value:t})}function Eh(e){for(let t of e[1])if(t[0].type==="log")for(let n of t[1].items){n.body=W(n.body);let r=n.attributes;if(r){bh(r);for(let[o,i]of Object.entries(r)){let s=X({[o]:i.value})[o];typeof s=="string"&&(r[o]={type:"string",value:s})}}}}var Sh=e=>gc(e)||wc(e)?null:(e.message&&(e.message=W(e.message,"message")),e.data&&typeof e.data=="object"&&(e.data=X(e.data)),e);async function Ic(){if(fc)return Gn;if(fc=!0,yc())return;let e=oh(),t=process.env.SENTRY_DSN?.trim()||ih,n=dh();e.init({dsn:t,release:`pm-cli@${n}`,environment:lh(),tracesSampleRate:bc(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[e.extraErrorDataIntegration({depth:4,captureErrorCause:!1}),e.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":n,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend:hh,beforeSendTransaction:yh,beforeSendSpan:e.withStreamedSpan(gh),beforeSendLog:wh,beforeBreadcrumb:Sh});let r=e.getClient();if(!r)return;let o=Je();return e.setTags({"pm.version":n,"pm.source_context":o.source_context,"pm.source_context_source":o.source_context_source}),e.setAttribute("pm.source_context",o.source_context),r.on("beforeEnvelope",Eh),Gn=e,e}async function vh(e){if(e!==!0||!hc.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||bc()===0||yc())return!1;try{return await Ic()!==void 0}catch{return Gn=void 0,!1}}function Oe(){return Gn}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e8ad404-2f8d-5d9b-9046-60178a70e5b2")}catch{}})();var Ht=class extends p{constructor(t,n,r){super(t,m.GENERIC_FAILURE,n),this.name="ExtensionCommandError",Object.defineProperty(this,"cause",{value:r,configurable:!0,writable:!0})}};function RT(e,t){let n=t.warnings[0]??"extension_command_handler_failed",r=t.errorMessage?.trim();return new Ht(`Command "${e}" failed in extension handler (${n}).${r?` ${r}`:""}`,{code:t.errorCode??"command_failed",nextSteps:t.remediation?[t.remediation]:void 0},t.cause)}function kT(e){return e instanceof p||e instanceof Error?e.message:"Unknown failure"}function Th(e){if(typeof e!="object"||e===null||!("exitCode"in e))return;let t=e.exitCode;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ih(e){let t=Math.trunc(e);return t>m.SUCCESS?t:m.GENERIC_FAILURE}function OT(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function DT(e,t){if(e instanceof Error)return e;let n=new Error(t),r=Th(e);return r!==void 0&&(n.exitCode=Ih(r)),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]="bd65294f-dfa5-53d2-9691-c630884f2a5f")}catch{}})();var Ch=new Set(["init","config","completion","completion-statuses","completion-tags","completion-types"]),Ah=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"]),xh=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"]),Rh=new Set(["test","test-all","test-runs","test-verify","trace-test","test-ping"]),kh=new Set(["health","validate","normalize","reindex","gc","telemetry","extension-doctor"]);function Oh(e){return e.trim().replaceAll(/\s+/g," ").toLowerCase()}function Cc(e){let t=e?.trim().toLowerCase();return t&&t.length>0?t:void 0}var Dh=[{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")}],Nh=new Map([[m.USAGE,"invalid_command_usage"],[m.NOT_FOUND,"item_not_found"],[m.CONFLICT,"lock_conflict"],[m.DEPENDENCY_FAILED,"dependency_failed"]]);function De(e){let t=Oh(e),n=t.length>0?t.split(" "):["<unknown>"],r=n[0],o=n[n.length-1],i="other";return Ch.has(r)?i="setup":Ah.has(r)?i="query":xh.has(r)?i="mutation":Rh.has(r)?i="testing":r==="extension"?i="extension":kh.has(r)&&(i="diagnostics"),{command_path:t.length>0?t:"<unknown>",command_root:r,command_leaf:o,command_depth:n.length,command_family:i}}function Uo(e){if(e.ok)return;let t=Cc(e.errorCode);if(t)return t;let n=(e.errorMessage??"").trim().toLowerCase();for(let o of Dh)if(o.matches(n))return o.code;let r=Number.isFinite(e.exitCode)?Math.max(0,Math.trunc(e.exitCode)):void 0;return r!==void 0?Nh.get(r)??"command_failed":"command_failed"}function Ze(e){if(e.ok)return"success";let t=Cc(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]="10325dfb-128f-5d83-9163-061d8d8b29b6")}catch{}})();var Ne;function ye(e,t,n){if(n===void 0)return;let r=e;typeof r.setAttribute=="function"&&r.setAttribute(t,n)}function et(e,t,n){typeof n=="string"&&n.trim().length>0&&e.setTag(t,n)}function Mh(e,t,n){e.setTag("pm.ok",t),e.setTag("pm.command_ok",t),typeof n?.exit_code=="number"&&(e.setTag("pm.exit_code",String(n.exit_code)),e.setTag("pm.command_exit_code",String(n.exit_code))),et(e,"pm.error_code",n?.error_code),et(e,"pm.error_category",n?.error_category),et(e,"pm.command_resolution",n?.command_resolution),et(e,"pm.resolution_stage",n?.resolution_stage)}function Lh(e,t,n,r){ye(e,"pm.ok",t),ye(e,"pm.command_ok",t),ye(e,"pm.exit_code",n),ye(e,"pm.command_exit_code",n),ye(e,"pm.error_code",r?.error_code),ye(e,"pm.error_category",r?.error_category),ye(e,"pm.command_resolution",r?.command_resolution),ye(e,"pm.resolution_stage",r?.resolution_stage)}function Ph(e,t,n,r){let o=Oe();if(!o)return;let i=De(e);o.setTag("pm.command",e),o.setTag("pm.command_root",i.command_root),o.setTag("pm.command_family",i.command_family),et(o,"pm.version",r?.pm_version),et(o,"pm.source_context_source",r?.source_context_source),o.setTag("pm.extension.name",r?.extension?.name),o.setTag("pm.extension.version",r?.extension?.version),o.setTag("pm.extension.layer",r?.extension?.layer),typeof r?.source_context=="string"&&r.source_context.trim().length>0&&(o.setTag("pm.source_context",r.source_context),o.setAttribute("pm.source_context",r.source_context));let s=t.map(()=>"[redacted]");o.setContext("pm.command",{name:e,root:i.command_root,leaf:i.command_leaf,family:i.command_family,args:s,option_keys:Object.keys(n).sort(),source_context:r?.source_context,source_context_source:r?.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:r?.source_context}})}function $h(e){let t=Oe();if(!t)return;let n=De(e);Ne=t.startInactiveSpan({op:"pm.command",name:`pm ${e}`,forceTransaction:!0,attributes:{"pm.command":e,"pm.command_root":n.command_root,"pm.command_family":n.command_family}})}function Fh(){Ne=void 0}function jh(e,t,n){if(!Ne)return;let r=e?"true":"false",o=typeof n?.exit_code=="number"?String(n.exit_code):void 0,i=Oe();i&&Mh(i,r,n),Lh(Ne,r,o,n),Ne.setStatus(e?{code:1}:{code:2,message:t??"command_failed"}),Ne.end(),Ne=void 0}var Uh="unclassified_runtime_error";function zh(e){let t=typeof e=="object"&&e!==null?e:void 0,n=typeof t?.exitCode=="number",r=n?Math.trunc(t?.exitCode):m.GENERIC_FAILURE;return{error_code:typeof t?.code=="string"&&t.code.length>0&&n?t?.code:Uh,exit_code:r}}function Vh(e){let t=zh(e);return{"pm.error_code":t.error_code,"pm.exit_code":String(t.exit_code)}}function Hh(e){if(!Bh(e))return;let t=Oe();if(!t)return;let n=Vh(e);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=Qe(e.context)),t.captureException(e,{extra:r,tags:n})}else t.captureException(new Error(String(e)),{tags:n})}function qh(e){let t=Oe();if(!t)return;let n=e.command_resolution??Ze({ok:!1,errorCode:e.error_code,errorCategory:e.error_category}),r=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":n,"pm.resolution_stage":r,"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":n,"pm.resolution_stage":r,"pm.source_context":e.source_context??"unknown"},extra:o})}function Bh(e){if(e instanceof Ht)return!0;if(e instanceof p||Vt(e)||e instanceof Error&&e.name==="AbortError"&&/(?:ctrl\+[cd]|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([m.SUCCESS,m.USAGE,m.NOT_FOUND,m.CONFLICT]).has(t)}return!0}async function Wh(e=3e3){let t=Oe();if(t)try{await t.flush(e)}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]="bab18354-8e62-57c2-872b-f7ef47fcf6d6")}catch{}})();var Me=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,R="[/\\\\]+",Yh="[\\p{L}\\p{N}._@-]+",Le=Yh+"(?:"+R+Me+")*",Kn="(?:(?:home|users)"+R+Le+"|root"+R+Le+")",Gh="[/\\\\]"+Kn,Kh="[/\\\\]{2,}"+Kn,Xh="/?[a-z]:"+R+"users"+R+Le,Jh=Me+"(?: +"+Me+")*",zo="(?:"+Jh+R+")?users"+R+Le,Qh="[/\\\\]{2,}"+Me+R+zo,Zh="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+Me+")",Lc="[/\\\\]{2}[?.]"+R+"(?:unc"+R+Me+R+zo+"|"+Zh+R+"users"+R+Le+")",ey="file:(?:"+Lc+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+R+")(?:"+Kn+"|[a-z]:"+R+"users"+R+Le+")|[/\\\\]{2}(?:[a-z]:"+R+"users"+R+Le+"|"+Me+R+"(?:"+Kn+"|"+zo+")))",ty=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+Gh+"|"+Xh+"|"+ey+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+Kh+"|"+Qh+"|"+Lc+")","giu"),Ac=4,ny=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,ry=new TextDecoder("utf-8");function oy(e){return e.replace(/(?:%[a-f0-9]{2})+/giu,t=>ry.decode(Uint8Array.from(t.matchAll(/%([a-f0-9]{2})/giu),n=>Number.parseInt(n[1],16)))).replace(/%(?![a-f0-9]{2})[a-z0-9]{0,2}/giu,"\uFFFD")}function iy(e){return e.replace(/\\+(?:u([a-f0-9]{4})|x([a-f0-9]{2})|(\/))?/giu,(t,n,r,o)=>{let i=n??r;return i===void 0?o??t:String.fromCharCode(Number.parseInt(i,16))})}function sy(e){return e.normalize("NFKC").replace(/[\p{Bidi_Control}\u200b-\u200f\u2060-\u206f\ufeff]/gu,"").replace(/[\u2215\u2044]/gu,"/").replace(/[\u043e\u041e]/gu,"o").replace(/[\u0455\u0405]/gu,"s")}function ay(e,t){for(let[n,r]of[["percent_decode",oy],["json_unescape",iy],["unicode_fold",sy]]){let o=r(e);o!==e&&!t.includes(n)&&t.push(n),e=o}return e}function*cy(e,t,n){let r=e,o=[];for(let i=0;i<Ac;i+=1){let s=r;if(r=ay(r,o),!n){t.lastIndex=0;for(let a of r.matchAll(t))n=!0,yield{index:0,normalizations:[...o]}}if(r===s)break;i===Ac-1&&ny.test(r)&&(yield{index:0,normalizations:[...o],normalization_incomplete:!0})}}function*dy(e,t){let n=0;for(let r of e.split(`
107
+ `)){t.lastIndex=0;let o=!1;for(let i of r.matchAll(t))o=!0,yield{index:n+i.index};for(let i of cy(r,t,o))yield{...i,index:n};n+=r.length+1}}var xc="password|passphrase",Rc=/(?:(?!<|\$\{|\$\(|config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))[A-Za-z0-9!@#$%^&*._+\-=]{8,}|"(?!<|\$\{|\$\()[^"]{8,}"|'(?!<|\$\{|\$\()[^']{8,}')/,kc="token|secret|password|passwd|api[_-]?key",Oc=/["']?([A-Za-z0-9+/=_-]{24,})/,Pc=[{name:"private-key",mutationRule:"private_key",regex:/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/g},{name:"github-token",mutationRule:"github_token",regex:/\b(?:gh[opsru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g},{name:"npm-token",mutationRule:"npm_token",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g},{name:"aws-access-key",mutationRule:"aws_access_key",regex:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g},{name:"google-api-key",mutationRule:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"slack-token",mutationRule:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"anthropic-api-key",mutationRule:"anthropic_api_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"openai-api-key",mutationRule:"openai_api_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"gitlab-token",mutationRule:"gitlab_token",regex:/\bglpat-[A-Za-z0-9_.-]{20,}\b/g},{name:"jwt-like-token",mutationRule:"jwt_like_token",regex:/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g},{name:"npm-auth-token-assignment",mutationRule:"npm_auth_token_assignment",regex:/_authToken\s*=\s*\S+/g},{name:"sentry-user-token",mutationRule:"sentry_user_token",regex:/\bsntryu_[A-Za-z0-9]{20,}\b/g},{name:"sentry-org-token",mutationRule:"sentry_org_token",regex:/\bsntrys_[A-Za-z0-9_-]{20,}\b/g},{name:"private-ip",mutationRule:"private_ip",regex:/\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},{name:"private-ssh-target",mutationRule:"private_ssh_target",regex:/\b(?:ssh|scp|rsync)\s+[A-Za-z0-9._-]+@(?: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},{name:"sshpass-inline-password",mutationRule:"sshpass_inline_password",regex:/\bsshpass\s+-p\s+["'][^"']{6,}["']/g},{name:"password-assignment",mutationRule:"password_assignment",regex:new RegExp(String.raw`\b(?:${xc})\s*[:=]\s*`+Rc.source,"gi"),structured:{keys:xc,value:Rc.source,element:!0}},{name:"absolute-home-path",mutationRule:"absolute_home_path",regex:ty,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",regex:/\b[A-Za-z0-9._-]+@(?: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,excludeFiles:/^(?:tests\/|examples\/)/},{name:"high-entropy-assignment",mutationRule:"high_entropy_assignment",regex:new RegExp(String.raw`\b(?:${kc})\s*[:=]\s*`+Oc.source,"gi"),structured:{keys:kc,value:Oc.source},mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.",minimumEntropy:3.5}];function*$c(e,t){if(e.mutationRule==="absolute_home_path"){yield*dy(t,e.regex);return}e.regex.lastIndex=0;for(let n of t.matchAll(e.regex))jc(e,n)&&(yield{index:n.index});e.structured&&(yield*Sy(e,e.structured,t))}var Dc=new Map,Nc=/[\r\n\u2028\u2029]/u;function ly(e){let t=`${e.keys}\0${e.value}\0${e.element===!0}`,n=Dc.get(t);return n||(n={key:new RegExp(String.raw`\b(?:${e.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(e.value,"iy"),...e.element?{element:new RegExp(String.raw`<(?:${e.keys})(?:\s[^<>]*)?>([^<]*)<\/(?:${e.keys})\s*>`,"gi")}:{}},Dc.set(t,n)),n}function Fc(e,t){let n=e[t];for(let r=t+1;r<e.length;r+=1){let o=e[r];if(o==="\\")r+=1;else if(o===n)return{end:r+1,terminated:!0}}return{end:e.length,terminated:!1}}function uy(e,t){return Fc(e,t).end}function my(e,t,n){return e.at(-1)==="}"?n:t}function fy(e,t,n,r=n){let o=[],i=!1;for(let s=t;s<e.length;s+=1){let a=e[s];switch(a){case"[":case"{":o.push(a==="["?"]":"}"),i=a==="{";break;case"]":case"}":if(o.pop()!==a||o.length===0)return{found:!1,end:s+1};i=!1;break;case",":i=o.at(-1)==="}";break;case":":i=!1;break;case'"':case"'":if(!i&&my(o,n,r)(s))return{found:!0,end:s};s=uy(e,s)-1;break;default:break}}return{found:!1,end:e.length}}var py=/\\(?:U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-7]{1,3}|[\s\S])/gu,_y={n:`
108
+ `,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function Mc(e,t){let n=e[0],r=e.slice(1,t?-1:void 0).replaceAll(py,o=>{let i=o[1];if((i==="u"||i==="x")&&o.length>2)return String.fromCharCode(Number.parseInt(o.slice(2),16));if(/^[0-7]$/u.test(i))return String.fromCharCode(Number.parseInt(o.slice(1),8));if(i==="U"&&o.length===10){let s=Number.parseInt(o.slice(2),16);return s<=1114111?String.fromCodePoint(s):"\uFFFD"}return _y[i]??i}).replaceAll(n,n==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," ");return`${n}${r}${t?n:""}`}var hy=64;function yy(e,t,n){let r=e[t-1];if(!n)return r!==void 0&&/[\p{L}\p{N}_.-]/u.test(r)?"prefixed":"exact";if(r===n)return"exact";let o=Math.max(0,t-hy);for(let i=t-1;i>=o;i-=1){let s=e[i];if(s===n)return"prefixed";if(s===`
109
+ `||s==="\r"||s==='"'||s==="'")return"malformed"}return"malformed"}function gy(e,t,n){let r=(s,a)=>{t.lastIndex=a;let c=t.exec(s);return c!==null&&!Nc.test(c[0])&&jc(e,c)?c:null},o=s=>{if(n[s]!=='"'&&n[s]!=="'")return;let{end:a,terminated:c}=Fc(n,s),d=n.slice(s,a);return d.includes("\\")?Nc.test(d)?[]:(n[s]==="'"?[Mc(d,c),d]:[Mc(d,c)]).map(l=>r(l,0)).filter(l=>l!==null):void 0},i=s=>{let a=o(s);if(a!==void 0)return a;let c=r(n,s);return c===null?[]:[c]};return{direct:s=>r(n,s)!==null,escaped:s=>(o(s)?.length??0)>0,accepts:s=>a=>i(a).some(c=>!(s&&/\s/u.test(c[0])))}}function*wy(e,t){e.lastIndex=0;for(let n of t.matchAll(e)){let r=n[1].trim();r.length>=8&&!r.startsWith("${")&&!r.startsWith("$(")&&(yield{index:n.index})}}function by(e,t,n){return t<e.exact||n&&t<e.compact}function Ey(e,t,n,r){return(n||e.escaped(r)&&!e.direct(r))&&t(r)}function*Sy(e,t,n){let r=ly(t),o=gy(e,r.value,n),i=new RegExp(r.key),s={exact:0,compact:0};for(let a=i.exec(n);a;a=i.exec(n)){let c=a[1],d=yy(n,a.index,c);if(d==="malformed")continue;let l=d==="prefixed",u=o.accepts(l),f=a.index+a[0].length,_=n[f];if(_==="["||_==="{"){if(by(s,f,l))continue;let y=fy(n,f,u,o.accepts(!0));s[l?"compact":"exact"]=y.end,y.found&&(yield{index:a.index})}else Ey(o,u,c,f)&&(yield{index:a.index})}r.element&&(yield*wy(r.element,n))}function jc(e,t){if(e.minimumEntropy===void 0)return!0;let n=t[1],r=new Map;for(let i of n)r.set(i,(r.get(i)??0)+1);let o=0;for(let i of r.values()){let s=i/n.length;o-=s*Math.log2(s)}return o>=e.minimumEntropy}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6059407-bf03-5ae8-8b01-e3e7c5b28030")}catch{}})();var vy=[{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"}],Ho=new Map(vy.map(e=>[e.action,e]));function Vo(e,t="$",n=new WeakSet){return typeof e=="string"?[{path:t,value:e}]:typeof e!="object"||e===null?[]:n.has(e)?[]:(n.add(e),Array.isArray(e)?e.flatMap((r,o)=>Vo(r,`${t}[${o}]`,n)):Object.entries(e).flatMap(([r,o])=>Vo(o,`${t}.${r}`,n)))}function Ty(e,t){let n=$c(e,t),r=n.next().value;if(!r||e.mutationRule!=="absolute_home_path"||r.normalization_incomplete)return r;for(let o of n)if(o.normalization_incomplete)return{...r,normalizations:[...new Set([r.normalizations,o.normalizations].flatMap(i=>i??[]))],normalization_incomplete:!0};return r}function Uc(e){let t=[];for(let n of Vo(e))for(let r of Pc){let o=Ty(r,n.value);if(o){let i={rule:r.mutationRule,path:n.path};o.normalizations&&(i.normalizations=o.normalizations),o.normalization_incomplete&&(i.normalization_incomplete=!0),t.push(i)}}return t.filter((n,r,o)=>o.findIndex(i=>i.rule===n.rule&&i.path===n.path)===r)}function Iy(e){let t=e.author.trim()||"unknown";if(e.settings.require_attributed_author&&t.toLowerCase()==="unknown")throw new p("Mutation author is required by workspace policy.",m.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 n;try{n=Uc(e.payload)}catch{return{author:t,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(n.length===0)return{author:t,findings:n,warnings:[],override_applied:!1};let r=[...new Set(n.map(o=>o.rule))].sort().join(",");if(e.settings.secret_guard==="block"&&e.force!==!0)throw new p(`Mutation blocked by secret guard (${r}). No detected value was logged.`,m.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:n,warnings:[`secret_guard_detected:${n.length}:rules=${r}`,...e.settings.secret_guard==="block"&&e.force===!0?["secret_guard_force_override"]:[]],override_applied:e.settings.secret_guard==="block"&&e.force===!0}}function Cy(e){return Ho.has(e.trim().toLowerCase())}function Ay(){return[...Ho.keys()].sort((e,t)=>e.localeCompare(t))}function GT(e){return Ho.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]="5767332d-8094-55cd-96e9-47c5d20cd7df")}catch{}})();var xy=/\b([a-z][a-z0-9]*)-(\d+)(?:-[a-z0-9]+)*\b/giu,Ry=/^(?:utf|iso|sha|tls|http|covid|match)$/iu;function qo(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Vc(e){return[...new Set(qo(e).match(/[\p{L}\p{N}]+/gu)??[])]}function zc(e){let t=qo(e);return{normalized:t,tokens:Vc(t),issueCodes:[...new Set([...e.matchAll(xy)].filter(n=>{let r=n[1],o=n.index,i=e.slice(o+n[0].length);return!Ry.test(r)&&(r===r.toUpperCase()||r.length<=2||o===0&&/^\s*(?::|—|–|\])/u.test(i))}).map(n=>n[0].toLowerCase()))]}}function ky(e,t){return Oy(zc(e),zc(t))}function Oy(e,t){if(e.normalized===t.normalized)return{score:1,reason:"exact_title"};let n=new Set(e.issueCodes);return t.issueCodes.some(r=>n.has(r))?{score:.99,reason:"issue_code"}:{score:Xt(e.tokens,t.tokens),reason:"title_token_jaccard"}}import Dy 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]="a7cd1d62-16fe-5e5b-b382-64335fc5e403")}catch{}})();function Xn(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Ny(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,r)=>r.time-n.time)[0]?.value??e.updated_at}function Hc(e,t){let n=Math.max(1,Math.trunc(t.threshold_hours)),r=(t.now??new Date).getTime(),o=Xn(t.in_progress_status),i=[];for(let s of e){if(Xn(String(s.status))!==o||(s.assignee?.trim().length??0)>0)continue;let a=Ny(s,t.last_history_activity?.(s)),c=Date.parse(a);if(!Number.isFinite(c))continue;let d=Math.max(0,Math.floor((r-c)/36e5));d>=n&&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:n,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 My(e,t,n){let r=new Map;return await Promise.all(t.filter(o=>Xn(String(o.status))===Xn(n.in_progress_status)&&(o.assignee?.trim().length??0)===0).map(async o=>{let i;try{i=await ft(Dy.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&&r.set(o.id,s)})),Hc(t,{...n,last_history_activity:o=>r.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]="ab644545-f072-53c0-9ebf-72a62c237a2f")}catch{}})();var Ly=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"}),Py=/&(?:lt|gt|quot|#39|amp);/g;function $y(e){return typeof e!="string"||!e.includes("&lt;")&&!e.includes("&gt;")?e:e.replace(Py,t=>Ly[t])}function Fy(e){return Bo(e,new WeakMap)}function Bo(e,t){if(typeof e=="string")return $y(e);if(Array.isArray(e)){if(t.has(e))return t.get(e);let n=[];t.set(e,n);for(let r of e)n.push(Bo(r,t));return n}if(e!==null&&typeof e=="object"){if(!jy(e))return e;if(t.has(e))return t.get(e);let n=e,r=Object.create(Object.getPrototypeOf(e));t.set(e,r);for(let[o,i]of Object.entries(n))Object.defineProperty(r,o,{value:Bo(i,t),enumerable:!0,writable:!0,configurable:!0});return r}return e}function jy(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]="e7deff0d-d9c9-5250-b172-ab752ddd64a4")}catch{}})();function Uy(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]="bc9e1b59-21cb-5dda-91c0-36e123734cd3")}catch{}})();function qc(e){return e.split(/[\s,|]+/).map(t=>t.trim()).filter(t=>t.startsWith("--"))}function zy(e){return qc(e)[0]??null}function Vy(e,t){let n=zy(t);if(n===null)return!1;let r=o=>o.slice(2).replaceAll("-","_");return qc(e).some(o=>!o.slice(2).includes("-")||n===o?!1:r(n)===r(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4b566486-120f-5aed-8d92-9e62ed996210")}catch{}})();function Hy(e,t){if(e==null)return[];let n=t?.separators??/,/,r=e.split(n).map(i=>i.trim()).filter(i=>i.length>0),o=t?.unique!==!1?Array.from(new Set(r)):r;return t?.sort===!0?[...o].sort():o}import Wo from"node:fs/promises";import Jn 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]="12ee7de1-dff4-53f1-8d0d-d8b1c1ebea42")}catch{}})();function qy(e){return"json_markdown"}function Bc(e,t){return Jn.relative(e,t).replaceAll("\\","/")}function By(e){return String(e).replaceAll(/[^a-zA-Z0-9._-]+/g,"_").slice(0,120)}async function Wy(e,t,n){e!==t&&ce(await Wo.readFile(t,"utf8"),{format:"json_markdown",requireSupportedFormat:!0,schema:n})}async function Yy(e,t,n="item_format:migrate",r=ee,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=qy(t),l=Object.entries(r);for(let[u,f]of l){let _=Jn.join(e,f),y=[];try{y=await Wo.readdir(_)}catch{continue}let g=new Map;for(let w of y){let b=Jn.join(_,w),I=st(b);if(!I)continue;let A=Jn.extname(w),L=w.slice(0,w.length-A.length).trim();if(L.length===0)continue;let x=g.get(L)??{};x[I]=b,g.set(L,x)}let h=[...g.keys()].sort((w,b)=>w.localeCompare(b));for(let w of h){let b=g.get(w);c+=1;let I=b[d];if(!I)continue;let A=b[t]??I,L=A===b[t]?t:d;try{let x=await Wo.readFile(A,"utf8"),D=ce(x,{format:L,requireSupportedFormat:!0,schema:o,onWarning:Z=>a.push(`item_format_migration_parse_warning:${w}:${Z}`)});await Wy(A,I,o);let Q=$e(e,u,w,t,r),ae=ut(D,{format:t,schema:o});await C(Q)!==ae&&(await T(Q,ae),a.push(...await z({path:Q,scope:"project",op:n})),i.add(w)),await rt(I),s.add(Bc(e,I)),a.push(...await z({path:I,scope:"project",op:`${n}:remove`})),i.add(w)}catch(x){a.push(`item_format_migration_skipped:${Bc(e,A)}:${By(x)}`)}}}return{target_format:t,scanned:c,migrated:[...i].sort((u,f)=>u.localeCompare(f)),removed:[...s].sort((u,f)=>u.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]="12c59406-7e00-5fe1-bd93-c1f9d8537f01")}catch{}})();var Gy=new Set(["completed","superseded"]);function Ky(e){return e!==void 0&&Gy.has(e)}function Xy(e){if(e.type.trim().toLowerCase()!=="plan")return!1;let t=e.plan_steps??[];return t.length>0&&t.every(n=>n.status==="completed")}import{createHash as Jy}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7cbbb50d-e9bc-5940-9ae6-6270e9c2fcbf")}catch{}})();var Qy=/^[a-z][a-z0-9_-]{0,63}$/u,Zy=new Set(["constructor","prototype"]),Wc="settings:section:write",eg=240;function Qn(e){return`sha256:${Jy("sha256").update(Yo(e)).digest("hex")}`}function Yo(e){return Array.isArray(e)?`[${e.map(t=>Yo(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Yo(Object.getOwnPropertyDescriptor(e,t)?.value)}`).join(",")}}`:String(JSON.stringify(e))}function Gc(e){if(!Qy.test(e)||Zy.has(e))throw new p(`Invalid settings section name "${e.slice(0,80)}". Use 1-64 lowercase letters, digits, underscores or hyphens, starting with a letter.`,m.USAGE,{code:"settings_section_name_invalid",field:"section",required:"Name the section after the package, for example lint or jev."});if(Vi.includes(e))throw new p(`Settings section "${e}" is owned by core settings; extension sections must use another name.`,m.USAGE,{code:"settings_section_reserved",field:"section",value:e,required:"Read core settings with readSettings and change them with writeSettings or pm config."})}function Kc(e){let t;try{t=JSON.parse(e)}catch{t=void 0}if(typeof t!="object"||t===null||Array.isArray(t))throw new p("settings.json is not a JSON object, so no settings section can be read or written.",m.USAGE,{code:"settings_section_document_malformed",reason:t===void 0?"settings_json_malformed":"settings_json_not_object",nextSteps:["Repair .agents/pm/settings.json so it is a JSON object, then retry.","Run pm health to confirm the settings warning has cleared."]});return t}function Go(e,t,n){let r;try{r=n===void 0?t:n(t)}catch(o){throw new p(`Settings section "${e}" is invalid: ${S(o).slice(0,eg)}`,m.USAGE,{code:"settings_section_invalid",field:e,required:`Fix the "${e}" section of .agents/pm/settings.json so the owning package accepts it, then retry.`})}return r}function Xc(e){return typeof Reflect.get(e,"toJSON")=="function"}function Ko(e){return e.length===0?"the value":e.join(".")}function Jc(e,t){return Object.values(Object.getOwnPropertyDescriptors(e)).every(n=>"value"in n&&(!t||n.enumerable===!0))}function tg(e){if(Object.getPrototypeOf(e)!==Array.prototype||!Jc(e,!1))return!1;let t=Object.keys(e);return t.length===e.length&&t.every((n,r)=>n===String(r))&&Object.getOwnPropertyNames(e).length===e.length+1&&Object.getOwnPropertySymbols(e).length===0&&!Xc(e)}function ng(e){let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Jc(e,!0)&&Object.getOwnPropertySymbols(e).length===0&&!Xc(e)}function rg(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return null;let n=Ko(t);return typeof e=="number"?Number.isFinite(e)?null:{detail:`${n} is a non-finite number`,representable:!0}:{detail:`${n} is ${typeof e}`,representable:typeof e!="bigint"&&t.length>0}}function Qc(e,t=[],n=new Set){if(typeof e!="object"||e===null)return rg(e,t);let r=Ko(t);if(n.has(e))return{detail:`${r} is a circular reference`,representable:!1};if(!(Array.isArray(e)?tg(e):ng(e)))return{detail:`${r} is not a plain JSON ${Array.isArray(e)?"array":"object"}`,representable:!0};n.add(e);for(let[o,i]of Object.entries(e)){let s=Qc(i,[...t,o],n);if(s!==null)return s}return n.delete(e),null}function Zc(e,t=[]){if(typeof e!="object"||e===null)return null;for(let[n,r]of Object.entries(e)){let o=[...t,n];if(n==="__proto__"||n==="prototype"&&t.at(-1)==="constructor")return Ko(o);let i=Zc(r,o);if(i!==null)return i}return null}function Yc(e,t,n){return Go(e,t,()=>{throw new Error(n)})}function og(e,t){let n=Qc(t);if(n!==null){let o=n.representable?`the value would change when stored as JSON: ${n.detail}`:`the value is not representable as JSON: ${n.detail}`;return Yc(e,t,o)}let r=Zc(t);return r!==null?Yc(e,t,`${r} is a reserved key that settings history cannot record`):JSON.parse(JSON.stringify(t))}function ed(e,t){return Object.hasOwn(e,t)?e[t]:void 0}async function ig(e,t,n={}){Gc(t);let r=we(e);await Ee({path:r,scope:"project"});let o=await C(r),i=o===null?void 0:ed(Kc(o),t);if(i===void 0)return{section:t,source:"default",value:n.defaultValue,revision:null};let s=Qn(i);return{section:t,source:"stored",value:Go(t,structuredClone(i),n.validate),revision:s}}async function sg(e,t,n,r={}){Gc(t);let o=n===void 0?void 0:og(t,Go(t,n,r.validate)),i=we(e),s=await Y(e);try{let a=await vr({pmRoot:e,filePath:i,op:Wc,author:mt(r.author,s.author_default),lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,recordCreation:!1,mutate:c=>{if(c===null)throw new p("settings.json does not exist, so no settings section can be written.",m.NOT_FOUND,{code:"settings_section_document_missing",required:"Initialize the tracker with pm init, then retry."});let d=Kc(c),l=ed(d,t),u=l===void 0?null:Qn(l);if(r.expectedRevision!==void 0&&r.expectedRevision!==u)throw new p(`Settings section "${t}" changed since it was read; read it again and reapply the change.`,m.CONFLICT,{code:"settings_section_revision_conflict",field:t,expected_revision:r.expectedRevision,current_revision:u,required:"Read the section again with readSettingsSection, then retry with its current revision."});let f={section:t,changed:!1,previous_revision:u,revision:o===void 0?null:Qn(o)};return nt(l,o)?{raw:c,result:f}:(o===void 0?delete d[t]:d[t]=o,{raw:`${JSON.stringify(d,null,2)}
110
+ `,result:{...f,changed:!0}})}});return a.changed&&await z({path:i,scope:"project",op:Wc}),a.result}finally{rn(e)}}import ag from"node:readline/promises";import{stdin as cg,stdout as td}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]="88db9929-8e1d-56ad-9a5f-6cc0febadfb3")}catch{}})();var dg="PM_TELEMETRY_PROMPT",nd=new Set(["0","false","no","off"]),lg=new Set(["init","completion","completion-statuses","completion-tags","completion-types"]);function ug(e){return typeof e!="string"?!1:nd.has(e.trim().toLowerCase())}function mg(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t.length===0?!1:!nd.has(t)}function fg(e,t){if(t.json===!0||t.quiet===!0||process.stdin.isTTY!==!0||process.stdout.isTTY!==!0||ug(process.env[dg])||mg(process.env.CI))return!0;let n=e.trim().toLowerCase();return n.length===0?!0:lg.has(n)}function pg(e){let t=e.trim().toLowerCase();return!(t==="n"||t==="no")}async function _g(e){let t=`pm telemetry helps improve reliability and usage diagnostics.
111
111
  It is enabled by default and can be changed anytime via:
112
112
  pm config global set telemetry-tracking --policy disabled
113
- Enable telemetry now? [${e?"Y/n":"y/N"}] `,n=ig.createInterface({input:sg,output:Jc});try{let r=await n.question(t);return r.trim().length===0?e:mg(r)}finally{n.close()}}async function pg(e,t){if(!(K().telemetry_disabled||ug(e,t)))try{let n=me(process.cwd()),r=await Y(n);if(r.telemetry.first_run_prompt_completed||yt(r))return;let o=await fg(r.telemetry.enabled);r.telemetry.enabled=o,r.telemetry.first_run_prompt_completed=!0,await gt(n,r,"telemetry:first_run_prompt"),Jc.write(`Telemetry ${o?"enabled":"disabled"} for this CLI install. Update any time with pm config global set telemetry-tracking --policy ${o?"disabled":"enabled"}.
114
- `)}catch{}}import J from"node:crypto";import{spawn as yg}from"node:child_process";import{mkdirSync as Ko,rmSync as gg,statSync as ld}from"node:fs";import{mkdir as Xo,readdir as wg,rm as ri,stat as ud}from"node:fs/promises";import{request as bg}from"node:http";import{request as Eg}from"node:https";import oi from"node:os";import O from"node:path";import _g from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f455b67-536a-59be-8f25-1dc9c9c0b917")}catch{}})();async function Zc(e,t,n,r=process.env,o=Date.now()){if(!n||!Un.has(t))return 1;if(r.PM_TELEMETRY_READ_SAMPLE_RATE!==void 0)return Ba(t,!0,r);try{let i=_g.join(e,"runtime","telemetry","read-sampling.json"),s=Math.floor(o/6e4),a=hg(await C(i),s),c=Math.min(Number.MAX_SAFE_INTEGER,(a[t]??0)+1);return a[t]=c,await T(i,`${JSON.stringify({minute:s,counts:a})}
115
- `),Math.min(1,(10/c)**2)}catch{return 1}}function hg(e,t){let n={},r;try{r=JSON.parse(e??"null")}catch{return n}if(typeof r!="object"||r===null||!("minute"in r)||r.minute!==t||!("counts"in r)||typeof r.counts!="object"||r.counts===null)return n;for(let[o,i]of Object.entries(r.counts))Un.has(o)&&typeof i=="number"&&Number.isSafeInteger(i)&&i>=0&&(n[o]=i);return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ca73b84-5485-515a-a836-7fcce9851fb6")}catch{}})();var Sg=O.join("runtime","telemetry","events.jsonl"),vg=O.join("runtime","telemetry","state.json"),Tg=O.join("runtime","telemetry","otel-spans.jsonl"),Ig=8,ed=500,nr=1,td=1,Cg=100,Ag=36e5,xg=3e4,nd=2e4,Rg=1e3,kg=25e3,ii=250,Og=864e5,rr=65536,md=6,fd=20,pd=15,Dg=8192,_d=[25,50,100,200],Ng=3600*1e3,Mg=1440*60*1e3,hd=6e4,Lg=6e4,Pg="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",$g="OTEL_EXPORTER_OTLP_ENDPOINT",Fg="OTEL_SERVICE_NAME",jg="PM_TELEMETRY_OTEL_DISABLED",Ug=new Set(["1","true","yes","on"]),zg="PM_TELEMETRY_INLINE_FLUSH",ue="PM_TELEMETRY_FLUSH_CHILD",Vg="PM_TELEMETRY_HTTP_TIMEOUT_MS",Hg=globalThis.fetch,rd=!1,Jo=Promise.resolve(),od=Promise.resolve(),Zn=new WeakMap;var qg=new Set(["1","true","yes","on"]),Bg=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]),or=J.randomUUID(),Wg=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],Yg=new Set(["literal","literals","regex","regexes","replacement","replacements","setjson","set_json","update"]),yd="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",Gg=new RegExp(`\\b(${yd})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),Kg=new RegExp(`(--${yd})(=|\\s+)([^\\s,;]+)`,"giu"),Xg=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,Jg=/bearer\s+[a-z0-9._=-]+/giu,Qg=/\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 qt(e,t=U().endpoint){return O.join(O.dirname(O.join(e,Sg)),zt("events.jsonl",t))}function Bt(e){return O.join(e,Tg)}function Zg(e){return O.dirname(qt(e,null))}function gd(e,t=U().endpoint){return O.join(O.dirname(O.join(e,vg)),zt("state.json",t))}function si(e){return O.join(e,"runtime","telemetry","flush.lock")}function wd(e){return O.join(e,"runtime","telemetry","flush.spawn.lock")}function ew(){return O.join(ct(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function tw(){return se(process.env[zg])||se(process.env[ue])?!0:jn()}async function nw(e,t=U().endpoint){let n=await C(gd(e,t));if(!n||n.trim().length===0)return{};try{let r=JSON.parse(n);return typeof r!="object"||r===null||Array.isArray(r)?{}:r}catch{return{}}}async function er(e,t,n=U().endpoint){try{await ge(async()=>{let r={...await nw(e,n),...t},o=Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0).sort((i,s)=>i[0].localeCompare(s[0])));await T(gd(e,n),`${JSON.stringify(o,null,2)}
116
- `,{createParentDirectories:!se(process.env[ue])})},e)}catch{}}function Zo(e){let t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),n=t.split("_").filter(r=>r.length>0);return Yg.has(t)||Wg.some(r=>t===r||t.endsWith(`_${r}`)||n.includes(r))}function bd(e){return e.replaceAll(Gg,(t,n,r)=>`${n}${r}[redacted]`).replaceAll(Kg,(t,n,r)=>`${n}${r}[redacted]`)}function Ed(e){return e.replaceAll(Xg,(t,n)=>`${n}[redacted_path]`)}function Sd(e){let t=e>=65&&e<=90,n=e>=97&&e<=122,r=e>=48&&e<=57;return t||n||r}function vd(e){if(!e)return!1;let t=e.charCodeAt(0);return Sd(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function Td(e){if(!e)return!1;let t=e.charCodeAt(0);return Sd(t)?!0:e==="."||e==="-"}function rw(e){let t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@")||t===e.length-1)return!1;let n=e.slice(0,t),r=e.slice(t+1),o=r.lastIndexOf(".");if(o<=0||o===r.length-1||r.length-(o+1)<2)return!1;for(let i of n)if(!vd(i))return!1;for(let i of r)if(!Td(i))return!1;return!0}function ow(e){let t="",n=0;for(;n<e.length;){let r=e.indexOf("@",n);if(r<0){t+=e.slice(n);break}let o=r-1;for(;o>=n&&vd(e[o]);)o-=1;o+=1;let i=r+1;for(;i<e.length&&Td(e[i]);)i+=1;let s=e.slice(o,i);if(rw(s)){t+=e.slice(n,o),t+="[redacted_email]",n=i;continue}t+=e.slice(n,r+1),n=r+1}return t}function Id(e){return ow(Kt(e)).replaceAll(Jg,"bearer [redacted_token]").replaceAll(Qg,"[redacted_ip]")}function iw(e){let t=Id(e),n=bd(t),r=Ed(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>512?`${r.slice(0,509)}...`:r}function sw(e){let t=Id(e),n=bd(t),r=Ed(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>2048?`${r.slice(0,2045)}...`:r}function k(e,t="redacted"){return t==="max"?sw(e):iw(e)}function Pe(e,t,n="redacted",r=0){if(t&&Zo(t))return"[redacted]";if(e==null)return e;if(typeof e=="string")return k(e,n);if(typeof e=="number"||typeof e=="boolean")return e;if(r>=md)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,fd).map(o=>Pe(o,void 0,n,r+1));if(typeof e=="object"){let o=e,i={};for(let[s,a]of Object.entries(o))i[s]=Pe(a,s,n,r+1);return i}return String(e)}function Cd(e,t="redacted"){let n=[],r=!1;for(let o of e){let i=k(Ai(o),t);if(r){n.push("[redacted]"),r=!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);Zo(c)?n.push(`--${c}=[redacted]`):n.push(`--${c}=${k(d,t)}`);continue}if(Zo(s)){n.push(`--${s}`),r=!0;continue}}n.push(i)}return n}function aw(e){let t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function se(e){return qg.has((e??"").trim().toLowerCase())}function id(){let e=process.env[Vg]?.trim();if(!e)return nd;let t=Number(e);return Number.isFinite(t)?Math.min(kg,Math.max(Rg,Math.trunc(t))):nd}async function Ad(e,t,n){let r=new URL(e);if(globalThis.fetch!==Hg){let i=new AbortController,s,a=new Promise((c,d)=>{s=setTimeout(()=>{i.abort(),d(new Error("telemetry_http_timeout"))},id())});try{return(await Promise.race([globalThis.fetch(e,{method:"POST",headers:t,body:n,signal:i.signal}),a])).status}finally{clearTimeout(s)}}let o=r.protocol==="https:"?Eg:r.protocol==="http:"?bg:void 0;if(!o)throw new Error(`telemetry_http_protocol_unsupported_${r.protocol}`);return new Promise((i,s)=>{let a=id(),c={method:"POST",headers:{...t,"content-length":Buffer.byteLength(n)},signal:AbortSignal.timeout(a),autoSelectFamilyAttemptTimeout:Math.min(5e3,a)},d=o(r,c,l=>{l.once("error",s),l.once("end",()=>i(l.statusCode)),l.resume()});d.once("error",s),d.end(n)})}function xd(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function ai(e){let t=e?.trim();return t&&t.length>0?t:void 0}function ci(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Rd(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?Yt(e.errorCode):"unknown"}function kd(e){let t=Je(e);return t.source_context_source==="env_override_rejected"&&!rd&&!e.quiet&&(rd=!0,process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${Fn.join("|")}; ignoring override.
117
- `)),t}function F(e,t){return J.createHash("sha256").update(`${e}:${t}`).digest("hex")}function di(e,t){let n=(br()??"").trim(),r=Fi({env:process.env,argv:process.argv}),o=r.harness!==void 0||r.model!==void 0;return e==="minimal"?{has_author_context:n.length>0,has_agent_context:o}:{agent_harness:r.harness?Bg.has(r.harness)?r.harness:"other":"none",ci:se(process.env.CI),...n.length>0?{author_context_hash:F(t,n)}:{},...r.harness?{agent_harness_hash:F(t,r.harness)}:{},...r.model?{agent_model_hash:F(t,r.model)}:{},...r.model_source?{agent_model_source:r.model_source}:{}}}function ei(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=md)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,fd).map(n=>ei(n,t+1));if(typeof e=="object"){let n=e,r={},o=Object.keys(n).sort((i,s)=>i.localeCompare(s));for(let i of o)r[i]=ei(n[i],t+1);return r}return String(e)}function ti(e,t){return F(e,JSON.stringify(ei(t)))}function Od(e,t){return{hashes:t.map(n=>F(e,n)),digest:F(e,t.join("\0"))}}function Dd(e,t,n,r){let o=k(typeof r=="string"?r:"","redacted"),i=typeof n=="string"&&n.length>0?n:"unknown_error",s=`${t}\0${i}\0${o}`;return F(e,s)}function cw(){if(Ug.has((process.env[jg]??"").trim().toLowerCase()))return null;let e=(process.env[Pg]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}let t=(process.env[$g]??"").trim();if(t.length===0)return null;try{let n=new URL(t),r=n.pathname.replace(/\/+$/,"");return r.endsWith("/v1/traces")||(n.pathname=`${r.length===0?"":r}/v1/traces`),n.toString()}catch{return null}}function sd(e){let t=Date.parse(e),n=Number.isNaN(t)?Date.now():t;return`${BigInt(n)*1000000n}`}function V(e,t){return{key:e,value:{stringValue:t}}}function dw(e,t){return{key:e,value:{boolValue:t}}}function ad(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function lw(e,t,n,r,o=1){let i=e.otel_traces_endpoint;if(typeof i!="string"||i.trim().length===0||[e.otel_trace_id,e.otel_span_id].some(_=>typeof _!="string"||_.length===0))return null;let s=k((process.env[Fg]??"").trim()),a=s.length>0?s:"pm-cli",c=ci(t.exit_code,t.ok),d=ai(t.error_code),l=Rd({ok:t.ok,errorCode:d,errorCategory:t.error_category}),u=[V("pm.command",k(e.command)),V("pm.version",e.pm_version),V("pm.source_context",e.source_context),V("pm.source_context_source",e.source_context_source),V("pm.installation_id",e.installation_id),V("pm.session_id",or),V("pm.pm_root_hash",e.pm_root_hash),V("pm.cwd_hash",e.cwd_hash),dw("pm.ok",t.ok),ad("pm.exit_code",c),ad("pm.duration_ms",r),V("pm.sample_rate",String(o))];typeof d=="string"&&u.push(V("pm.error_code",d)),typeof l=="string"&&u.push(V("pm.error_category",l)),typeof t.error=="string"&&t.error.trim().length>0&&u.push(V("pm.error",k(t.error)));let f={resourceSpans:[{resource:{attributes:[V("service.name",a)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:e.otel_trace_id,spanId:e.otel_span_id,name:`pm.command.${k(e.command)}`,kind:1,startTimeUnixNano:sd(e.started_at),endTimeUnixNano:sd(n),attributes:u,status:{code:t.ok?1:2,message:t.ok?"":k(typeof t.error=="string"?t.error:"command_failed")}}]}]}]};return{endpoint:i,payload:f}}function uw(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:k(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(n=>Pe(n,void 0,t))};if(typeof e=="object"){let n=e,r=Object.keys(n).filter(s=>s!=="tests").sort((s,a)=>s.localeCompare(a)),o={},i=0;for(let s of r.slice(0,25)){let a=Pe(n[s],s,t);if(a===void 0)continue;let c=JSON.stringify(a).length;if(i+c>Dg){o[s]="[preview_truncated]";break}i+=c,o[s]=a}return{type:"object",key_count:r.length,keys_preview:r.slice(0,50),preview:o}}return{type:typeof e,value:String(e)}}function mw(e){let{captureLevel:t,context:n,pmVersion:r,sourceContext:o,pmRootHash:i,cwdHash:s,installationId:a}=e,c=De(n.command),d=Od(a,n.args),l=F(a,`${n.command}\0${n.args.join("\0")}`),u=ti(a,n.options),f=ti(a,n.global),_=di(t,a);return t==="minimal"?{capture_level:t,pm_version:r,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,command_args_digest:d.digest,command_invocation_digest:l,command_options_digest:u,global_options_digest:f,..._}:{pm_version:r,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,..._,command_args:Cd(n.args,t),command_args_hashes:d.hashes,command_args_digest:d.digest,command_invocation_digest:l,command_options:Pe(n.options,void 0,t),command_options_digest:u,global_options:Pe(n.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:F(a,oi.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function fw(e){let{captureLevel:t,pmVersion:n,sourceContext:r,outcome:o,durationMs:i,startedAt:s,command:a,installationId:c,commandTaxonomy:d,exitCode:l,errorCode:u,errorCategory:f,commandResolution:_,resolutionStage:y}=e,g=o.ok===!1?Dd(c,a,u,o.error):void 0,h=di(t,c);return t==="minimal"?{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:d,command_resolution:_,resolution_stage:y,ok:o.ok,exit_code:l,error_code:u,error_category:f,error:o.error?k(o.error,"redacted"):void 0,error_fingerprint:g,duration_ms:i,...h}:{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:d,command_resolution:_,resolution_stage:y,...h,ok:o.ok,exit_code:l,error_code:u,error_category:f,error:o.error?k(o.error,t):void 0,error_fingerprint:g,duration_ms:i,started_at:s,result_summary:uw(o.result,t)}}function pw(e){let{captureLevel:t,pmVersion:n,sourceContext:r,command:o,commandTaxonomy:i,commandResolution:s,resolutionStage:a,args:c,options:d,pmRootHash:l,cwdHash:u,installationId:f,errorCode:_,errorMessage:y,errorCategory:g,exitCode:h}=e,w=Od(f,c),b=F(f,o),I=ti(f,d),A=Dd(f,o,_,y),L=di(t,f);return t==="minimal"?{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,attempted_command_digest:b,attempted_args_digest:w.digest,attempted_options_digest:I,error_code:_,error_category:g,exit_code:h,error:k(y,"redacted"),error_fingerprint:A,...L}:{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,...L,attempted_command:k(o,t),attempted_command_digest:b,attempted_args:Cd(c,t),attempted_args_hashes:w.hashes,attempted_args_digest:w.digest,attempted_options:Pe(d,void 0,t),attempted_options_digest:I,error_code:_,error_category:g,exit_code:h,error:k(y,t),error_fingerprint:A,pm_root_hash:l,cwd_hash:u,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:F(f,oi.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function li(e){let t=await Y(e);if(!t.telemetry.enabled||K().telemetry_disabled)return null;if(t.telemetry.installation_id.trim().length===0){if(Ir(e)||yt(t))return null;t.telemetry.installation_id=J.randomUUID(),await gt(e,t,"telemetry:install_id")}return{installationId:t.telemetry.installation_id,endpoint:t.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(t.telemetry.retention_days)),captureLevel:aw(t.telemetry.capture_level)}}async function tr(e,t){let n=JSON.stringify({client_schema_version:td,event:t,attempts:0});if(n.length>rr){let r={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:n.length}}};n=JSON.stringify({client_schema_version:td,event:r,attempts:0})}await dr(qt(e),n)}function Nd(e){let t=[];for(let n of e.split(`
118
- `)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);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 Md(e){let t=Math.min(xg*2**Math.max(e-1,0),Ag);return new Date(Date.now()+t).toISOString()}function ui(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 Ld(e){return ui(e.next_attempt_after)}function Pd(e){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*Og}function _w(e,t){let n=e.event?.occurred_at;if(typeof n!="string"||n.trim().length===0)return!1;let r=Date.parse(n);return Number.isNaN(r)?!1:r<t}function ir(e,t){let n=Pd(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>rr||_w(i,n)||i.attempts>=pd){o+=1;continue}r.push(i)}return{entries:r,prunedCount:o}}async function $d(e,t,n=U().endpoint){let r=t.map(i=>JSON.stringify(i)).join(`
113
+ Enable telemetry now? [${e?"Y/n":"y/N"}] `,n=ag.createInterface({input:cg,output:td});try{let r=await n.question(t);return r.trim().length===0?e:pg(r)}finally{n.close()}}async function hg(e,t){if(!(K().telemetry_disabled||fg(e,t)))try{let n=me(process.cwd()),r=await Y(n);if(r.telemetry.first_run_prompt_completed||yt(r))return;let o=await _g(r.telemetry.enabled);r.telemetry.enabled=o,r.telemetry.first_run_prompt_completed=!0,await gt(n,r,"telemetry:first_run_prompt"),td.write(`Telemetry ${o?"enabled":"disabled"} for this CLI install. Update any time with pm config global set telemetry-tracking --policy ${o?"disabled":"enabled"}.
114
+ `)}catch{}}import J from"node:crypto";import{spawn as wg}from"node:child_process";import{mkdirSync as Xo,rmSync as bg,statSync as pd}from"node:fs";import{mkdir as Jo,readdir as Eg,rm as oi,stat as _d}from"node:fs/promises";import{request as Sg}from"node:http";import{request as vg}from"node:https";import ii from"node:os";import O from"node:path";import yg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f455b67-536a-59be-8f25-1dc9c9c0b917")}catch{}})();async function rd(e,t,n,r=process.env,o=Date.now()){if(!n||!Un.has(t))return 1;if(r.PM_TELEMETRY_READ_SAMPLE_RATE!==void 0)return Ka(t,!0,r);try{let i=yg.join(e,"runtime","telemetry","read-sampling.json"),s=Math.floor(o/6e4),a=gg(await C(i),s),c=Math.min(Number.MAX_SAFE_INTEGER,(a[t]??0)+1);return a[t]=c,await T(i,`${JSON.stringify({minute:s,counts:a})}
115
+ `),Math.min(1,(10/c)**2)}catch{return 1}}function gg(e,t){let n={},r;try{r=JSON.parse(e??"null")}catch{return n}if(typeof r!="object"||r===null||!("minute"in r)||r.minute!==t||!("counts"in r)||typeof r.counts!="object"||r.counts===null)return n;for(let[o,i]of Object.entries(r.counts))Un.has(o)&&typeof i=="number"&&Number.isSafeInteger(i)&&i>=0&&(n[o]=i);return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ca73b84-5485-515a-a836-7fcce9851fb6")}catch{}})();var Tg=O.join("runtime","telemetry","events.jsonl"),Ig=O.join("runtime","telemetry","state.json"),Cg=O.join("runtime","telemetry","otel-spans.jsonl"),Ag=8,od=500,nr=1,id=1,xg=100,Rg=36e5,kg=3e4,sd=2e4,Og=1e3,Dg=25e3,si=250,Ng=864e5,rr=65536,hd=6,yd=20,gd=15,Mg=8192,wd=[25,50,100,200],Lg=3600*1e3,Pg=1440*60*1e3,bd=6e4,$g=6e4,Fg="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",jg="OTEL_EXPORTER_OTLP_ENDPOINT",Ug="OTEL_SERVICE_NAME",zg="PM_TELEMETRY_OTEL_DISABLED",Vg=new Set(["1","true","yes","on"]),Hg="PM_TELEMETRY_INLINE_FLUSH",ue="PM_TELEMETRY_FLUSH_CHILD",qg="PM_TELEMETRY_HTTP_TIMEOUT_MS",Bg=globalThis.fetch,ad=!1,Qo=Promise.resolve(),cd=Promise.resolve(),Zn=new WeakMap;var Wg=new Set(["1","true","yes","on"]),Yg=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]),or=J.randomUUID(),Gg=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],Kg=new Set(["literal","literals","regex","regexes","replacement","replacements","setjson","set_json","update"]),Ed="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",Xg=new RegExp(`\\b(${Ed})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),Jg=new RegExp(`(--${Ed})(=|\\s+)([^\\s,;]+)`,"giu"),Qg=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,Zg=/bearer\s+[a-z0-9._=-]+/giu,ew=/\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 qt(e,t=U().endpoint){return O.join(O.dirname(O.join(e,Tg)),zt("events.jsonl",t))}function Bt(e){return O.join(e,Cg)}function tw(e){return O.dirname(qt(e,null))}function Sd(e,t=U().endpoint){return O.join(O.dirname(O.join(e,Ig)),zt("state.json",t))}function ai(e){return O.join(e,"runtime","telemetry","flush.lock")}function vd(e){return O.join(e,"runtime","telemetry","flush.spawn.lock")}function nw(){return O.join(ct(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function rw(){return se(process.env[Hg])||se(process.env[ue])?!0:jn()}async function ow(e,t=U().endpoint){let n=await C(Sd(e,t));if(!n||n.trim().length===0)return{};try{let r=JSON.parse(n);return typeof r!="object"||r===null||Array.isArray(r)?{}:r}catch{return{}}}async function er(e,t,n=U().endpoint){try{await ge(async()=>{let r={...await ow(e,n),...t},o=Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0).sort((i,s)=>i[0].localeCompare(s[0])));await T(Sd(e,n),`${JSON.stringify(o,null,2)}
116
+ `,{createParentDirectories:!se(process.env[ue])})},e)}catch{}}function ei(e){let t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),n=t.split("_").filter(r=>r.length>0);return Kg.has(t)||Gg.some(r=>t===r||t.endsWith(`_${r}`)||n.includes(r))}function Td(e){return e.replaceAll(Xg,(t,n,r)=>`${n}${r}[redacted]`).replaceAll(Jg,(t,n,r)=>`${n}${r}[redacted]`)}function Id(e){return e.replaceAll(Qg,(t,n)=>`${n}[redacted_path]`)}function Cd(e){let t=e>=65&&e<=90,n=e>=97&&e<=122,r=e>=48&&e<=57;return t||n||r}function Ad(e){if(!e)return!1;let t=e.charCodeAt(0);return Cd(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function xd(e){if(!e)return!1;let t=e.charCodeAt(0);return Cd(t)?!0:e==="."||e==="-"}function iw(e){let t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@")||t===e.length-1)return!1;let n=e.slice(0,t),r=e.slice(t+1),o=r.lastIndexOf(".");if(o<=0||o===r.length-1||r.length-(o+1)<2)return!1;for(let i of n)if(!Ad(i))return!1;for(let i of r)if(!xd(i))return!1;return!0}function sw(e){let t="",n=0;for(;n<e.length;){let r=e.indexOf("@",n);if(r<0){t+=e.slice(n);break}let o=r-1;for(;o>=n&&Ad(e[o]);)o-=1;o+=1;let i=r+1;for(;i<e.length&&xd(e[i]);)i+=1;let s=e.slice(o,i);if(iw(s)){t+=e.slice(n,o),t+="[redacted_email]",n=i;continue}t+=e.slice(n,r+1),n=r+1}return t}function Rd(e){return sw(Kt(e)).replaceAll(Zg,"bearer [redacted_token]").replaceAll(ew,"[redacted_ip]")}function aw(e){let t=Rd(e),n=Td(t),r=Id(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>512?`${r.slice(0,509)}...`:r}function cw(e){let t=Rd(e),n=Td(t),r=Id(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>2048?`${r.slice(0,2045)}...`:r}function k(e,t="redacted"){return t==="max"?cw(e):aw(e)}function Pe(e,t,n="redacted",r=0){if(t&&ei(t))return"[redacted]";if(e==null)return e;if(typeof e=="string")return k(e,n);if(typeof e=="number"||typeof e=="boolean")return e;if(r>=hd)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,yd).map(o=>Pe(o,void 0,n,r+1));if(typeof e=="object"){let o=e,i={};for(let[s,a]of Object.entries(o))i[s]=Pe(a,s,n,r+1);return i}return String(e)}function kd(e,t="redacted"){let n=[],r=!1;for(let o of e){let i=k(xi(o),t);if(r){n.push("[redacted]"),r=!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);ei(c)?n.push(`--${c}=[redacted]`):n.push(`--${c}=${k(d,t)}`);continue}if(ei(s)){n.push(`--${s}`),r=!0;continue}}n.push(i)}return n}function dw(e){let t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function se(e){return Wg.has((e??"").trim().toLowerCase())}function dd(){let e=process.env[qg]?.trim();if(!e)return sd;let t=Number(e);return Number.isFinite(t)?Math.min(Dg,Math.max(Og,Math.trunc(t))):sd}async function Od(e,t,n){let r=new URL(e);if(globalThis.fetch!==Bg){let i=new AbortController,s,a=new Promise((c,d)=>{s=setTimeout(()=>{i.abort(),d(new Error("telemetry_http_timeout"))},dd())});try{return(await Promise.race([globalThis.fetch(e,{method:"POST",headers:t,body:n,signal:i.signal}),a])).status}finally{clearTimeout(s)}}let o=r.protocol==="https:"?vg:r.protocol==="http:"?Sg:void 0;if(!o)throw new Error(`telemetry_http_protocol_unsupported_${r.protocol}`);return new Promise((i,s)=>{let a=dd(),c={method:"POST",headers:{...t,"content-length":Buffer.byteLength(n)},signal:AbortSignal.timeout(a),autoSelectFamilyAttemptTimeout:Math.min(5e3,a)},d=o(r,c,l=>{l.once("error",s),l.once("end",()=>i(l.statusCode)),l.resume()});d.once("error",s),d.end(n)})}function Dd(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function ci(e){let t=e?.trim();return t&&t.length>0?t:void 0}function di(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Nd(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?Yt(e.errorCode):"unknown"}function Md(e){let t=Je(e);return t.source_context_source==="env_override_rejected"&&!ad&&!e.quiet&&(ad=!0,process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${Fn.join("|")}; ignoring override.
117
+ `)),t}function F(e,t){return J.createHash("sha256").update(`${e}:${t}`).digest("hex")}function li(e,t){let n=(br()??"").trim(),r=ji({env:process.env,argv:process.argv}),o=r.harness!==void 0||r.model!==void 0;return e==="minimal"?{has_author_context:n.length>0,has_agent_context:o}:{agent_harness:r.harness?Yg.has(r.harness)?r.harness:"other":"none",ci:se(process.env.CI),...n.length>0?{author_context_hash:F(t,n)}:{},...r.harness?{agent_harness_hash:F(t,r.harness)}:{},...r.model?{agent_model_hash:F(t,r.model)}:{},...r.model_source?{agent_model_source:r.model_source}:{}}}function ti(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=hd)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,yd).map(n=>ti(n,t+1));if(typeof e=="object"){let n=e,r={},o=Object.keys(n).sort((i,s)=>i.localeCompare(s));for(let i of o)r[i]=ti(n[i],t+1);return r}return String(e)}function ni(e,t){return F(e,JSON.stringify(ti(t)))}function Ld(e,t){return{hashes:t.map(n=>F(e,n)),digest:F(e,t.join("\0"))}}function Pd(e,t,n,r){let o=k(typeof r=="string"?r:"","redacted"),i=typeof n=="string"&&n.length>0?n:"unknown_error",s=`${t}\0${i}\0${o}`;return F(e,s)}function lw(){if(Vg.has((process.env[zg]??"").trim().toLowerCase()))return null;let e=(process.env[Fg]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}let t=(process.env[jg]??"").trim();if(t.length===0)return null;try{let n=new URL(t),r=n.pathname.replace(/\/+$/,"");return r.endsWith("/v1/traces")||(n.pathname=`${r.length===0?"":r}/v1/traces`),n.toString()}catch{return null}}function ld(e){let t=Date.parse(e),n=Number.isNaN(t)?Date.now():t;return`${BigInt(n)*1000000n}`}function V(e,t){return{key:e,value:{stringValue:t}}}function uw(e,t){return{key:e,value:{boolValue:t}}}function ud(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function mw(e,t,n,r,o=1){let i=e.otel_traces_endpoint;if(typeof i!="string"||i.trim().length===0||[e.otel_trace_id,e.otel_span_id].some(_=>typeof _!="string"||_.length===0))return null;let s=k((process.env[Ug]??"").trim()),a=s.length>0?s:"pm-cli",c=di(t.exit_code,t.ok),d=ci(t.error_code),l=Nd({ok:t.ok,errorCode:d,errorCategory:t.error_category}),u=[V("pm.command",k(e.command)),V("pm.version",e.pm_version),V("pm.source_context",e.source_context),V("pm.source_context_source",e.source_context_source),V("pm.installation_id",e.installation_id),V("pm.session_id",or),V("pm.pm_root_hash",e.pm_root_hash),V("pm.cwd_hash",e.cwd_hash),uw("pm.ok",t.ok),ud("pm.exit_code",c),ud("pm.duration_ms",r),V("pm.sample_rate",String(o))];typeof d=="string"&&u.push(V("pm.error_code",d)),typeof l=="string"&&u.push(V("pm.error_category",l)),typeof t.error=="string"&&t.error.trim().length>0&&u.push(V("pm.error",k(t.error)));let f={resourceSpans:[{resource:{attributes:[V("service.name",a)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:e.otel_trace_id,spanId:e.otel_span_id,name:`pm.command.${k(e.command)}`,kind:1,startTimeUnixNano:ld(e.started_at),endTimeUnixNano:ld(n),attributes:u,status:{code:t.ok?1:2,message:t.ok?"":k(typeof t.error=="string"?t.error:"command_failed")}}]}]}]};return{endpoint:i,payload:f}}function fw(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:k(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(n=>Pe(n,void 0,t))};if(typeof e=="object"){let n=e,r=Object.keys(n).filter(s=>s!=="tests").sort((s,a)=>s.localeCompare(a)),o={},i=0;for(let s of r.slice(0,25)){let a=Pe(n[s],s,t);if(a===void 0)continue;let c=JSON.stringify(a).length;if(i+c>Mg){o[s]="[preview_truncated]";break}i+=c,o[s]=a}return{type:"object",key_count:r.length,keys_preview:r.slice(0,50),preview:o}}return{type:typeof e,value:String(e)}}function pw(e){let{captureLevel:t,context:n,pmVersion:r,sourceContext:o,pmRootHash:i,cwdHash:s,installationId:a}=e,c=De(n.command),d=Ld(a,n.args),l=F(a,`${n.command}\0${n.args.join("\0")}`),u=ni(a,n.options),f=ni(a,n.global),_=li(t,a);return t==="minimal"?{capture_level:t,pm_version:r,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,command_args_digest:d.digest,command_invocation_digest:l,command_options_digest:u,global_options_digest:f,..._}:{pm_version:r,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,..._,command_args:kd(n.args,t),command_args_hashes:d.hashes,command_args_digest:d.digest,command_invocation_digest:l,command_options:Pe(n.options,void 0,t),command_options_digest:u,global_options:Pe(n.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:F(a,ii.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function _w(e){let{captureLevel:t,pmVersion:n,sourceContext:r,outcome:o,durationMs:i,startedAt:s,command:a,installationId:c,commandTaxonomy:d,exitCode:l,errorCode:u,errorCategory:f,commandResolution:_,resolutionStage:y}=e,g=o.ok===!1?Pd(c,a,u,o.error):void 0,h=li(t,c);return t==="minimal"?{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:d,command_resolution:_,resolution_stage:y,ok:o.ok,exit_code:l,error_code:u,error_category:f,error:o.error?k(o.error,"redacted"):void 0,error_fingerprint:g,duration_ms:i,...h}:{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:d,command_resolution:_,resolution_stage:y,...h,ok:o.ok,exit_code:l,error_code:u,error_category:f,error:o.error?k(o.error,t):void 0,error_fingerprint:g,duration_ms:i,started_at:s,result_summary:fw(o.result,t)}}function hw(e){let{captureLevel:t,pmVersion:n,sourceContext:r,command:o,commandTaxonomy:i,commandResolution:s,resolutionStage:a,args:c,options:d,pmRootHash:l,cwdHash:u,installationId:f,errorCode:_,errorMessage:y,errorCategory:g,exitCode:h}=e,w=Ld(f,c),b=F(f,o),I=ni(f,d),A=Pd(f,o,_,y),L=li(t,f);return t==="minimal"?{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,attempted_command_digest:b,attempted_args_digest:w.digest,attempted_options_digest:I,error_code:_,error_category:g,exit_code:h,error:k(y,"redacted"),error_fingerprint:A,...L}:{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,...L,attempted_command:k(o,t),attempted_command_digest:b,attempted_args:kd(c,t),attempted_args_hashes:w.hashes,attempted_args_digest:w.digest,attempted_options:Pe(d,void 0,t),attempted_options_digest:I,error_code:_,error_category:g,exit_code:h,error:k(y,t),error_fingerprint:A,pm_root_hash:l,cwd_hash:u,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:F(f,ii.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function ui(e){let t=await Y(e);if(!t.telemetry.enabled||K().telemetry_disabled)return null;if(t.telemetry.installation_id.trim().length===0){if(Ir(e)||yt(t))return null;t.telemetry.installation_id=J.randomUUID(),await gt(e,t,"telemetry:install_id")}return{installationId:t.telemetry.installation_id,endpoint:t.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(t.telemetry.retention_days)),captureLevel:dw(t.telemetry.capture_level)}}async function tr(e,t){let n=JSON.stringify({client_schema_version:id,event:t,attempts:0});if(n.length>rr){let r={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:n.length}}};n=JSON.stringify({client_schema_version:id,event:r,attempts:0})}await dr(qt(e),n)}function $d(e){let t=[];for(let n of e.split(`
118
+ `)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);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 Fd(e){let t=Math.min(kg*2**Math.max(e-1,0),Rg);return new Date(Date.now()+t).toISOString()}function mi(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 jd(e){return mi(e.next_attempt_after)}function Ud(e){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*Ng}function yw(e,t){let n=e.event?.occurred_at;if(typeof n!="string"||n.trim().length===0)return!1;let r=Date.parse(n);return Number.isNaN(r)?!1:r<t}function ir(e,t){let n=Ud(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>rr||yw(i,n)||i.attempts>=gd){o+=1;continue}r.push(i)}return{entries:r,prunedCount:o}}async function zd(e,t,n=U().endpoint){let r=t.map(i=>JSON.stringify(i)).join(`
119
119
  `),o=r.length>0?`${r}
120
- `:"";for(let i=0;;i+=1)try{await T(qt(e,n),o,{createParentDirectories:!se(process.env[ue])});return}catch(s){let a=_d[i];if(a===void 0||!Fd(s))throw s;await jd(a)}}function Fd(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function jd(e){return new Promise(t=>{setTimeout(t,e)})}async function hw(e,t){let n={id:J.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:$(),attempts:0},r=JSON.stringify(n);r.length>rr||await dr(Bt(e),r)}function yw(e){let t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return J.createHash("sha256").update(t).digest("hex").slice(0,32)}function mi(e){let t=[];for(let n of e.split(`
121
- `)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);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=yw(o)),t.push(o))}catch{}}return t}function gw(e,t){if(typeof e.enqueued_at!="string"||e.enqueued_at.trim().length===0)return!1;let n=Date.parse(e.enqueued_at);return Number.isNaN(n)?!1:n<t}function fi(e,t){let n=Pd(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>rr||gw(i,n)||i.attempts>=pd){o+=1;continue}r.push(i)}if(r.length>ed){let i=r.length-ed;return o+=i,{entries:r.slice(i),prunedCount:o}}return{entries:r,prunedCount:o}}async function ww(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
120
+ `:"";for(let i=0;;i+=1)try{await T(qt(e,n),o,{createParentDirectories:!se(process.env[ue])});return}catch(s){let a=wd[i];if(a===void 0||!Vd(s))throw s;await Hd(a)}}function Vd(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function Hd(e){return new Promise(t=>{setTimeout(t,e)})}async function gw(e,t){let n={id:J.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:$(),attempts:0},r=JSON.stringify(n);r.length>rr||await dr(Bt(e),r)}function ww(e){let t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return J.createHash("sha256").update(t).digest("hex").slice(0,32)}function fi(e){let t=[];for(let n of e.split(`
121
+ `)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);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=ww(o)),t.push(o))}catch{}}return t}function bw(e,t){if(typeof e.enqueued_at!="string"||e.enqueued_at.trim().length===0)return!1;let n=Date.parse(e.enqueued_at);return Number.isNaN(n)?!1:n<t}function pi(e,t){let n=Ud(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>rr||bw(i,n)||i.attempts>=gd){o+=1;continue}r.push(i)}if(r.length>od){let i=r.length-od;return o+=i,{entries:r.slice(i),prunedCount:o}}return{entries:r,prunedCount:o}}async function Ew(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
122
122
  `),r=n.length>0?`${n}
123
- `:"";for(let o=0;;o+=1)try{await T(Bt(e),r,{createParentDirectories:!se(process.env[ue])});return}catch(i){let s=_d[o];if(s===void 0||!Fd(i))throw i;await jd(s)}}async function cd(e,t,n,r){return ge(async()=>{let o=await C(Bt(e)),i=o===null?[]:mi(o),s=[];for(let c of i){if(n.has(c.id))continue;let d=r.get(c.id);s.push(d?{...c,attempts:d.attempts,next_attempt_after:d.next_attempt_after}:c)}let{entries:a}=fi(s,t);return await ww(e,a),a.length},e)}async function bw(e,t){let n=await C(Bt(e));if(n===null||n.trim().length===0){await er(e,{pending_otel_spans:0},null);return}let r=mi(n),{entries:o,prunedCount:i}=fi(r,t),s=o.filter(y=>ui(y.next_attempt_after)).slice(0,Ig);if(s.length===0){let y=i>0?await cd(e,t,new Set,new Map):o.length;await er(e,{pending_otel_spans:y},null);return}let a=$(),c=new Set,d=new Map,l=0,u;await Promise.all(s.map(async y=>{try{let g=await Ad(y.endpoint,{"content-type":"application/json"},JSON.stringify(y.payload));if(g<200||g>=300)throw new Error(`local_otel_export_http_${g}`);c.add(y.id),l+=1}catch(g){u=g instanceof Error?k(Vn(g.message),"redacted"):"local_otel_export_failed";let h=y.attempts+1;d.set(y.id,{attempts:h,next_attempt_after:Md(h)})}}));let f=await cd(e,t,c,d),_={pending_otel_spans:f,last_otel_attempt_at:a};l>0&&(_.last_otel_success_at=a),u!==void 0?(_.last_otel_failure_at=a,_.last_otel_failure_error=u):f===0&&(_.last_otel_failure_at=void 0,_.last_otel_failure_error=void 0),await er(e,_,null)}async function Ud(e,t,n){try{await Tw(e,t,n)}catch{}try{await bw(e,n)}catch{}}async function Ew(e,t=Ng,n=U().endpoint){try{let r=Zg(e),o=await wg(r,{withFileTypes:!0}),i=Date.now(),s=new Set([zt("events.jsonl",n),zt("state.json",n)]),a=c=>{if(!s.has(c))return/^\.events(?:\.[a-f0-9]{16})?\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(c)?i-Math.max(0,t):/^(?:events\.[a-f0-9]{16}\.jsonl|state\.[a-f0-9]{16}\.json)$/.test(c)?i-Mg:void 0};await Promise.all(o.map(async c=>{let d=c.isFile()?a(c.name):void 0;if(d===void 0)return;let l=O.join(r,c.name);(await ud(l)).mtimeMs<d&&await ri(l,{force:!0})}))}catch{}}async function ge(e,t=me(process.cwd()),n=5e3){let r=od.catch(()=>{}).then(()=>Ni(async()=>{let o=await Se(t,"telemetry-queue",60,"telemetry",!1,!1,n,{createParentDirectories:!se(process.env[ue])});try{return rn(t),await e()}finally{await o()}}));return od=r.catch(()=>{}),r}async function sr(e,t=U().endpoint){let n=await C(qt(e,t));return n===null||n.trim().length===0?[]:Nd(n)}async function Qo(e,t,n,r=U().endpoint){return ge(async()=>{let o=await sr(e,r),{entries:i}=ir(o,n),s=i.filter(a=>!t.has(a.event.event_id));return await $d(e,s,r),s},e)}async function Sw(e,t,n,r,o=U().endpoint){return ge(async()=>{let i=await sr(e,o),{entries:s}=ir(i,r),a=s.map(c=>{if(!t.has(c.event.event_id))return c;let d=c.attempts+1;return{...c,attempts:d,last_attempt_at:n,next_attempt_after:Md(d)}});return await $d(e,a,o),a},e)}function vw(e,t){return t===null?e:zn(e)}async function Tw(e,t,n){let r=U().endpoint;await Ew(e,void 0,r);let o=(r??t).trim(),i=vw(o,r),s=h=>er(e,h,r);if(o.length===0)return;let a=await C(qt(e,r));if(a===null||a.trim().length===0){await s({endpoint:i,queue_entries:0});return}let c=Nd(a);if(c.length===0){await s({endpoint:i,queue_entries:0});return}let{entries:d,prunedCount:l}=ir(c,n);if(d.length===0){let h=await Qo(e,new Set,n,r);await s({endpoint:i,queue_entries:h.length});return}let u=d.filter(h=>Ld(h)).slice(0,Cg);if(u.length===0){let h=l>0?await Qo(e,new Set,n,r):d;await s({endpoint:i,queue_entries:h.length});return}let f=new Set(u.map(h=>h.event.event_id)),_=$(),y={"content-type":"application/json"},g=process.env.PM_TELEMETRY_INGEST_KEY?.trim();g&&(y["x-pm-telemetry-key"]=g);try{let h=await Ad(o,y,JSON.stringify({schema_version:nr,events:u.map(w=>w.event)}));if(h<200||h>=300)throw new Error(`telemetry_flush_http_${h}`)}catch(h){let w=await Sw(e,f,_,n,r),b=h instanceof Error?k(Vn(h.message),"redacted"):"telemetry_flush_failed";await s({endpoint:i,queue_entries:w.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:b});return}try{let h=await Qo(e,f,n,r);await s({endpoint:i,queue_entries:h.length,last_attempted_flush_at:_,last_successful_flush_at:_,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(h){let w=h instanceof Error?k(Vn(h.message),"redacted"):"telemetry_flush_failed",b=await sr(e,r).catch(()=>d);await s({endpoint:i,queue_entries:b.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:w})}}async function Iw(e){let t=si(e);se(process.env[ue])||await Xo(O.dirname(t),{recursive:!0});try{return await Xo(t),!0}catch(n){if(typeof n!="object"||n===null||!("code"in n)||n.code!=="EEXIST")throw n}try{let n=await ud(t);return Date.now()-n.mtimeMs<hd?!1:(await ri(t,{recursive:!0,force:!0}),await Xo(t),!0)}catch{return!1}}function Cw(e,t){try{return Date.now()-ld(e).mtimeMs<t}catch{return!1}}function zd(e){try{gg(e,{recursive:!0,force:!0})}catch{}}function Aw(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function xw(e){try{return Ko(e),!0}catch(t){if(Aw(t)==="EEXIST"||!P(t))return!1}try{return Ko(O.dirname(e),{recursive:!0}),Ko(e),!0}catch{return!1}}function Rw(e){if(Cw(si(e),hd))return!1;let t=wd(e);try{if(Date.now()-ld(t).mtimeMs<Lg)return!1;zd(t)}catch(n){if(!P(n))return!1}return xw(t)}function ni(e){zd(wd(e))}async function kw(e,t,n){let r=await Iw(e);if(ni(e),!r)return!1;try{await Ud(e,t,n)}finally{try{await ri(si(e),{recursive:!0,force:!0})}catch{}}return!0}async function dd(e,t){let n=new Set;try{let{entries:r}=ir(await sr(e),t);for(let o of r.filter(Ld))n.add(`event:${o.event.event_id}`)}catch{}try{let r=await C(Bt(e));if(r!==null)for(let o of fi(mi(r),t).entries)ui(o.next_attempt_after)&&n.add(`span:${o.id}`)}catch{}return n}function pi(e,t,n){if(!Ir(e)){if(tw())return Jo=Jo.then(()=>Ud(e,t,n)),Jo;try{if(!Rw(e))return;let r=yg(process.execPath,[ew()],{detached:!0,stdio:"ignore",cwd:oi.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[ue]:"1"}});r.on("error",()=>{ni(e)}),r.unref()}catch{ni(e)}}}async function iC(e=me(process.cwd())){if(!K().telemetry_disabled)try{await Tr(e,async()=>{let t=se(process.env[ue]),n=!0;for(;n;){if(!(await Y(e)).telemetry.enabled)return;let r=await ge(()=>li(e),e);if(!r)return;let o=t?await dd(e,r.retentionDays):new Set;if(!await kw(e,r.endpoint,r.retentionDays)||!t)return;let i=await dd(e,r.retentionDays);n=i.size>0&&(i.size!==o.size||[...i].some(s=>!o.has(s)))}},()=>se(process.env[ue]))}catch{}}async function Ow(e){if(K().telemetry_disabled||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=me(process.cwd());if(!(await Y(t)).telemetry.enabled)return null;let n=e.global.noExtensions===!0||Mi(e.command),r=await ge(async()=>{let o=await li(t);if(!o)return null;let{installationId:i,endpoint:s,retentionDays:a,captureLevel:c}=o,d=xd(e.pm_version),l=kd(e.global),u=F(i,e.pm_root),f=F(i,process.cwd()),_=cw(),y=$(),g={schema_version:nr,event_id:J.randomUUID(),event_type:"command_start",occurred_at:y,installation_id:i,session_id:or,command:e.command,payload:mw({captureLevel:c,context:e,pmVersion:d,sourceContext:l,pmRootHash:u,cwdHash:f,installationId:i})},h=await Zc(t,e.command,n);h===1&&await tr(t,g);let w=De(e.command),b={...h<1?{sample_rate:h}:{},started_at:y,started_at_ms:Date.now(),command:e.command,command_taxonomy:w,pm_version:d,source_context:l.source_context,source_context_source:l.source_context_source,installation_id:i,pm_root_hash:u,cwd_hash:f,endpoint:s,retention_days:a,global_pm_root:t,capture_level:c,otel_traces_endpoint:_??void 0,otel_trace_id:_?J.randomBytes(16).toString("hex"):void 0,otel_span_id:_?J.randomBytes(8).toString("hex"):void 0};return h<1&&Zn.set(b,g),b},t,ii);return r&&r.sample_rate===void 0&&pi(t,r.endpoint,r.retention_days),r}catch{return null}}async function Dw(e,t){if(!(!e||K().telemetry_disabled))try{if(!await ge(async()=>{let n=await Y(e.global_pm_root);if(K().telemetry_disabled||!n.telemetry.enabled||n.telemetry.installation_id!==e.installation_id)return Zn.delete(e),!1;let r=Zn.get(e),o=t.ok?e.sample_rate??1:1;if(r){if(Zn.delete(e),J.randomBytes(6).readUIntBE(0,6)/281474976710656>=o)return!1;r.payload.sample_rate=o,await tr(e.global_pm_root,r)}let i=$(),s=Math.max(0,Date.now()-e.started_at_ms),a=ai(jo({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),c=Rd({ok:t.ok,errorCode:a,errorCategory:t.error_category}),d=ci(t.exit_code,t.ok),l=t.command_resolution??Ze({ok:t.ok,errorCode:a,errorCategory:c}),u=t.resolution_stage??"execute",f={schema_version:nr,event_id:J.randomUUID(),event_type:"command_finish",occurred_at:i,installation_id:e.installation_id,session_id:or,command:e.command,payload:{...r?{sample_rate:o}:{},...fw({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:s,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:d,errorCode:a,errorCategory:c,commandResolution:l,resolutionStage:u})}};await tr(e.global_pm_root,f);let _=lw(e,{...t,exit_code:d,error_code:a,error_category:c},i,s,o);return _&&await hw(e.global_pm_root,_),!0},e.global_pm_root,ii))return;await pi(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function Nw(e){if(!K().telemetry_disabled)try{let t=me(process.cwd());if(!(await Y(t)).telemetry.enabled)return;let n=await ge(async()=>{let r=await li(t);if(!r)return null;let{installationId:o,captureLevel:i}=r,s=xd(e.pm_version),a=kd(e.global),c=F(o,e.pm_root),d=F(o,process.cwd()),l=$(),u=ai(jo({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),f=e.error_category??Yt(u),_=ci(e.exit_code,!1),y=e.command.trim().length>0?e.command:"<unknown>",g=De(y),h=e.command_resolution??Ze({ok:!1,errorCode:u,errorCategory:f}),w=e.resolution_stage??"unknown",b={schema_version:nr,event_id:J.randomUUID(),event_type:"command_error",occurred_at:l,installation_id:o,session_id:or,command:k(y,"redacted"),payload:pw({captureLevel:i,pmVersion:s,sourceContext:a,command:y,commandTaxonomy:g,commandResolution:h,resolutionStage:w,args:e.args,options:e.options,pmRootHash:c,cwdHash:d,installationId:o,errorCode:u,errorCategory:f,exitCode:_,errorMessage:e.error_message})};return await tr(t,b),r},t,ii);n&&await pi(t,n.endpoint,n.retentionDays)}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]="79bb744c-f468-5333-b39a-552bf8639096")}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]="e216fd39-09ee-5a04-b0b5-44f518db4f93")}catch{}})();function DR(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function NR(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}export{Yd as a,xr as b,Wi as c,Gd as d,Fw as e,qi as f,an as g,Ki as h,Xi as i,Xd as j,Jd as k,Qd as l,Zd as m,Or as n,al as o,Hw as p,cl as q,qw as r,Et as s,ll as t,St as u,Bw as v,ul as w,cn as x,Ww as y,ze as z,fl as A,pl as B,Qw as C,Nr as D,Zw as E,eb as F,vt as G,tb as H,ts as I,Tl as J,hb as K,Cl as L,xl as M,kl as N,Ol as O,Eb as P,Nl as Q,dn as R,Tt as S,Fl as T,Vl as U,Ab as V,Gl as W,Rb as X,Kl as Y,Xl as Z,kb as _,Lr as $,ms as aa,tu as ba,Pr as ca,nu as da,un as ea,ps as fa,lu as ga,hs as ha,Ve as ia,le as ja,_u as ka,cE as la,yu as ma,gs as na,gu as oa,wu as pa,Eu as qa,Su as ra,vu as sa,wE as ta,Cu as ua,IE as va,ku as wa,Du as xa,Nu as ya,Mu as za,Lu as Aa,jr as Ba,Fu as Ca,ME as Da,LE as Ea,PE as Fa,$E as Ga,FE as Ha,jE as Ia,UE as Ja,Vu as Ka,Hu as La,qu as Ma,Bu as Na,Wu as Oa,Yu as Pa,He as Qa,Ps as Ra,Sm as Sa,aS as Ta,It as Ua,Om as Va,Hs as Wa,Hr as Xa,qs as Ya,hS as Za,Nm as _a,Lm as $a,Pm as ab,$m as bb,Fm as cb,qr as db,NS as eb,HS as fb,qS as gb,BS as hb,WS as ib,YS as jb,GS as kb,KS as lb,XS as mb,Bm as nb,Wm as ob,Ym as pb,JS as qb,Zm as rb,QS as sb,ZS as tb,Qr as ub,eo as vb,$v as wb,av as xb,cv as yb,dv as zb,ca as Ab,pf as Bb,co as Cb,Sv as Db,lo as Eb,Mt as Fb,Ye as Gb,Lt as Hb,Zf as Ib,ba as Jb,ep as Kb,p0 as Lb,fo as Mb,Ea as Nb,ap as Ob,_0 as Pb,cp as Qb,dp as Rb,E0 as Sb,Rn as Tb,xa as Ub,ho as Vb,Sp as Wb,vp as Xb,T0 as Yb,Ra as Zb,Ge as _b,yo as $b,wo as ac,Mn as bc,P0 as cc,Ao as dc,Pn as ec,Pa as fc,$n as gc,xo as hc,Ro as ic,ko as jc,Oo as kc,Va as lc,Ha as mc,Fa as nc,w_ as oc,Fn as pc,Je as qc,zt as rc,S_ as sc,zn as tc,oT as uc,K as vc,ke as wc,x_ as xc,Za as yc,ec as zc,tc as Ac,O_ as Bc,uT as Cc,L_ as Dc,mT as Ec,fT as Fc,Vt as Gc,Ec as Hc,Eh as Ic,Ht as Jc,CT as Kc,AT as Lc,Sh as Mc,vh as Nc,xT as Oc,RT as Pc,Ze as Qc,Mh as Rc,Lh as Sc,Ph as Tc,$h as Uc,zh as Vc,Vh as Wc,qh as Xc,Ey as Yc,Pc as Zc,vy as _c,Ty as $c,Iy as ad,BT as bd,Ho as cd,Fc as dd,$c as ed,xy as fd,Ry as gd,jc as hd,Dy as id,Py as jd,Fy as kd,Uy as ld,zy as md,By as nd,Yy as od,Gy as pd,Qn as qd,rg as rd,og as sd,pg as td,nr as ud,pd as vd,ge as wd,iC as xd,Ow as yd,Dw as zd,Nw as Ad,DR as Bd,NR as Cd};
124
- //# sourceMappingURL=chunk-GZ52WAY2.js.map
123
+ `:"";for(let o=0;;o+=1)try{await T(Bt(e),r,{createParentDirectories:!se(process.env[ue])});return}catch(i){let s=wd[o];if(s===void 0||!Vd(i))throw i;await Hd(s)}}async function md(e,t,n,r){return ge(async()=>{let o=await C(Bt(e)),i=o===null?[]:fi(o),s=[];for(let c of i){if(n.has(c.id))continue;let d=r.get(c.id);s.push(d?{...c,attempts:d.attempts,next_attempt_after:d.next_attempt_after}:c)}let{entries:a}=pi(s,t);return await Ew(e,a),a.length},e)}async function Sw(e,t){let n=await C(Bt(e));if(n===null||n.trim().length===0){await er(e,{pending_otel_spans:0},null);return}let r=fi(n),{entries:o,prunedCount:i}=pi(r,t),s=o.filter(y=>mi(y.next_attempt_after)).slice(0,Ag);if(s.length===0){let y=i>0?await md(e,t,new Set,new Map):o.length;await er(e,{pending_otel_spans:y},null);return}let a=$(),c=new Set,d=new Map,l=0,u;await Promise.all(s.map(async y=>{try{let g=await Od(y.endpoint,{"content-type":"application/json"},JSON.stringify(y.payload));if(g<200||g>=300)throw new Error(`local_otel_export_http_${g}`);c.add(y.id),l+=1}catch(g){u=g instanceof Error?k(Vn(g.message),"redacted"):"local_otel_export_failed";let h=y.attempts+1;d.set(y.id,{attempts:h,next_attempt_after:Fd(h)})}}));let f=await md(e,t,c,d),_={pending_otel_spans:f,last_otel_attempt_at:a};l>0&&(_.last_otel_success_at=a),u!==void 0?(_.last_otel_failure_at=a,_.last_otel_failure_error=u):f===0&&(_.last_otel_failure_at=void 0,_.last_otel_failure_error=void 0),await er(e,_,null)}async function qd(e,t,n){try{await Cw(e,t,n)}catch{}try{await Sw(e,n)}catch{}}async function vw(e,t=Lg,n=U().endpoint){try{let r=tw(e),o=await Eg(r,{withFileTypes:!0}),i=Date.now(),s=new Set([zt("events.jsonl",n),zt("state.json",n)]),a=c=>{if(!s.has(c))return/^\.events(?:\.[a-f0-9]{16})?\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(c)?i-Math.max(0,t):/^(?:events\.[a-f0-9]{16}\.jsonl|state\.[a-f0-9]{16}\.json)$/.test(c)?i-Pg:void 0};await Promise.all(o.map(async c=>{let d=c.isFile()?a(c.name):void 0;if(d===void 0)return;let l=O.join(r,c.name);(await _d(l)).mtimeMs<d&&await oi(l,{force:!0})}))}catch{}}async function ge(e,t=me(process.cwd()),n=5e3){let r=cd.catch(()=>{}).then(()=>Mi(async()=>{let o=await Se(t,"telemetry-queue",60,"telemetry",!1,!1,n,{createParentDirectories:!se(process.env[ue])});try{return rn(t),await e()}finally{await o()}}));return cd=r.catch(()=>{}),r}async function sr(e,t=U().endpoint){let n=await C(qt(e,t));return n===null||n.trim().length===0?[]:$d(n)}async function Zo(e,t,n,r=U().endpoint){return ge(async()=>{let o=await sr(e,r),{entries:i}=ir(o,n),s=i.filter(a=>!t.has(a.event.event_id));return await zd(e,s,r),s},e)}async function Tw(e,t,n,r,o=U().endpoint){return ge(async()=>{let i=await sr(e,o),{entries:s}=ir(i,r),a=s.map(c=>{if(!t.has(c.event.event_id))return c;let d=c.attempts+1;return{...c,attempts:d,last_attempt_at:n,next_attempt_after:Fd(d)}});return await zd(e,a,o),a},e)}function Iw(e,t){return t===null?e:zn(e)}async function Cw(e,t,n){let r=U().endpoint;await vw(e,void 0,r);let o=(r??t).trim(),i=Iw(o,r),s=h=>er(e,h,r);if(o.length===0)return;let a=await C(qt(e,r));if(a===null||a.trim().length===0){await s({endpoint:i,queue_entries:0});return}let c=$d(a);if(c.length===0){await s({endpoint:i,queue_entries:0});return}let{entries:d,prunedCount:l}=ir(c,n);if(d.length===0){let h=await Zo(e,new Set,n,r);await s({endpoint:i,queue_entries:h.length});return}let u=d.filter(h=>jd(h)).slice(0,xg);if(u.length===0){let h=l>0?await Zo(e,new Set,n,r):d;await s({endpoint:i,queue_entries:h.length});return}let f=new Set(u.map(h=>h.event.event_id)),_=$(),y={"content-type":"application/json"},g=process.env.PM_TELEMETRY_INGEST_KEY?.trim();g&&(y["x-pm-telemetry-key"]=g);try{let h=await Od(o,y,JSON.stringify({schema_version:nr,events:u.map(w=>w.event)}));if(h<200||h>=300)throw new Error(`telemetry_flush_http_${h}`)}catch(h){let w=await Tw(e,f,_,n,r),b=h instanceof Error?k(Vn(h.message),"redacted"):"telemetry_flush_failed";await s({endpoint:i,queue_entries:w.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:b});return}try{let h=await Zo(e,f,n,r);await s({endpoint:i,queue_entries:h.length,last_attempted_flush_at:_,last_successful_flush_at:_,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(h){let w=h instanceof Error?k(Vn(h.message),"redacted"):"telemetry_flush_failed",b=await sr(e,r).catch(()=>d);await s({endpoint:i,queue_entries:b.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:w})}}async function Aw(e){let t=ai(e);se(process.env[ue])||await Jo(O.dirname(t),{recursive:!0});try{return await Jo(t),!0}catch(n){if(typeof n!="object"||n===null||!("code"in n)||n.code!=="EEXIST")throw n}try{let n=await _d(t);return Date.now()-n.mtimeMs<bd?!1:(await oi(t,{recursive:!0,force:!0}),await Jo(t),!0)}catch{return!1}}function xw(e,t){try{return Date.now()-pd(e).mtimeMs<t}catch{return!1}}function Bd(e){try{bg(e,{recursive:!0,force:!0})}catch{}}function Rw(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function kw(e){try{return Xo(e),!0}catch(t){if(Rw(t)==="EEXIST"||!P(t))return!1}try{return Xo(O.dirname(e),{recursive:!0}),Xo(e),!0}catch{return!1}}function Ow(e){if(xw(ai(e),bd))return!1;let t=vd(e);try{if(Date.now()-pd(t).mtimeMs<$g)return!1;Bd(t)}catch(n){if(!P(n))return!1}return kw(t)}function ri(e){Bd(vd(e))}async function Dw(e,t,n){let r=await Aw(e);if(ri(e),!r)return!1;try{await qd(e,t,n)}finally{try{await oi(ai(e),{recursive:!0,force:!0})}catch{}}return!0}async function fd(e,t){let n=new Set;try{let{entries:r}=ir(await sr(e),t);for(let o of r.filter(jd))n.add(`event:${o.event.event_id}`)}catch{}try{let r=await C(Bt(e));if(r!==null)for(let o of pi(fi(r),t).entries)mi(o.next_attempt_after)&&n.add(`span:${o.id}`)}catch{}return n}function _i(e,t,n){if(!Ir(e)){if(rw())return Qo=Qo.then(()=>qd(e,t,n)),Qo;try{if(!Ow(e))return;let r=wg(process.execPath,[nw()],{detached:!0,stdio:"ignore",cwd:ii.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[ue]:"1"}});r.on("error",()=>{ri(e)}),r.unref()}catch{ri(e)}}}async function cC(e=me(process.cwd())){if(!K().telemetry_disabled)try{await Tr(e,async()=>{let t=se(process.env[ue]),n=!0;for(;n;){if(!(await Y(e)).telemetry.enabled)return;let r=await ge(()=>ui(e),e);if(!r)return;let o=t?await fd(e,r.retentionDays):new Set;if(!await Dw(e,r.endpoint,r.retentionDays)||!t)return;let i=await fd(e,r.retentionDays);n=i.size>0&&(i.size!==o.size||[...i].some(s=>!o.has(s)))}},()=>se(process.env[ue]))}catch{}}async function Nw(e){if(K().telemetry_disabled||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=me(process.cwd());if(!(await Y(t)).telemetry.enabled)return null;let n=e.global.noExtensions===!0||Li(e.command),r=await ge(async()=>{let o=await ui(t);if(!o)return null;let{installationId:i,endpoint:s,retentionDays:a,captureLevel:c}=o,d=Dd(e.pm_version),l=Md(e.global),u=F(i,e.pm_root),f=F(i,process.cwd()),_=lw(),y=$(),g={schema_version:nr,event_id:J.randomUUID(),event_type:"command_start",occurred_at:y,installation_id:i,session_id:or,command:e.command,payload:pw({captureLevel:c,context:e,pmVersion:d,sourceContext:l,pmRootHash:u,cwdHash:f,installationId:i})},h=await rd(t,e.command,n);h===1&&await tr(t,g);let w=De(e.command),b={...h<1?{sample_rate:h}:{},started_at:y,started_at_ms:Date.now(),command:e.command,command_taxonomy:w,pm_version:d,source_context:l.source_context,source_context_source:l.source_context_source,installation_id:i,pm_root_hash:u,cwd_hash:f,endpoint:s,retention_days:a,global_pm_root:t,capture_level:c,otel_traces_endpoint:_??void 0,otel_trace_id:_?J.randomBytes(16).toString("hex"):void 0,otel_span_id:_?J.randomBytes(8).toString("hex"):void 0};return h<1&&Zn.set(b,g),b},t,si);return r&&r.sample_rate===void 0&&_i(t,r.endpoint,r.retention_days),r}catch{return null}}async function Mw(e,t){if(!(!e||K().telemetry_disabled))try{if(!await ge(async()=>{let n=await Y(e.global_pm_root);if(K().telemetry_disabled||!n.telemetry.enabled||n.telemetry.installation_id!==e.installation_id)return Zn.delete(e),!1;let r=Zn.get(e),o=t.ok?e.sample_rate??1:1;if(r){if(Zn.delete(e),J.randomBytes(6).readUIntBE(0,6)/281474976710656>=o)return!1;r.payload.sample_rate=o,await tr(e.global_pm_root,r)}let i=$(),s=Math.max(0,Date.now()-e.started_at_ms),a=ci(Uo({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),c=Nd({ok:t.ok,errorCode:a,errorCategory:t.error_category}),d=di(t.exit_code,t.ok),l=t.command_resolution??Ze({ok:t.ok,errorCode:a,errorCategory:c}),u=t.resolution_stage??"execute",f={schema_version:nr,event_id:J.randomUUID(),event_type:"command_finish",occurred_at:i,installation_id:e.installation_id,session_id:or,command:e.command,payload:{...r?{sample_rate:o}:{},..._w({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:s,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:d,errorCode:a,errorCategory:c,commandResolution:l,resolutionStage:u})}};await tr(e.global_pm_root,f);let _=mw(e,{...t,exit_code:d,error_code:a,error_category:c},i,s,o);return _&&await gw(e.global_pm_root,_),!0},e.global_pm_root,si))return;await _i(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function Lw(e){if(!K().telemetry_disabled)try{let t=me(process.cwd());if(!(await Y(t)).telemetry.enabled)return;let n=await ge(async()=>{let r=await ui(t);if(!r)return null;let{installationId:o,captureLevel:i}=r,s=Dd(e.pm_version),a=Md(e.global),c=F(o,e.pm_root),d=F(o,process.cwd()),l=$(),u=ci(Uo({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),f=e.error_category??Yt(u),_=di(e.exit_code,!1),y=e.command.trim().length>0?e.command:"<unknown>",g=De(y),h=e.command_resolution??Ze({ok:!1,errorCode:u,errorCategory:f}),w=e.resolution_stage??"unknown",b={schema_version:nr,event_id:J.randomUUID(),event_type:"command_error",occurred_at:l,installation_id:o,session_id:or,command:k(y,"redacted"),payload:hw({captureLevel:i,pmVersion:s,sourceContext:a,command:y,commandTaxonomy:g,commandResolution:h,resolutionStage:w,args:e.args,options:e.options,pmRootHash:c,cwdHash:d,installationId:o,errorCode:u,errorCategory:f,exitCode:_,errorMessage:e.error_message})};return await tr(t,b),r},t,si);n&&await _i(t,n.endpoint,n.retentionDays)}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]="79bb744c-f468-5333-b39a-552bf8639096")}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]="e216fd39-09ee-5a04-b0b5-44f518db4f93")}catch{}})();function LR(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function PR(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}export{Jd as a,xr as b,Yi as c,Qd as d,Uw as e,Bi as f,an as g,Ji as h,Qi as i,Zd as j,el as k,tl as l,nl as m,Bw as n,Dr as o,dl as p,Ww as q,ll as r,Yw as s,Et as t,ml as u,St as v,Gw as w,fl as x,cn as y,Kw as z,ze as A,_l as B,hl as C,tb as D,Mr as E,nb as F,rb as G,vt as H,ob as I,is as J,Cl as K,wb as L,xl as M,kl as N,Dl as O,Nl as P,Tb as Q,Ll as R,dn as S,Tt as T,Ul as U,ql as V,kb as W,Xl as X,Db as Y,Jl as Z,Ql as _,Nb as $,Pr as aa,hs as ba,ru as ca,$r as da,ou as ea,un as fa,gs as ga,mu as ha,bs as ia,Ve as ja,le as ka,yu as la,uE as ma,wu as na,Ss as oa,bu as pa,Eu as qa,vu as ra,Tu as sa,Iu as ta,SE as ua,xu as va,xE as wa,Du as xa,Mu as ya,Lu as za,Pu as Aa,$u as Ba,Ur as Ca,Uu as Da,$E as Ea,FE as Fa,jE as Ga,UE as Ha,zE as Ia,VE as Ja,HE as Ka,qu as La,Bu as Ma,Wu as Na,Yu as Oa,Gu as Pa,Ku as Qa,He as Ra,Us as Sa,Tm as Ta,lS as Ua,It as Va,Nm as Wa,Ys as Xa,qr as Ya,Gs as Za,wS as _a,Lm as $a,$m as ab,Fm as bb,jm as cb,Um as db,Br as eb,PS as fb,WS as gb,YS as hb,GS as ib,KS as jb,XS as kb,JS as lb,QS as mb,ZS as nb,Ym as ob,Gm as pb,Km as qb,ev as rb,tf as sb,tv as tb,nv as ub,Zr as vb,to as wb,Uv as xb,lv as yb,uv as zb,mv as Ab,ma as Bb,hf as Cb,lo as Db,Iv as Eb,uo as Fb,Mt as Gb,Ye as Hb,Lt as Ib,tp as Jb,Ta as Kb,np as Lb,y0 as Mb,po as Nb,Ia as Ob,dp as Pb,g0 as Qb,lp as Rb,up as Sb,T0 as Tb,Rn as Ub,Da as Vb,yo as Wb,Tp as Xb,Ip as Yb,A0 as Zb,Na as _b,Ge as $b,go as ac,bo as bc,Mn as cc,j0 as dc,xo as ec,Pn as fc,Ua as gc,$n as hc,Ro as ic,ko as jc,Oo as kc,Do as lc,Wa as mc,Ya as nc,Va as oc,E_ as pc,Fn as qc,Je as rc,zt as sc,T_ as tc,zn as uc,aT as vc,K as wc,ke as xc,k_ as yc,rc as zc,oc as Ac,ic as Bc,N_ as Cc,pT as Dc,$_ as Ec,_T as Fc,hT as Gc,Vt as Hc,Ic,vh as Jc,Ht as Kc,RT as Lc,kT as Mc,Th as Nc,Ih as Oc,OT as Pc,DT as Qc,Ze as Rc,Ph as Sc,$h as Tc,Fh as Uc,jh as Vc,Hh as Wc,qh as Xc,Wh as Yc,vy as Zc,Uc as _c,Iy as $c,Cy as ad,Ay as bd,GT as cd,qo as dd,Vc as ed,zc as fd,ky as gd,Oy as hd,Hc as id,My as jd,Fy as kd,Uy as ld,Vy as md,Hy as nd,Yy as od,Ky as pd,Xy as qd,Qn as rd,ig as sd,sg as td,hg as ud,nr as vd,gd as wd,ge as xd,cC as yd,Nw as zd,Mw as Ad,Lw as Bd,LR as Cd,PR as Dd};
124
+ //# sourceMappingURL=chunk-FOT5K5OM.js.map