@unbrained/pm-cli 2026.11.18 → 2026.11.19

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 (93) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli-bundle/bundle-manifest.json +1 -1
  3. package/dist/cli-bundle/chunks/chunk-2UTJ5QIE.js +71 -0
  4. package/dist/cli-bundle/chunks/{chunk-T3E3WNHO.js → chunk-4FNMPZ7Y.js} +2 -2
  5. package/dist/cli-bundle/chunks/{chunk-2VH6COJE.js → chunk-723PMYNX.js} +37 -37
  6. package/dist/cli-bundle/chunks/{chunk-S3RMFLEG.js → chunk-AGPFANRX.js} +3 -3
  7. package/dist/cli-bundle/chunks/{chunk-TS2CZE3O.js → chunk-AMHD7WIV.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-VETSGCF4.js → chunk-AOV5HG3Y.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-WKHS4QC6.js → chunk-CNMGGAZO.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-LGWP5D7V.js → chunk-CTOE26W4.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-7LCJA54R.js → chunk-GQCMICAL.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-JBPXNG6P.js → chunk-IQKCRLQP.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-SSZBVRIN.js → chunk-IUTN67EB.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-7ETRLLK3.js → chunk-M76BEWTT.js} +30 -30
  15. package/dist/cli-bundle/chunks/{chunk-TA5VN4ME.js → chunk-N2CPCFSN.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-MUGGRKK3.js → chunk-NMVPQTZI.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-YJI2Y5N6.js → chunk-O7IFAJ76.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-CGTVDSAR.js → chunk-OESI2ETD.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-FJQCORYR.js → chunk-P4A5RFLX.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-L2ZLH3LZ.js → chunk-PRVT7ITI.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-XDIJK6VW.js → chunk-Q32Q3LRH.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-AGU7632B.js → chunk-XPBPGDFW.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-QK7RAN7R.js → chunk-Z5LHCEXG.js} +2 -2
  24. package/dist/cli-bundle/chunks/{item-revision-BV5BUBCR.js → item-revision-YJKGOYBR.js} +2 -2
  25. package/dist/cli-bundle/chunks/item-transaction-K4YZ7GWR.js +2 -0
  26. package/dist/cli-bundle/chunks/{mutation-admission-5AWMXMCB.js → mutation-admission-JLMQJ2M5.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-list-query-RJT7YBRF.js → register-list-query-4AXLLXK7.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-mutation-6KTMJGYF.js → register-mutation-FJIXGGF4.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-operations-W24TA3HZ.js → register-operations-W4E2KEMA.js} +2 -2
  30. package/dist/cli-bundle/chunks/{register-setup-QK67WUX6.js → register-setup-RYRIBNSN.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-LZR3JKYT.js → chunk-2XULTI5B.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-3H3SVHAT.js → chunk-4S7I342K.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-6OZ7BKWJ.js → chunk-77CDWGBW.js} +55 -54
  34. package/dist/cli-bundle/focused-chunks/{chunk-IGMFXB5W.js → chunk-7A4VIRIU.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-EO4XM3XJ.js → chunk-D72EQN7Z.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-PNCCTZKI.js → chunk-GAOWBALE.js} +23 -23
  37. package/dist/cli-bundle/focused-chunks/{chunk-T3NMYMW4.js → chunk-N64BUB63.js} +24 -24
  38. package/dist/cli-bundle/focused-chunks/{chunk-DWCFZVT2.js → chunk-OF4UM5B6.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-ONHUG7IL.js → chunk-P4TG4VMJ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{item-revision-NS2V4WON.js → item-revision-32HFGFYG.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{item-transaction-NENC4HYI.js → item-transaction-C4VW3SHX.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{mutation-admission-DZIBDJAE.js → mutation-admission-PNK6ORZR.js} +2 -2
  43. package/dist/cli-bundle/main.js +2 -2
  44. package/dist/cli-bundle/sdk-authoring.js +1 -1
  45. package/dist/cli-bundle/sdk-core.js +1 -1
  46. package/dist/cli-bundle/sdk-governance.js +1 -1
  47. package/dist/cli-bundle/sdk-merge.js +53 -53
  48. package/dist/cli-bundle/sdk-query.js +1 -1
  49. package/dist/cli-bundle/sdk-runtime.js +1 -1
  50. package/dist/cli-bundle/sdk-testing.js +1 -1
  51. package/dist/cli-bundle/sdk.js +11 -11
  52. package/dist/core/shared/process-tree.js +3 -0
  53. package/dist/core/shared/secret-rules.d.ts +12 -1
  54. package/dist/core/shared/secret-rules.js +2 -2
  55. package/dist/sdk/extension/managed-state.d.ts +3 -1
  56. package/dist/sdk/extension/managed-state.js +1 -1
  57. package/dist/sdk/extension/managed-update-status.js +1 -1
  58. package/dist/sdk/extension/update-check.d.ts +42 -6
  59. package/dist/sdk/extension/update-check.js +1 -1
  60. package/dist/sdk/extension.d.ts +3 -1
  61. package/dist/sdk/extension.js +1 -1
  62. package/dist/sdk/index.d.ts +1 -1
  63. package/dist/sdk/index.js +1 -1
  64. package/dist/sdk/mutation-guard.d.ts +121 -1
  65. package/dist/sdk/mutation-guard.js +1 -1
  66. package/dist/sdk/public-surface.json +1 -1
  67. package/dist/sdk/test/execution.js +2 -2
  68. package/docs/CONFIGURATION.md +1 -0
  69. package/docs/MUTATION_INTEGRITY.md +72 -0
  70. package/docs/PACKAGE_EVIDENCE.md +66 -0
  71. package/marketplace.json +1 -1
  72. package/package.json +1 -1
  73. package/packages/pm-beads/package.json +1 -1
  74. package/packages/pm-calendar/package.json +1 -1
  75. package/packages/pm-command-kit/package.json +1 -1
  76. package/packages/pm-digital-twin/package.json +1 -1
  77. package/packages/pm-governance-audit/package.json +1 -1
  78. package/packages/pm-guide-shell/package.json +1 -1
  79. package/packages/pm-kanban/package.json +1 -1
  80. package/packages/pm-lifecycle-hooks/package.json +1 -1
  81. package/packages/pm-linked-test-adapters/package.json +1 -1
  82. package/packages/pm-search-advanced/package.json +1 -1
  83. package/packages/pm-templates/package.json +1 -1
  84. package/packages/pm-todos/package.json +1 -1
  85. package/packages/pm-vcs/package.json +1 -1
  86. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  87. package/plugins/pm-claude/package.json +1 -1
  88. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  89. package/plugins/pm-codex/package.json +1 -1
  90. package/plugins/pm-codex/plugin.json +1 -1
  91. package/runtime-dependencies.json +1 -1
  92. package/dist/cli-bundle/chunks/chunk-OD2I3SFQ.js +0 -70
  93. package/dist/cli-bundle/chunks/item-transaction-E2ST3A3X.js +0 -2
@@ -1,18 +1,18 @@
1
- import{B as as,H as cn,e as Or,f as Dr,j as is,m as an,n as Nr,o as Lr,p as ss,r as Et,u as He,v as B,w as bt}from"./chunk-CR5GC3VO.js";import{$d as vr,Ad as Sr,Ga as _r,Gb as Vi,Ha as hr,Hb as b,He as en,Ia as Fi,Ja as yr,Jb as lt,Jh as Ar,Ka as ct,Kb as Ue,Kh as Cr,Lb as S,Lh as es,Mb as Hi,Mc as wr,Mh as xr,Nc as Yi,Nh as ts,Pa as Jt,Sb as qi,Ta as gr,Tc as Er,Td as Xi,Ua as me,Uc as Gi,Va as Ee,Vd as Tr,Vi as rs,Wa as ze,Wb as Wi,Xa as dt,Xb as P,Xh as gt,Y as Li,Ya as ee,Yc as br,Yh as Rr,Z as Mi,Zc as Qt,aa as $i,ae as mt,b as it,ca as at,ce as pt,cj as pe,e as Ri,ed as Ki,ee as _t,fe as Ji,gc as Se,gj as os,i as ki,ih as Ir,jj as rn,kj as wt,lb as be,m as Oi,md as ce,me as ht,n as Di,nb as ji,nd as ft,nj as U,ob as zi,oc as Bi,od as Ve,oe as yt,qj as on,rj as ve,sh as tn,si as ns,sj as kr,tb as Ui,th as nn,u as Ni,uc as ut,ve as Zi,wb as Zt,we as Qi,xj as sn,zd as Te}from"./chunk-7UUPLMCU.js";import{A as m,B as Xt,C as p,D as Pi,E as j,G as $,H as A,K as v,L as pr,M as st,m as fr,u as Q,z as mr}from"./chunk-5OFMWP3Q.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 eu=new Set(["rename-type","rename-field","remap-status",...Ri]);function tu(e,t){if(t&&!eu.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 dn=new WeakSet,Mr=new WeakMap,ds=new WeakSet;function $r(e){return ds.add(e),e}function Pr(e){return ds.has(e)}function St(e){dn.add(e);for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let r=[...n];Reflect.set(e,t,r),dn.add(r)}return e}function ls(e,t){return dn.has(e)||t!==void 0&&Mr.get(e)?.has(t)===!0}function nu(e,t){let n=new Set(t);Mr.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),dn.add(i)}return e}function us(e,t){if(Pr(e)&&$r(t),ls(e))return St(t);let n=Mr.get(e);return n?nu(t,n):t}function l0(e){return ls(e)?"sdk":"cli"}function cs(e,t){return e==="cli"?`--${t}`:t.replace(/-([a-z])/gu,(n,r)=>r.toUpperCase())}function Tt(e){return`Pass unset: ["${e}"] to clear it`}function ln(e,t,n=""){return e==="cli"?`--${t} must not be empty${n}`:`${cs("sdk",t)} must not be empty. ${Tt(t)}, or omit ${cs("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="-",ms=/^[A-Za-z0-9_.-]+$/u,Fr=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 ps(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 _s(e){let t=e.trim();if(t==="")return[];let n=(au(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 hs(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let n of e)if(typeof n=="string")for(let r of _s(n))t.push(r);return Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r))}function ys(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function ru(e){return typeof e!="string"?[]:e.split(";").map(t=>t.trim()).filter(Boolean)}function ou(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 iu(e,t){let n=ys(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 hs(t))r.add(o);return Array.from(r).sort((o,i)=>o.localeCompare(i))}function su(e,t){let n=Array.from(new Set(ys(e))).sort((o,i)=>o.localeCompare(i));if(!t||t.length===0)return n;let r=new Set(hs(t));return r.size===0?n:n.filter(o=>!r.has(o))}function au(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 jr(e){return e.replace(/\r\n/g,`
3
- `)}function gs(e){let t=jr(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
1
+ import{B as as,H as cn,e as Dr,f as Nr,j as is,m as an,n as Lr,o as Mr,p as ss,r as Et,u as He,v as W,w as bt}from"./chunk-CR5GC3VO.js";import{$d as Ir,Ad as vr,Ga as yr,Gb as Vi,Ha as hr,Hb as b,He as en,Ia as Fi,Ja as gr,Jb as lt,Jh as Cr,Ka as ct,Kb as Ue,Kh as Rr,Lb as S,Lh as es,Mb as Hi,Mc as Er,Mh as xr,Nc as Yi,Nh as ts,Pa as Jt,Sb as qi,Ta as wr,Tc as br,Td as Xi,Ua as me,Uc as Gi,Va as Ee,Vd as Tr,Vi as rs,Wa as ze,Wb as Bi,Xa as dt,Xb as P,Xh as gt,Y as Li,Ya as ee,Yc as Sr,Yh as Or,Z as Mi,Zc as Qt,aa as $i,ae as mt,b as it,ca as at,ce as pt,cj as pe,e as xi,ed as Ki,ee as _t,fe as Ji,gc as Se,gj as os,i as Oi,ih as Ar,jj as rn,kj as wt,lb as be,m as ki,md as ce,me as yt,n as Di,nb as ji,nd as ft,nj as U,ob as zi,oc as Wi,od as Ve,oe as ht,qj as on,rj as Te,sh as tn,si as ns,sj as kr,tb as Ui,th as nn,u as Ni,uc as ut,ve as Zi,wb as Zt,we as Qi,xj as sn,zd as ve}from"./chunk-7UUPLMCU.js";import{A as m,B as Xt,C as p,D as Pi,E as j,G as $,H as A,K as T,L as _r,M as st,m as mr,u as Q,z as pr}from"./chunk-5OFMWP3Q.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 ou=new Set(["rename-type","rename-field","remap-status",...xi]);function iu(e,t){if(t&&!ou.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 dn=new WeakSet,$r=new WeakMap,ds=new WeakSet;function Pr(e){return ds.add(e),e}function Fr(e){return ds.has(e)}function St(e){dn.add(e);for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let r=[...n];Reflect.set(e,t,r),dn.add(r)}return e}function ls(e,t){return dn.has(e)||t!==void 0&&$r.get(e)?.has(t)===!0}function su(e,t){let n=new Set(t);$r.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),dn.add(i)}return e}function us(e,t){if(Fr(e)&&Pr(t),ls(e))return St(t);let n=$r.get(e);return n?su(t,n):t}function h0(e){return ls(e)?"sdk":"cli"}function cs(e,t){return e==="cli"?`--${t}`:t.replace(/-([a-z])/gu,(n,r)=>r.toUpperCase())}function vt(e){return`Pass unset: ["${e}"] to clear it`}function ln(e,t,n=""){return e==="cli"?`--${t} must not be empty${n}`:`${cs("sdk",t)} must not be empty. ${vt(t)}, or omit ${cs("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="-",ms=/^[A-Za-z0-9_.-]+$/u,jr=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 ps(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 _s(e){let t=e.trim();if(t==="")return[];let n=(uu(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 ys(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let n of e)if(typeof n=="string")for(let r of _s(n))t.push(r);return Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r))}function hs(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function au(e){return typeof e!="string"?[]:e.split(";").map(t=>t.trim()).filter(Boolean)}function cu(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 du(e,t){let n=hs(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 ys(t))r.add(o);return Array.from(r).sort((o,i)=>o.localeCompare(i))}function lu(e,t){let n=Array.from(new Set(hs(e))).sort((o,i)=>o.localeCompare(i));if(!t||t.length===0)return n;let r=new Set(ys(t));return r.size===0?n:n.filter(o=>!r.has(o))}function uu(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 zr(e){return e.replace(/\r\n/g,`
3
+ `)}function gs(e){let t=zr(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 ws(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 cu(e){return ws(e).map(t=>t.text)}function _0(e){return ws(e.trim()).map(({text:t,raw:n})=>{let r=Es(t),o=t.slice(0,Math.max(r,0)).trim();return ms.test(o)?{text:t,raw:n,key:o,value:zr(t.slice(r+1).trim())}:{text:t,raw:n}})}function zr(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 Es(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 du(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 fs(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=du(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 bs(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 lu(e,t){let n=gs(e).trim();if(n.length===0||!n.includes(`
6
- `)&&!n.startsWith("-")&&!n.startsWith("*")&&!n.startsWith("+"))return null;let r={},o,i=jr(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();bs(r,c,e,t),r[c]=zr(a[3].trim()),o=c;continue}if(o&&Fr.has(o.toLowerCase())){r[o]=`${r[o]}
8
- ${s}`;continue}return null}return r}function Ur(e,t){let n=gs(e).trim();if(!n)throw new p(`${t} cannot be empty`,m.USAGE);let r=lu(n,t);if(r)return r;let o={},i,s=cu(n);for(let a of s){let c=Es(a),d=a.slice(0,Math.max(c,0)).trim();if(d!==""&&i!==void 0&&Fr.has(i.toLowerCase())&&!ms.test(d)){o[i]=`${o[i]},${a}`;continue}if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new p(fs(e,t),m.USAGE);let u=zr(a.slice(c+1).trim());bs(o,l,e,t),o[l]=u,i=l;continue}if(i&&Fr.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new p(fs(e,t),m.USAGE)}return o}var uu=/^[A-Za-z]:[\\/]/,fu=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function mu(e){let t=e.trim();return uu.test(t)?!1:fu.test(t)}function h0(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 pu(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 _u(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(jr(r))}),process.stdin.on("error",o=>{n(o)})})}var Ie=Symbol("all-mutation-stdin-fields"),Y=new WeakMap;function y0(e){return Pr(e)?e:St(vt({...e}))}function vt(e){return Y.set(e,Ie),e}function hu(e,t){let n=Y.get(e);return n===Ie||Y.set(e,new Set([...n??[],...t])),e}function It(e,t){us(e,t);let n=Y.get(e);return n===void 0||Y.set(t,n===Ie?n:new Set(n)),t}function g0(e,t){let n=Y.get(e),r=Y.get(t);return n===void 0||r===Ie?t:n===Ie?(Y.set(t,n),t):(Y.set(t,new Set([...r??[],...n])),t)}function yu(e){return Y.get(e)!==Ie}function un(e,t){let n=Y.get(e);return n!==Ie&&!n?.has(t)}function gu(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 w0(e,t,n){let r=e,o=[...t,...n];gu(o.map(([a,c])=>({value:r[a],optionName:c,resolveToken:un(e,a)})));let i=qe(),s={...r};for(let[a,c]of t)s[a]=await i.resolveValue(r[a],c,un(e,a));for(let[a,c]of n)s[a]=await i.resolveList(r[a],c,un(e,a));return vt(It(e,s))}function qe(){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=_u(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 wu(e,t){let n=Number(e);if(!Number.isFinite(n))throw new p(`Invalid ${t} value "${e}"`,m.USAGE);return n}function Eu(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]="d1a6d08a-65cd-5403-a43d-57c0ea1815a1")}catch{}})();function I0(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 bu(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 Su(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=bu(e,n);if(o===void 0)return;n=o;continue}if("<>()`".includes(r))return;n+=1}return n===e.length?n:void 0}function Vr(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 Tu(e,t){let n=Vr(e,t),r=e[n];return r===void 0||!";&|".includes(r)?n:(n+=1,r!==";"&&e[n]===r&&(n+=1),Vr(e,n))}function vu(e){let t=e.trim(),n=Vr(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=Su(t,r+1);if(o===void 0)return!1;n=Tu(t,o)}return!0}function Hr(e){if(!(e===void 0||!vu(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 A0(e){if(Hr(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:[be(["test","<id>","--add-json",JSON.stringify({command:e.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}function C0(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 At=["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","phase"],Iu=new Set(At);function x0(e){return ps(e,At)}function Ss(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!Iu.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: ${At.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 Ts(e){if(!e?.trim())return!1;try{return Hr(e.trim()),!0}catch{return!1}}function Au(e){try{let{command:t,...n}=Ss(Ur(e,"--add"),"--add");return Ts(t)?["--add",e]:["command=<actual command>",...Object.entries(n).map(([r,o])=>`${r}=${JSON.stringify(o)}`)].join(",")}catch{return}}function Cu(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Mi.has(n)&&n!=="--all")continue;let r=n.split("=",1)[0];if(!Li.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 xu(e,t){let n=$i(t);if(n===void 0)return;let r=Ni(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("-"))&&Cu(t.slice(o+2)))return{idIndex:o,value:s}}function Ru(e,t){let n=/^[A-Za-z_][A-Za-z0-9_]*=/u.exec(t)?.[0];if(e==="test")return n?["command=","cmd="].includes(n)?Au(t):At.includes(n.slice(0,-1))?`command=<actual command>,${t}`:void 0:Ts(t)?["--add-json",JSON.stringify({command:t})]:"command=<actual command>";if(!(n&&n!=="path="))return["--add",n?t:`path=${JSON.stringify(t)}`]}function ku(e,t){if(e===void 0||!["files","docs","test"].includes(e))return;let n=xu(e,t);if(!n)return;let{idIndex:r,value:o}=n,i=t[r],s=Ru(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 Ou}from"node:fs/promises";import vs 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 H0(e){if(e!==void 0){if(typeof e!="string")throw new p("--rollback requires a non-empty checkpoint ID string",m.USAGE);return Is(e)}}function Is(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 Du(e,t){let n=t.replace(/[-:.TZ]/g,"").slice(0,14),r=Math.random().toString(36).slice(2,8);return`${e}-${n}-${r}`}function Nu(e,t){return vs.join(e,"checkpoints",t)}function As(e,t,n){return vs.join(Nu(e,t),`${n}.json`)}async function Lu(e,t,n,r){let o=As(e,t,n),i=`${JSON.stringify(r,null,2)}
10
- `;if(!await Vi(o,i)&&await A(o)!==i)throw new p(`Checkpoint ${n} already exists with different contents; use a new checkpoint ID.`,m.CONFLICT);return o}function Mu(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 $u(e,t,n,r){let o=Is(n),i=As(e,t,o);if(!await j(i))throw new p(`Checkpoint ${o} not found`,m.NOT_FOUND);let s=await Ou(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=Mu(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:P(),author:typeof c.author=="string"?c.author:"unknown"}}async function Pu(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 G0=[{code:"unknown_lifecycle_action"}];function Fu(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:Se(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 Cs(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function ju(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:Fu(r,o),l=Cs([...i,r,...s]),u=e.retry_command??(d?Cs([...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 Ae=new Set(fr),fn=Object.freeze({get size(){return Ae.size},has(e){return Ae.has(e)},entries(){return Ae.entries()},keys(){return Ae.keys()},values(){return Ae.values()},forEach(e,t){Ae.forEach(n=>e.call(t,n,n,fn))},[Symbol.iterator](){return Ae.values()}});function xs(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Rs(e){return typeof e!="string"?null:ns(e)}function zu(e){try{return structuredClone(e)}catch{return e}}function Uu(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 Vu(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 Hu(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):Vu(n,e,t)}function qr(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=xs(r.name),i=Rs(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 ks(e){if(fn.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: ${[...fn].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 Ct(e){return[...qr(e).keys()].sort((t,n)=>t.localeCompare(n))}function qu(e,t,n,r){if(!e||e.length===0)return{};let o=qr(t),i={};for(let s of e){let{key:a,value:c}=Uu(s),d=o.get(a);if(!d)throw Wu(a,o,n,r);ks(d.name),i[d.name]=Hu(d.name,d.type,c)}return i}function Wu(e,t,n,r){if(fn.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 Bu(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 Yu(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function Gu(e,t,n={}){if(t){qr(t);for(let r of t.item_fields)for(let o of r.fields){let i=xs(o.name);if(!i)continue;ks(i),!(i in e)&&!n.skipDefaultFields?.has(i)&&Object.prototype.hasOwnProperty.call(o,"default")&&(e[i]=zu(o.default));let s=e[i];if(s===void 0)continue;let a=Rs(o.type);if(a&&!Bu(s,a))throw new TypeError(`Item field "${i}" must be of type ${a}`);let c=Array.isArray(o.values)?o.values:void 0;if(!Yu(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 Os=new Set(["item_format"]),Ds=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"]),Ku=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"]),Xu=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),Ju={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function Zu(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(Os.has(t)||Ds.has(t)||Ku.has(t)||t==="context")return t}function Qu(e){let t=e.trim().toLowerCase();return Ju[t]??e}function eS(e,t){let n=Zu(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."}:Os.has(n)?{routable:!0,flag:"format",value:t}:Ds.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:Xu.has(n)?Qu(t):t}}function ef(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 _e(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function nS(e,t){let n=_e(t);return!e||!n?null:[...e.assurance_providers??[]].reverse().find(r=>_e(r.definition.id)===n)??null}function tf(e,t){let n=_e(t);return!e||!n?null:[...e.search_providers].reverse().find(r=>(_e(r.runtime_definition?.name)??_e(r.definition?.name))===n)??null}function nf(e,t){let n=_e(t);return!e||!n?null:[...e.vector_store_adapters].reverse().find(r=>(_e(r.runtime_definition?.name)??_e(r.definition?.name))===n)??null}function rS(e){return e.runtime_definition??e.definition}import{readFile as rf}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 of=e=>rf(e,"utf8"),sf=async e=>await qe().resolveValue("-",e);function Wr(e){return[...new Set(e.split(/[,\r\n]+/).map(t=>t.trim()).filter(t=>t.length>0))]}function af(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=Wr(t.join(`
11
- `));return n.length>0?n.join(","):""}function Ns(e){if(e===void 0)return;if(typeof e=="number")return Number.isFinite(e)?String(e):"";if(Array.isArray(e))return af(e);if(typeof e!="string")return"";let t=Wr(e);return t.length>0?t.join(","):""}async function cf(e,t="--ids",n={}){if(e===void 0)return;let r=e.trim(),o=e;try{if(r==="-")o=await(n.readStdin??sf)(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??of)(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=Ns(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 Ls(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Br(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?Ls(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?Ls(t):"root"}function mn(e,t){return t==="body"?e.body:t==="metadata"?e.metadata:t==="root"?e:e.metadata[t]}function df(e,t){let n=t?.windowStartIndex??0,r=t?.field;if(e.length===0||n>=e.length)return[];let o=Ji(),i=[];for(let s=0;s<e.length;s+=1){let a=e[s],c=o,d=ht(o,a.patch),l;d.ok?(l=d.document,o=l):l=c;let u=new Set;for(let _ of a.patch)u.add(Br(_.path)),_.from!==void 0&&u.add(Br(_.from));let f=[...u].sort((_,y)=>_.localeCompare(y));if(s>=n)if(r!==void 0){if(!u.has(r))continue;let _={field:r,before:mn(c,r),after:mn(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:mn(c,y),after:mn(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 lf from"node:fs/promises";import uf 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 ff(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function mf(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 pf(e,t){return await Pi(uf.dirname(e)),await(await lf.open(e,"a")).close(),U({path:e,scope:"project",op:`${t}:history:auto_create`})}async function pn(e){return Ms({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function Ms(e){let t=ff(e.itemIds),n=[],r=[];for(let o of t){let i=ee(e.pmRoot,o);if(!await j(i)){if(e.settings.history.missing_stream==="strict_error")throw mf(o,e.commandLabel);r.push(...await pf(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}import{readFile as _f}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 hf=e=>_f(e,"utf8");async function yf(e,t,n=hf){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 qe().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 gf from"node:crypto";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]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function Ps(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 We(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function le(e,t){let n=Ps(t),r=We(e);return r.startsWith(n)?r:`${n}${r}`}function wf(e){let t=Wi(e);if(t!==void 0)return t;let n="";for(let r=0;r<e;r+=1)n+=gf.randomInt(0,36).toString(36);return n}async function Ef(e,t,n){let r=[...new Set(Object.values(n))].flatMap(o=>[_n.join(e,o,`${t}.md`),_n.join(e,o,`${t}.toon`)]);return r.push(_n.join(e,"history",`${t}.jsonl`)),(await Promise.all(r.map(o=>j(o)))).some(Boolean)}var $s=4,Fs=12;function bf(e){return typeof e!="number"||!Number.isFinite(e)?$s:Math.min(Fs,Math.max($s,Math.trunc(e)))}async function Sf(e,t,n={}){let r=bf(n.tokenLength),o=Math.min(r+6,Fs),i=0;for(;r<=o;){for(let s=0;s<32;s+=1){let a=`${Ps(t)}${wf(r)}`;if(!await(n.probeExisting===!1?j(_n.join(e,"history",`${a}.jsonl`)):Ef(e,a,n.typeToFolder??Q)))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 Tf=new Set(["none","null","undefined"]);function MS(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 vf(e,t="cli"){let n=t==="sdk";if(typeof e!="string")throw new p(n?`parent must be a string. ${Tt("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(ln(t,"parent",". Use --parent none to unset."),m.USAGE);if(js(r))throw new p(n?`parent must not be the placeholder "${r}". ${Tt("parent")}, or omit parent.`:`--parent must not use placeholder token "${r}". Use --unset parent to clear this field.`,m.USAGE);return r}function js(e){return Tf.has(e.trim().toLowerCase())}function If(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 Af(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"?`${Tt("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 Yr={critical:0,high:1,medium:2,low:3,minimal:4},zs=Object.keys(Yr),Cf=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${zs.join(", ")}), case-insensitive`;function hn(e){return new p(`Invalid priority "${e}". Accepted values: ${Cf}.`,m.USAGE,{code:"invalid_argument_value",field:"priority",value:e,allowed:["0","1","2","3","4",...zs]})}function xf(e){if(typeof e=="number"){if(Number.isInteger(e)&&e>=0&&e<=4)return e;throw hn(String(e))}if(typeof e!="string")throw hn(String(e));let t=e.trim();if(t.length===0)throw hn(e);let n=t.toLowerCase();if(Object.prototype.hasOwnProperty.call(Yr,n))return Yr[n];if(/^[0-4]$/.test(t))return Number(t);throw hn(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 Rf(e){let t={...e};for(let[n,r]of Object.entries(t))Array.isArray(r)&&Reflect.set(t,n,[...r]);return $r(It(e,t))}function kf(e){return St(vt(It(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 Of=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,Df=64;function BS(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 Nf(e,t,n,r="cli"){let o=t.trim();if(o.length===0)throw new p(ln(r,e,`. Use --${e} none to unset.`),m.USAGE);if(o.length<=Df&&Of.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 Us={open:"open_status",closed:"close_status",canceled:"canceled_status",cancelled:"canceled_status"},Vs="all";function ZS(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]===Vs}function Lf(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Us[n];return r?t[r]:br(e,t)}function Mf(e){let t=new Set(Object.keys(Us));for(let n of e.definitions){t.add(n.id);for(let r of n.aliases)t.add(r)}return[...t]}function $f(e,t){let n=e.trim().toLowerCase(),r,o=Number.POSITIVE_INFINITY;for(let i of Mf(t)){let s=Se(n,i.toLowerCase(),2);s!==null&&s<o&&(r=i,o=s)}return r}function Pf(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()===Vs).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=Lf(a,t);if(c===void 0){if(r){let d=$f(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 Ff={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 jf(e){if(e!==void 0)return Ff[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 qs(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 Gr(e){return e==null?"":Array.isArray(e)?e.map(t=>Gr(t)).join(";"):typeof e=="object"?JSON.stringify(e):String(e)}function Hs(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function zf(e){if(e.length===0)return"";let t=qs(e),n=[t.map(r=>Hs(r)).join(",")];for(let r of e)n.push(t.map(o=>Hs(Gr(r[o]))).join(","));return n.join(`
12
- `)}function Uf(e){if(e.length===0)return"";let t=qs(e),n=e.map(s=>t.map(a=>Gr(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 Vf(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 Hf=new Map(at.map(e=>[e.toLowerCase(),e])),qf=/^[A-Za-z][A-Za-z0-9_-]*$/;function Ws(e,t){if(!qf.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 Kr(e){return Hf.get(e.trim().toLowerCase())}function Gs(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Wf(e){return e.replace(/[\\"`$]/g,t=>`\\${t}`)}function Ks(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 aT(e){let t=(e.name??"").trim();if(t.length===0)throw new Error("Type name must not be empty.");Ws(t,"Type name");let n=Kr(t);if(n)throw new Error(`Cannot redefine built-in item type "${n}". Built-in types are reserved: ${at.join(", ")}.`);let r=e.description?.trim(),o=e.defaultStatus?.trim(),i=e.folder?.trim(),s=i&&i.length>0?yr(i):void 0,a=Ks(e.aliases??[]);for(let c of a){Ws(c,"Alias");let d=Kr(c);if(d)throw new Error(`Alias "${c}" collides with built-in item type "${d}". Built-in types are reserved: ${at.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 cT(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 Gs(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 Bs(e,t){return typeof t=="string"&&t.trim().length>0?yr(t).toLowerCase():Fi(e).toLowerCase()}function dT(e,t,n){let r=e.name.toLowerCase(),o=Bs(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||Bs(c,a.folder)===o&&i(c)}let s=n?.get(o);s!==void 0&&s.toLowerCase()!==r&&i(s)}function lT(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:Bf(t)}}function Bf(e){let t=Yf(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 Yf(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 uT(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=Ks([...Gs(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,Ys(a,"description",t.description),Ys(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 fT(e,t){let n=(t??"").trim();if(n.length===0)throw new Error("Type name must not be empty.");let r=Kr(n);if(r)throw new Error(`Cannot remove built-in item type "${r}". Built-in types are reserved: ${at.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 Ys(e,t,n){let r=e;n!==void 0&&(r[t]=n)}function mT(e){return`${JSON.stringify({definitions:e.definitions},null,2)}
14
- `}function Gf(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 "${Wf(n)}" (writes ${r}).`}function Kf(e,t,n){return`Invalid type value "${e}". Allowed: ${t.join(", ")}. ${Gf(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 Xs(e,t){return it(e,t)}function Xf(e,t,n){let r={};for(let o of t.command_to_fields.get(n)??[]){let i=wr(e,o);i!==void 0&&(r[o.metadata_key]=Yi(o,i))}return r}function Jf(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(!Xs(o,r[r.length-1]))return!1;continue}if(!Xs(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 Js(e){return typeof e=="string"?e.trim().toLowerCase():""}function yn(e,t){let n=ut(e);return n.length===0?"":t?.alias_to_id?.get(n)??n}function Zf(e){let t=Array.isArray(e?.type_workflows)?e.type_workflows:[],n=new Map;for(let r of t){let o=Js(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=ut(a[0]),d=ut(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 Qf(e){let t=Js(e.typeName),n=e.typeWorkflows.find(i=>i.type===t);if(!n)return{allowed:!0,hasRule:!1,allowedTransitions:[]};let r=yn(e.fromStatus,e.statusRegistry),o=yn(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=yn(i[0],e.statusRegistry),a=yn(i[1],e.statusRegistry);return s===r&&a===o}),hasRule:!0,allowedTransitions:n.allowed_transitions}}function em(e){return e.length===0?"(no transitions allowed)":e.map(t=>`${t[0]} -> ${t[1]}`).join(", ")}import{spawnSync as Qs}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 tm="PM_DISABLE_OLLAMA_AUTO_DEFAULTS",nm="PM_OLLAMA_MODEL",rm="http://localhost:11434",om="qwen3-embedding:0.6b",im=".agents/pm/search/lancedb/",sm=1500,am=2500,cm=/qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i,dm=/embed|embedding/i,te=b;function lm(){let e=te(process.env[tm]);if(!e)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}function Zs(e){return e.some(t=>te(t)!==null)}function um(e){let t=te(e);return!!(t&&t.toLowerCase()!=="ollama")}function fm(e){let t=te(e);return!!(t&&t.toLowerCase()!=="lancedb")}function mm(e){return um(e.search?.provider)||fm(e.vector_store?.adapter)||Zs([e.providers?.openai?.base_url,e.providers?.openai?.model,e.providers?.openai?.api_key])?!0:Zs([e.vector_store?.qdrant?.url,e.vector_store?.qdrant?.api_key])}function pm(){let e=Qs("ollama",["--version"],{encoding:"utf8",timeout:sm});return e.error?!1:e.status===0}function _m(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=>cm.test(r))||(n.find(r=>dm.test(r))??null)}function hm(e){let t=te(e.providers?.ollama?.model);if(t)return t;let n=te(process.env[nm]);if(n)return n;let r=Qs("ollama",["list"],{encoding:"utf8",timeout:am});if(!r.error&&r.status===0){let o=_m(typeof r.stdout=="string"?r.stdout:"");if(o)return o}return null}function ym(e){return{baseUrl:te(e.providers?.ollama?.base_url)===null,model:te(e.providers?.ollama?.model)===null,lancedbPath:te(e.vector_store?.lancedb?.path)===null,embeddingModel:te(e.search?.embedding_model)===null}}function gm(e){return e.baseUrl||e.model||e.lancedbPath||e.embeddingModel}function wm(e,t,n){if(!t.baseUrl&&!t.model)return;let r=e.providers??={},o=r.ollama??={};t.baseUrl&&(o.base_url=rm),t.model&&(o.model=n)}function Em(e,t){if(!t.lancedbPath)return;let n=e.vector_store??={},r=n.lancedb??={};r.path=im}function bm(e,t,n){if(!t.embeddingModel)return;let r=e.search??={};r.embedding_model=n}function Be(e){let t={settings:e,auto_ollama_defaults_applied:!1};if(lm()||mm(e))return t;let n=ym(e);if(!gm(n)||n.model&&!pm())return t;let r=structuredClone(e),o=hm(r);return o?(wm(r,n,o),Em(r,n),bm(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 ${om} or configure providers.ollama.model explicitly (and search.embedding_model if you need an override).`}}import{spawn as Sm}from"node:child_process";import{mkdirSync as ea,rmSync as na,statSync as Tm}from"node:fs";import gn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9ecff496-8afa-5cfc-9178-2be8bd403978")}catch{}})();var ra="reindex",vm="search/pending-refresh.json",Im="search/pending-refresh.gate.lock",Am=3e4,Cm="PM_SEARCH_REFRESH_INLINE",oa="PM_SEARCH_REFRESH_CHILD",xm=3e4;function ta(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Rm(){if(ta(process.env[Cm])||ta(process.env[oa]))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 ia(e){return gn.join(e,vm)}function sa(e){return gn.join(e,Im)}function km(e){let t=sa(e);try{if(Date.now()-Tm(t).mtimeMs<Am)return!1;na(t,{recursive:!0,force:!0})}catch{}try{return ea(gn.dirname(t),{recursive:!0}),ea(t),!0}catch{return!1}}function Om(e){try{na(sa(e),{recursive:!0,force:!0})}catch{}}async function aa(e,t,n){for(let r=0;r<50;r+=1){if(km(e))try{return await t()}finally{Om(e)}await Dm(20)}return n}function Dm(e){return new Promise(t=>{setTimeout(t,e)})}async function Jr(e){let t=await A(ia(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 ca(e,t){await v(ia(e),`${JSON.stringify({ids:t})}
15
- `)}async function Xr(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 Jr(e),i=[...new Set([...o,...n])].sort((s,a)=>s.localeCompare(a));await ca(e,i)};await aa(e,async()=>(await r(),!0),!1)||await r()}async function Nm(e){return aa(e,async()=>{let t=await Jr(e);return t.length>0&&await ca(e,[]),t},[])}function Lm(){return gn.join(gt(import.meta.url,["../../.."]),"dist","cli","search-refresh.js")}function Zr(e){try{let t=Sm(process.execPath,[Lm()],{detached:!0,stdio:"ignore",env:{...process.env,PM_PATH:e,[oa]:"1"}});t.on("error",()=>{}),t.unref()}catch{}}function Mm(e){setTimeout(()=>Zr(e),xm)}async function da(e,t){await Xr(e,t),Zr(e)}async function LT(e,t,n=Mm){let r=[],o=[];if(!await j(e))return{processed:o,rounds:0,warnings:r};let i;try{let l=await He(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=Be(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 Te(e,ra,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 Nm(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 Xr(e,l),c=!0,d=!0;break}o.push(...u.refreshed)}catch(u){r.push(`search_background_refresh_failed:${S(u)}`),await Xr(e,l),c=!0;break}}}finally{await s?.()}return d&&n(e),(c?[]:await Jr(e)).length>0&&Zr(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 xt(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 $m(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 Pm(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 Fm(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 la(e,t,n={}){let r=e.trim(),o=n.errorSubject??"history",i=o==="restore"?"Restore":"History",{guidance:s,lastTimestamp:a}=Pm(t,xt(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=xt(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=$m(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=ht(e,t);if(o.ok)return o.document;let i=Fm(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 ua(e,t){let n=e[0];if(n&&n.op!=="create"&&n.op!=="history_compact_baseline"){let s=ht(_t,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=yt([...r]),i=structuredClone(_t);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 HT(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 fa from"node:fs/promises";import Rt from"node:path";import{isUtf8 as jm}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]="9fa43d4b-3e4e-5d96-a256-0ce743f52372")}catch{}})();var zm=1048576,Um=4194304;async function ma(e,t){let n=Rt.dirname(e);for(;n!==Rt.parse(e).root;){let o=await fa.stat(n).catch(i=>{if($(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=Rt.dirname(n)}let r=await fa.open(e,"r").catch(o=>{if($(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||!jm(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 Vm(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 ki(t)}async function Hm(e){return Vm(await ma(Rt.join(e,"schema","policies.json"),zm))}async function qm(e,t){let n=await ma(ee(e,t),Um);if(n===null)return[];let r;try{if(r=n.split(/\r?\n/).filter(o=>o.trim()).map(o=>JSON.parse(o)),!yt(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 Wm(e,t,n){let r=n.before?.status!==n.after?.status&&t.policies.some(s=>s.rule.kind==="approval"&&Oi(s,n)),o=n.before?.id??n.after?.id,i=r&&typeof o=="string"?await qm(e,o):[];return Di(t,{...n,approvals:i})}function Bm(e,t){if(e.dryRun===!0)return!1;let n=es(e.pmRoot,[e.before?.metadata.id,e.after?.metadata.id],e.operation);return n===void 0?!1:(n.overrides.push(...t.map(r=>({source:"workflow_policy",policy_id:r.policy_id,rule:r.rule}))),!0)}async function eo(e){let t=await Hm(e.pmRoot),n=await Wm(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(o=>!o.satisfied&&o.effect==="refuse");return Bm(e,r)?n:Ym(e,t,n,r)}async function Ym(e,t,n,r){let o=[],i="";if(!e.dryRun)try{let f=await Or({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 _=_r("update",f);return _===void 0?`Supply ${f} using its declared SDK or package mutation contract, then retry.`:be(["update",l,hr("update",_),`<${f}>`,"--pm-path",Rt.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 Gm}from"node:async_hooks";import{channel as Km}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 to=new Gm,no=Km("@unbrained/pm-cli/item-metadata-enumeration/v1");function wn(e){no.publish(e)}async function av(e){let t={enumeration_calls:0,metadata_rows:0},n=r=>{to.getStore()?.includes(t)&&(t.enumeration_calls+=1,t.metadata_rows+=r)};no.subscribe(n);try{return{result:await to.run([...to.getStore()??[],t],e),work:{...t}}}finally{no.unsubscribe(n)}}import Ce from"node:fs/promises";import _a from"node:path";import{randomUUID as Xm}from"node:crypto";import{createRequire as Jm}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 Zm="metadata-query-index.sqlite",kt="5",ro;function Ot(){return ro!==void 0||(ro=Qi(process.versions.node,Jm(import.meta.url))),ro}function pa(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function Ye(e){return _a.join(e,"runtime",Zm)}function Qm(e){e.exec(`
5
+ `)}function ws(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 fu(e){return ws(e).map(t=>t.text)}function S0(e){return ws(e.trim()).map(({text:t,raw:n})=>{let r=Es(t),o=t.slice(0,Math.max(r,0)).trim();return ms.test(o)?{text:t,raw:n,key:o,value:Ur(t.slice(r+1).trim())}:{text:t,raw:n}})}function Ur(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 Es(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 mu(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 fs(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=mu(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 bs(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 pu(e,t){let n=gs(e).trim();if(n.length===0||!n.includes(`
6
+ `)&&!n.startsWith("-")&&!n.startsWith("*")&&!n.startsWith("+"))return null;let r={},o,i=zr(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();bs(r,c,e,t),r[c]=Ur(a[3].trim()),o=c;continue}if(o&&jr.has(o.toLowerCase())){r[o]=`${r[o]}
8
+ ${s}`;continue}return null}return r}function Vr(e,t){let n=gs(e).trim();if(!n)throw new p(`${t} cannot be empty`,m.USAGE);let r=pu(n,t);if(r)return r;let o={},i,s=fu(n);for(let a of s){let c=Es(a),d=a.slice(0,Math.max(c,0)).trim();if(d!==""&&i!==void 0&&jr.has(i.toLowerCase())&&!ms.test(d)){o[i]=`${o[i]},${a}`;continue}if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new p(fs(e,t),m.USAGE);let u=Ur(a.slice(c+1).trim());bs(o,l,e,t),o[l]=u,i=l;continue}if(i&&jr.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new p(fs(e,t),m.USAGE)}return o}var _u=/^[A-Za-z]:[\\/]/,yu=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function hu(e){let t=e.trim();return _u.test(t)?!1:yu.test(t)}function v0(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 gu(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 wu(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(zr(r))}),process.stdin.on("error",o=>{n(o)})})}var Ie=Symbol("all-mutation-stdin-fields"),Y=new WeakMap;function T0(e){return Fr(e)?e:St(Tt({...e}))}function Tt(e){return Y.set(e,Ie),e}function Eu(e,t){let n=Y.get(e);return n===Ie||Y.set(e,new Set([...n??[],...t])),e}function It(e,t){us(e,t);let n=Y.get(e);return n===void 0||Y.set(t,n===Ie?n:new Set(n)),t}function I0(e,t){let n=Y.get(e),r=Y.get(t);return n===void 0||r===Ie?t:n===Ie?(Y.set(t,n),t):(Y.set(t,new Set([...r??[],...n])),t)}function bu(e){return Y.get(e)!==Ie}function un(e,t){let n=Y.get(e);return n!==Ie&&!n?.has(t)}function Su(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 A0(e,t,n){let r=e,o=[...t,...n];Su(o.map(([a,c])=>({value:r[a],optionName:c,resolveToken:un(e,a)})));let i=qe(),s={...r};for(let[a,c]of t)s[a]=await i.resolveValue(r[a],c,un(e,a));for(let[a,c]of n)s[a]=await i.resolveList(r[a],c,un(e,a));return Tt(It(e,s))}function qe(){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=wu(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 vu(e,t){let n=Number(e);if(!Number.isFinite(n))throw new p(`Invalid ${t} value "${e}"`,m.USAGE);return n}function Tu(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]="d1a6d08a-65cd-5403-a43d-57c0ea1815a1")}catch{}})();function D0(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 Iu(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 Au(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=Iu(e,n);if(o===void 0)return;n=o;continue}if("<>()`".includes(r))return;n+=1}return n===e.length?n:void 0}function Hr(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 Cu(e,t){let n=Hr(e,t),r=e[n];return r===void 0||!";&|".includes(r)?n:(n+=1,r!==";"&&e[n]===r&&(n+=1),Hr(e,n))}function Ru(e){let t=e.trim(),n=Hr(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=Au(t,r+1);if(o===void 0)return!1;n=Cu(t,o)}return!0}function qr(e){if(!(e===void 0||!Ru(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 N0(e){if(qr(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:[be(["test","<id>","--add-json",JSON.stringify({command:e.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}function L0(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 At=["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","phase"],xu=new Set(At);function M0(e){return ps(e,At)}function Ss(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!xu.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: ${At.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 vs(e){if(!e?.trim())return!1;try{return qr(e.trim()),!0}catch{return!1}}function Ou(e){try{let{command:t,...n}=Ss(Vr(e,"--add"),"--add");return vs(t)?["--add",e]:["command=<actual command>",...Object.entries(n).map(([r,o])=>`${r}=${JSON.stringify(o)}`)].join(",")}catch{return}}function ku(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Mi.has(n)&&n!=="--all")continue;let r=n.split("=",1)[0];if(!Li.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 Du(e,t){let n=$i(t);if(n===void 0)return;let r=Ni(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("-"))&&ku(t.slice(o+2)))return{idIndex:o,value:s}}function Nu(e,t){let n=/^[A-Za-z_][A-Za-z0-9_]*=/u.exec(t)?.[0];if(e==="test")return n?["command=","cmd="].includes(n)?Ou(t):At.includes(n.slice(0,-1))?`command=<actual command>,${t}`:void 0:vs(t)?["--add-json",JSON.stringify({command:t})]:"command=<actual command>";if(!(n&&n!=="path="))return["--add",n?t:`path=${JSON.stringify(t)}`]}function Lu(e,t){if(e===void 0||!["files","docs","test"].includes(e))return;let n=Du(e,t);if(!n)return;let{idIndex:r,value:o}=n,i=t[r],s=Nu(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 Mu}from"node:fs/promises";import Ts 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 X0(e){if(e!==void 0){if(typeof e!="string")throw new p("--rollback requires a non-empty checkpoint ID string",m.USAGE);return Is(e)}}function Is(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 $u(e,t){let n=t.replace(/[-:.TZ]/g,"").slice(0,14),r=Math.random().toString(36).slice(2,8);return`${e}-${n}-${r}`}function Pu(e,t){return Ts.join(e,"checkpoints",t)}function As(e,t,n){return Ts.join(Pu(e,t),`${n}.json`)}async function Fu(e,t,n,r){let o=As(e,t,n),i=`${JSON.stringify(r,null,2)}
10
+ `;if(!await Vi(o,i)&&await A(o)!==i)throw new p(`Checkpoint ${n} already exists with different contents; use a new checkpoint ID.`,m.CONFLICT);return o}function ju(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 zu(e,t,n,r){let o=Is(n),i=As(e,t,o);if(!await j(i))throw new p(`Checkpoint ${o} not found`,m.NOT_FOUND);let s=await Mu(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=ju(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:P(),author:typeof c.author=="string"?c.author:"unknown"}}async function Uu(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 tS=[{code:"unknown_lifecycle_action"}];function Vu(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:Se(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 Cs(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function Hu(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:Vu(r,o),l=Cs([...i,r,...s]),u=e.retry_command??(d?Cs([...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 Ae=new Set(mr),fn=Object.freeze({get size(){return Ae.size},has(e){return Ae.has(e)},entries(){return Ae.entries()},keys(){return Ae.keys()},values(){return Ae.values()},forEach(e,t){Ae.forEach(n=>e.call(t,n,n,fn))},[Symbol.iterator](){return Ae.values()}});function Rs(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function xs(e){return typeof e!="string"?null:ns(e)}function qu(e){try{return structuredClone(e)}catch{return e}}function Bu(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 Wu(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 Yu(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):Wu(n,e,t)}function Br(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=Rs(r.name),i=xs(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 Os(e){if(fn.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: ${[...fn].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 Ct(e){return[...Br(e).keys()].sort((t,n)=>t.localeCompare(n))}function Gu(e,t,n,r){if(!e||e.length===0)return{};let o=Br(t),i={};for(let s of e){let{key:a,value:c}=Bu(s),d=o.get(a);if(!d)throw Ku(a,o,n,r);Os(d.name),i[d.name]=Yu(d.name,d.type,c)}return i}function Ku(e,t,n,r){if(fn.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 Xu(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 Ju(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function Zu(e,t,n={}){if(t){Br(t);for(let r of t.item_fields)for(let o of r.fields){let i=Rs(o.name);if(!i)continue;Os(i),!(i in e)&&!n.skipDefaultFields?.has(i)&&Object.prototype.hasOwnProperty.call(o,"default")&&(e[i]=qu(o.default));let s=e[i];if(s===void 0)continue;let a=xs(o.type);if(a&&!Xu(s,a))throw new TypeError(`Item field "${i}" must be of type ${a}`);let c=Array.isArray(o.values)?o.values:void 0;if(!Ju(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 ks=new Set(["item_format"]),Ds=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"]),Qu=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"]),ef=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),tf={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function nf(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(ks.has(t)||Ds.has(t)||Qu.has(t)||t==="context")return t}function rf(e){let t=e.trim().toLowerCase();return tf[t]??e}function aS(e,t){let n=nf(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."}:ks.has(n)?{routable:!0,flag:"format",value:t}:Ds.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:ef.has(n)?rf(t):t}}function of(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 _e(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function dS(e,t){let n=_e(t);return!e||!n?null:[...e.assurance_providers??[]].reverse().find(r=>_e(r.definition.id)===n)??null}function sf(e,t){let n=_e(t);return!e||!n?null:[...e.search_providers].reverse().find(r=>(_e(r.runtime_definition?.name)??_e(r.definition?.name))===n)??null}function af(e,t){let n=_e(t);return!e||!n?null:[...e.vector_store_adapters].reverse().find(r=>(_e(r.runtime_definition?.name)??_e(r.definition?.name))===n)??null}function lS(e){return e.runtime_definition??e.definition}import{readFile as cf}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 df=e=>cf(e,"utf8"),lf=async e=>await qe().resolveValue("-",e);function Wr(e){return[...new Set(e.split(/[,\r\n]+/).map(t=>t.trim()).filter(t=>t.length>0))]}function uf(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=Wr(t.join(`
11
+ `));return n.length>0?n.join(","):""}function Ns(e){if(e===void 0)return;if(typeof e=="number")return Number.isFinite(e)?String(e):"";if(Array.isArray(e))return uf(e);if(typeof e!="string")return"";let t=Wr(e);return t.length>0?t.join(","):""}async function ff(e,t="--ids",n={}){if(e===void 0)return;let r=e.trim(),o=e;try{if(r==="-")o=await(n.readStdin??lf)(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??df)(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=Ns(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 Ls(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Yr(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?Ls(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?Ls(t):"root"}function mn(e,t){return t==="body"?e.body:t==="metadata"?e.metadata:t==="root"?e:e.metadata[t]}function mf(e,t){let n=t?.windowStartIndex??0,r=t?.field;if(e.length===0||n>=e.length)return[];let o=Ji(),i=[];for(let s=0;s<e.length;s+=1){let a=e[s],c=o,d=yt(o,a.patch),l;d.ok?(l=d.document,o=l):l=c;let u=new Set;for(let _ of a.patch)u.add(Yr(_.path)),_.from!==void 0&&u.add(Yr(_.from));let f=[...u].sort((_,h)=>_.localeCompare(h));if(s>=n)if(r!==void 0){if(!u.has(r))continue;let _={field:r,before:mn(c,r),after:mn(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(h=>({field:h,before:mn(c,h),after:mn(l,h)}));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 pf from"node:fs/promises";import _f 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 yf(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function hf(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 gf(e,t){return await Pi(_f.dirname(e)),await(await pf.open(e,"a")).close(),U({path:e,scope:"project",op:`${t}:history:auto_create`})}async function pn(e){return Ms({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function Ms(e){let t=yf(e.itemIds),n=[],r=[];for(let o of t){let i=ee(e.pmRoot,o);if(!await j(i)){if(e.settings.history.missing_stream==="strict_error")throw hf(o,e.commandLabel);r.push(...await gf(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}import{readFile as wf}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 Ef=e=>wf(e,"utf8");async function bf(e,t,n=Ef){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 qe().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 Sf from"node:crypto";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]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function Ps(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 Be(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function le(e,t){let n=Ps(t),r=Be(e);return r.startsWith(n)?r:`${n}${r}`}function vf(e){let t=Bi(e);if(t!==void 0)return t;let n="";for(let r=0;r<e;r+=1)n+=Sf.randomInt(0,36).toString(36);return n}async function Tf(e,t,n){let r=[...new Set(Object.values(n))].flatMap(o=>[_n.join(e,o,`${t}.md`),_n.join(e,o,`${t}.toon`)]);return r.push(_n.join(e,"history",`${t}.jsonl`)),(await Promise.all(r.map(o=>j(o)))).some(Boolean)}var $s=4,Fs=12;function If(e){return typeof e!="number"||!Number.isFinite(e)?$s:Math.min(Fs,Math.max($s,Math.trunc(e)))}async function Af(e,t,n={}){let r=If(n.tokenLength),o=Math.min(r+6,Fs),i=0;for(;r<=o;){for(let s=0;s<32;s+=1){let a=`${Ps(t)}${vf(r)}`;if(!await(n.probeExisting===!1?j(_n.join(e,"history",`${a}.jsonl`)):Tf(e,a,n.typeToFolder??Q)))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 Cf=new Set(["none","null","undefined"]);function VS(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 Rf(e,t="cli"){let n=t==="sdk";if(typeof e!="string")throw new p(n?`parent must be a string. ${vt("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(ln(t,"parent",". Use --parent none to unset."),m.USAGE);if(js(r))throw new p(n?`parent must not be the placeholder "${r}". ${vt("parent")}, or omit parent.`:`--parent must not use placeholder token "${r}". Use --unset parent to clear this field.`,m.USAGE);return r}function js(e){return Cf.has(e.trim().toLowerCase())}function xf(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 Of(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"?`${vt("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 Gr={critical:0,high:1,medium:2,low:3,minimal:4},zs=Object.keys(Gr),kf=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${zs.join(", ")}), case-insensitive`;function yn(e){return new p(`Invalid priority "${e}". Accepted values: ${kf}.`,m.USAGE,{code:"invalid_argument_value",field:"priority",value:e,allowed:["0","1","2","3","4",...zs]})}function Df(e){if(typeof e=="number"){if(Number.isInteger(e)&&e>=0&&e<=4)return e;throw yn(String(e))}if(typeof e!="string")throw yn(String(e));let t=e.trim();if(t.length===0)throw yn(e);let n=t.toLowerCase();if(Object.prototype.hasOwnProperty.call(Gr,n))return Gr[n];if(/^[0-4]$/.test(t))return Number(t);throw yn(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 Nf(e){let t={...e};for(let[n,r]of Object.entries(t))Array.isArray(r)&&Reflect.set(t,n,[...r]);return Pr(It(e,t))}function Lf(e){return St(Tt(It(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 Mf=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,$f=64;function QS(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 Pf(e,t,n,r="cli"){let o=t.trim();if(o.length===0)throw new p(ln(r,e,`. Use --${e} none to unset.`),m.USAGE);if(o.length<=$f&&Mf.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 Us={open:"open_status",closed:"close_status",canceled:"canceled_status",cancelled:"canceled_status"},Vs="all";function iv(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]===Vs}function Ff(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Us[n];return r?t[r]:Sr(e,t)}function jf(e){let t=new Set(Object.keys(Us));for(let n of e.definitions){t.add(n.id);for(let r of n.aliases)t.add(r)}return[...t]}function zf(e,t){let n=e.trim().toLowerCase(),r,o=Number.POSITIVE_INFINITY;for(let i of jf(t)){let s=Se(n,i.toLowerCase(),2);s!==null&&s<o&&(r=i,o=s)}return r}function Uf(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()===Vs).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=Ff(a,t);if(c===void 0){if(r){let d=zf(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 Vf={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 Hf(e){if(e!==void 0)return Vf[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 qs(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 Kr(e){return e==null?"":Array.isArray(e)?e.map(t=>Kr(t)).join(";"):typeof e=="object"?JSON.stringify(e):String(e)}function Hs(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function qf(e){if(e.length===0)return"";let t=qs(e),n=[t.map(r=>Hs(r)).join(",")];for(let r of e)n.push(t.map(o=>Hs(Kr(r[o]))).join(","));return n.join(`
12
+ `)}function Bf(e){if(e.length===0)return"";let t=qs(e),n=e.map(s=>t.map(a=>Kr(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 Wf(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 Yf=new Map(at.map(e=>[e.toLowerCase(),e])),Gf=/^[A-Za-z][A-Za-z0-9_-]*$/;function Bs(e,t){if(!Gf.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 Xr(e){return Yf.get(e.trim().toLowerCase())}function Gs(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Kf(e){return e.replace(/[\\"`$]/g,t=>`\\${t}`)}function Ks(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 pv(e){let t=(e.name??"").trim();if(t.length===0)throw new Error("Type name must not be empty.");Bs(t,"Type name");let n=Xr(t);if(n)throw new Error(`Cannot redefine built-in item type "${n}". Built-in types are reserved: ${at.join(", ")}.`);let r=e.description?.trim(),o=e.defaultStatus?.trim(),i=e.folder?.trim(),s=i&&i.length>0?gr(i):void 0,a=Ks(e.aliases??[]);for(let c of a){Bs(c,"Alias");let d=Xr(c);if(d)throw new Error(`Alias "${c}" collides with built-in item type "${d}". Built-in types are reserved: ${at.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 _v(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 Gs(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 Ws(e,t){return typeof t=="string"&&t.trim().length>0?gr(t).toLowerCase():Fi(e).toLowerCase()}function yv(e,t,n){let r=e.name.toLowerCase(),o=Ws(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||Ws(c,a.folder)===o&&i(c)}let s=n?.get(o);s!==void 0&&s.toLowerCase()!==r&&i(s)}function hv(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:Xf(t)}}function Xf(e){let t=Jf(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 Jf(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 gv(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=Ks([...Gs(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,Ys(a,"description",t.description),Ys(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 wv(e,t){let n=(t??"").trim();if(n.length===0)throw new Error("Type name must not be empty.");let r=Xr(n);if(r)throw new Error(`Cannot remove built-in item type "${r}". Built-in types are reserved: ${at.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 Ys(e,t,n){let r=e;n!==void 0&&(r[t]=n)}function Ev(e){return`${JSON.stringify({definitions:e.definitions},null,2)}
14
+ `}function Zf(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 "${Kf(n)}" (writes ${r}).`}function Qf(e,t,n){return`Invalid type value "${e}". Allowed: ${t.join(", ")}. ${Zf(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 Xs(e,t){return it(e,t)}function em(e,t,n){let r={};for(let o of t.command_to_fields.get(n)??[]){let i=Er(e,o);i!==void 0&&(r[o.metadata_key]=Yi(o,i))}return r}function tm(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(!Xs(o,r[r.length-1]))return!1;continue}if(!Xs(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 Js(e){return typeof e=="string"?e.trim().toLowerCase():""}function hn(e,t){let n=ut(e);return n.length===0?"":t?.alias_to_id?.get(n)??n}function nm(e){let t=Array.isArray(e?.type_workflows)?e.type_workflows:[],n=new Map;for(let r of t){let o=Js(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=ut(a[0]),d=ut(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 rm(e){let t=Js(e.typeName),n=e.typeWorkflows.find(i=>i.type===t);if(!n)return{allowed:!0,hasRule:!1,allowedTransitions:[]};let r=hn(e.fromStatus,e.statusRegistry),o=hn(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=hn(i[0],e.statusRegistry),a=hn(i[1],e.statusRegistry);return s===r&&a===o}),hasRule:!0,allowedTransitions:n.allowed_transitions}}function om(e){return e.length===0?"(no transitions allowed)":e.map(t=>`${t[0]} -> ${t[1]}`).join(", ")}import{spawnSync as Qs}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 im="PM_DISABLE_OLLAMA_AUTO_DEFAULTS",sm="PM_OLLAMA_MODEL",am="http://localhost:11434",cm="qwen3-embedding:0.6b",dm=".agents/pm/search/lancedb/",lm=1500,um=2500,fm=/qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i,mm=/embed|embedding/i,te=b;function pm(){let e=te(process.env[im]);if(!e)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}function Zs(e){return e.some(t=>te(t)!==null)}function _m(e){let t=te(e);return!!(t&&t.toLowerCase()!=="ollama")}function ym(e){let t=te(e);return!!(t&&t.toLowerCase()!=="lancedb")}function hm(e){return _m(e.search?.provider)||ym(e.vector_store?.adapter)||Zs([e.providers?.openai?.base_url,e.providers?.openai?.model,e.providers?.openai?.api_key])?!0:Zs([e.vector_store?.qdrant?.url,e.vector_store?.qdrant?.api_key])}function gm(){let e=Qs("ollama",["--version"],{encoding:"utf8",timeout:lm});return e.error?!1:e.status===0}function wm(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=>fm.test(r))||(n.find(r=>mm.test(r))??null)}function Em(e){let t=te(e.providers?.ollama?.model);if(t)return t;let n=te(process.env[sm]);if(n)return n;let r=Qs("ollama",["list"],{encoding:"utf8",timeout:um});if(!r.error&&r.status===0){let o=wm(typeof r.stdout=="string"?r.stdout:"");if(o)return o}return null}function bm(e){return{baseUrl:te(e.providers?.ollama?.base_url)===null,model:te(e.providers?.ollama?.model)===null,lancedbPath:te(e.vector_store?.lancedb?.path)===null,embeddingModel:te(e.search?.embedding_model)===null}}function Sm(e){return e.baseUrl||e.model||e.lancedbPath||e.embeddingModel}function vm(e,t,n){if(!t.baseUrl&&!t.model)return;let r=e.providers??={},o=r.ollama??={};t.baseUrl&&(o.base_url=am),t.model&&(o.model=n)}function Tm(e,t){if(!t.lancedbPath)return;let n=e.vector_store??={},r=n.lancedb??={};r.path=dm}function Im(e,t,n){if(!t.embeddingModel)return;let r=e.search??={};r.embedding_model=n}function We(e){let t={settings:e,auto_ollama_defaults_applied:!1};if(pm()||hm(e))return t;let n=bm(e);if(!Sm(n)||n.model&&!gm())return t;let r=structuredClone(e),o=Em(r);return o?(vm(r,n,o),Tm(r,n),Im(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 ${cm} or configure providers.ollama.model explicitly (and search.embedding_model if you need an override).`}}import{spawn as Am}from"node:child_process";import{mkdirSync as ea,rmSync as na,statSync as Cm}from"node:fs";import gn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9ecff496-8afa-5cfc-9178-2be8bd403978")}catch{}})();var ra="reindex",Rm="search/pending-refresh.json",xm="search/pending-refresh.gate.lock",Om=3e4,km="PM_SEARCH_REFRESH_INLINE",oa="PM_SEARCH_REFRESH_CHILD",Dm=3e4;function ta(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Nm(){if(ta(process.env[km])||ta(process.env[oa]))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 ia(e){return gn.join(e,Rm)}function sa(e){return gn.join(e,xm)}function Lm(e){let t=sa(e);try{if(Date.now()-Cm(t).mtimeMs<Om)return!1;na(t,{recursive:!0,force:!0})}catch{}try{return ea(gn.dirname(t),{recursive:!0}),ea(t),!0}catch{return!1}}function Mm(e){try{na(sa(e),{recursive:!0,force:!0})}catch{}}async function aa(e,t,n){for(let r=0;r<50;r+=1){if(Lm(e))try{return await t()}finally{Mm(e)}await $m(20)}return n}function $m(e){return new Promise(t=>{setTimeout(t,e)})}async function Zr(e){let t=await A(ia(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 ca(e,t){await T(ia(e),`${JSON.stringify({ids:t})}
15
+ `)}async function Jr(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 ca(e,i)};await aa(e,async()=>(await r(),!0),!1)||await r()}async function Pm(e){return aa(e,async()=>{let t=await Zr(e);return t.length>0&&await ca(e,[]),t},[])}function Fm(){return gn.join(gt(import.meta.url,["../../.."]),"dist","cli","search-refresh.js")}function Qr(e){try{let t=Am(process.execPath,[Fm()],{detached:!0,stdio:"ignore",env:{...process.env,PM_PATH:e,[oa]:"1"}});t.on("error",()=>{}),t.unref()}catch{}}function jm(e){setTimeout(()=>Qr(e),Dm)}async function da(e,t){await Jr(e,t),Qr(e)}async function Uv(e,t,n=jm){let r=[],o=[];if(!await j(e))return{processed:o,rounds:0,warnings:r};let i;try{let l=await He(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=We(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 ve(e,ra,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 Pm(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 Jr(e,l),c=!0,d=!0;break}o.push(...u.refreshed)}catch(u){r.push(`search_background_refresh_failed:${S(u)}`),await Jr(e,l),c=!0;break}}}finally{await s?.()}return d&&n(e),(c?[]:await Zr(e)).length>0&&Qr(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 Rt(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 zm(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 Um(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 Vm(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 la(e,t,n={}){let r=e.trim(),o=n.errorSubject??"history",i=o==="restore"?"Restore":"History",{guidance:s,lastTimestamp:a}=Um(t,Rt(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=Rt(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=zm(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 eo(e,t,n,r){let o=yt(e,t);if(o.ok)return o.document;let i=Vm(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 ua(e,t){let n=e[0];if(n&&n.op!=="create"&&n.op!=="history_compact_baseline"){let s=yt(_t,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(_t);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=eo(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 Xv(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 fa from"node:fs/promises";import xt from"node:path";import{isUtf8 as Hm}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]="9fa43d4b-3e4e-5d96-a256-0ce743f52372")}catch{}})();var qm=1048576,Bm=4194304;async function ma(e,t){let n=xt.dirname(e);for(;n!==xt.parse(e).root;){let o=await fa.stat(n).catch(i=>{if($(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=xt.dirname(n)}let r=await fa.open(e,"r").catch(o=>{if($(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||!Hm(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 Wm(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 Oi(t)}async function Ym(e){return Wm(await ma(xt.join(e,"schema","policies.json"),qm))}async function Gm(e,t){let n=await ma(ee(e,t),Bm);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 Km(e,t,n){let r=n.before?.status!==n.after?.status&&t.policies.some(s=>s.rule.kind==="approval"&&ki(s,n)),o=n.before?.id??n.after?.id,i=r&&typeof o=="string"?await Gm(e,o):[];return Di(t,{...n,approvals:i})}function Xm(e,t){if(e.dryRun===!0)return!1;let n=es(e.pmRoot,[e.before?.metadata.id,e.after?.metadata.id],e.operation);return n===void 0?!1:(n.overrides.push(...t.map(r=>({source:"workflow_policy",policy_id:r.policy_id,rule:r.rule}))),!0)}async function to(e){let t=await Ym(e.pmRoot),n=await Km(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(o=>!o.satisfied&&o.effect==="refuse");return Xm(e,r)?n:Jm(e,t,n,r)}async function Jm(e,t,n,r){let o=[],i="";if(!e.dryRun)try{let f=await Dr({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 _=yr("update",f);return _===void 0?`Supply ${f} using its declared SDK or package mutation contract, then retry.`:be(["update",l,hr("update",_),`<${f}>`,"--pm-path",xt.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 Qm}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 no=new Zm,ro=Qm("@unbrained/pm-cli/item-metadata-enumeration/v1");function wn(e){ro.publish(e)}async function pT(e){let t={enumeration_calls:0,metadata_rows:0},n=r=>{no.getStore()?.includes(t)&&(t.enumeration_calls+=1,t.metadata_rows+=r)};ro.subscribe(n);try{return{result:await no.run([...no.getStore()??[],t],e),work:{...t}}}finally{ro.unsubscribe(n)}}import Ce from"node:fs/promises";import _a from"node:path";import{randomUUID as ep}from"node:crypto";import{createRequire as tp}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 np="metadata-query-index.sqlite",Ot="5",oo;function kt(){return oo!==void 0||(oo=Qi(process.versions.node,tp(import.meta.url))),oo}function pa(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function Ye(e){return _a.join(e,"runtime",np)}function rp(e){e.exec(`
16
16
  PRAGMA foreign_keys = ON;
17
17
  PRAGMA journal_mode = OFF;
18
18
  PRAGMA synchronous = OFF;
@@ -67,7 +67,7 @@ ${s}`;continue}return null}return r}function Ur(e,t){let n=gs(e).trim();if(!n)th
67
67
  tags,
68
68
  tokenize = 'unicode61'
69
69
  );
70
- `)}function bn(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function ha(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
70
+ `)}function bn(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function ya(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,8 +82,8 @@ ${s}`;continue}return null}return r}function Ur(e,t){let n=gs(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 ya(e){let t=Ye(e.pmRoot),n=Ot();if(!n){await Ce.rm(t,{force:!0});return}await Ce.mkdir(_a.dirname(t),{recursive:!0});let r=`${t}.${Xm()}.tmp`,o;try{o=new n(r),Qm(o),o.exec("BEGIN IMMEDIATE"),bn(o,"version",kt),bn(o,"context_fingerprint",e.contextFingerprint),bn(o,"source_cursor",e.sourceCursor);for(let i of e.rows)ha(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Ce.rm(t,{force:!0}),await Ce.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Ce.rm(r,{force:!0})]),i}}function Sn(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function ga(e){let t=Ot();if(!t)return!1;let n=Ye(e.pmRoot),r;try{await Ce.access(n),r=new t(n),r.exec("PRAGMA foreign_keys = ON");let o=Sn(r);if(o.version!==kt||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&&ha(r,e.row),bn(r,"source_cursor",e.sourceCursor),r.exec("COMMIT"),r.close(),!0}catch{try{r?.exec("ROLLBACK")}catch{}return r?.close(),!1}}function En(e,t,n,r,o){!r||r.length===0||(e.push(`${n} ${o} (${r.map(()=>"?").join(", ")})`),t.push(...r))}function ep(e){let t=[],n=[];En(t,n,"status",e.statuses,"IN"),En(t,n,"status",e.excludeStatuses,"NOT IN"),En(t,n,"type",e.types,"IN"),En(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 _v(e){let t=Ot();if(!t)return null;let n=e.query??{},{where:r,parameters:o}=ep(n),i;try{i=new t(Ye(e.pmRoot),{readOnly:!0});let s=Sn(i);if(s.version!==kt||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 hv(e){let t=Ot();if(!t||e.paths.length===0)return null;let n;try{n=new t(Ye(e.pmRoot),{readOnly:!0});let r=Sn(n);if(r.version!==kt||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 ha(e){let t=Ye(e.pmRoot),n=kt();if(!n){await Ce.rm(t,{force:!0});return}await Ce.mkdir(_a.dirname(t),{recursive:!0});let r=`${t}.${ep()}.tmp`,o;try{o=new n(r),rp(o),o.exec("BEGIN IMMEDIATE"),bn(o,"version",Ot),bn(o,"context_fingerprint",e.contextFingerprint),bn(o,"source_cursor",e.sourceCursor);for(let i of e.rows)ya(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Ce.rm(t,{force:!0}),await Ce.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Ce.rm(r,{force:!0})]),i}}function Sn(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function ga(e){let t=kt();if(!t)return!1;let n=Ye(e.pmRoot),r;try{await Ce.access(n),r=new t(n),r.exec("PRAGMA foreign_keys = ON");let o=Sn(r);if(o.version!==Ot||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&&ya(r,e.row),bn(r,"source_cursor",e.sourceCursor),r.exec("COMMIT"),r.close(),!0}catch{try{r?.exec("ROLLBACK")}catch{}return r?.close(),!1}}function En(e,t,n,r,o){!r||r.length===0||(e.push(`${n} ${o} (${r.map(()=>"?").join(", ")})`),t.push(...r))}function op(e){let t=[],n=[];En(t,n,"status",e.statuses,"IN"),En(t,n,"status",e.excludeStatuses,"NOT IN"),En(t,n,"type",e.types,"IN"),En(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 ST(e){let t=kt();if(!t)return null;let n=e.query??{},{where:r,parameters:o}=op(n),i;try{i=new t(Ye(e.pmRoot),{readOnly:!0});let s=Sn(i);if(s.version!==Ot||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 vT(e){let t=kt();if(!t||e.paths.length===0)return null;let n;try{n=new t(Ye(e.pmRoot),{readOnly:!0});let r=Sn(n);if(r.version!==Ot||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
88
  WHERE ${a}`).get(...s),d=pa(e.limit,50),l=pa(e.offset,0),u=n.prepare(`SELECT items.id, items.metadata_json
89
89
  FROM items
@@ -92,34 +92,34 @@ ${s}`;continue}return null}return r}function Ur(e,t){let n=gs(e).trim();if(!n)th
92
92
  WHERE item_linked_files.item_id = items.id AND ${a}
93
93
  )
94
94
  ORDER BY items.priority ASC, items.updated_at DESC, items.id ASC
95
- LIMIT ? OFFSET ?`).all(...s,d,l),f=[];if(u.length>0){let _=u.map(h=>String(h.id)),y=n.prepare(`SELECT item_id, path, scope, note
95
+ LIMIT ? OFFSET ?`).all(...s,d,l),f=[];if(u.length>0){let _=u.map(y=>String(y.id)),h=n.prepare(`SELECT item_id, path, scope, note
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),E=g.get(w);E.push({path:String(h.path),scope:String(h.scope),...h.note===null?{}:{note:String(h.note)}}),g.set(w,E)}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 yv(e){let t=Ot();if(!t)return null;let n;try{n=new t(Ye(e.pmRoot),{readOnly:!0});let r=Sn(n);if(r.version!==kt||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(y=>[y,[]]));for(let y of h){let w=String(y.item_id),E=g.get(w);E.push({path:String(y.path),scope:String(y.scope),...y.note===null?{}:{note:String(y.note)}}),g.set(w,E)}for(let y of u){let w=JSON.parse(String(y.metadata_json));f.push({item:w,files:g.get(String(y.id))})}}return n.close(),{source_cursor:r.source_cursor,total:Number(c.count),matches:f}}catch{return n?.close(),null}}async function TT(e){let t=kt();if(!t)return null;let n;try{n=new t(Ye(e.pmRoot),{readOnly:!0});let r=Sn(n);if(r.version!==Ot||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 Tn(e){await Ce.rm(Ye(e),{force:!0})}import N from"node:fs/promises";import T from"node:path";import{createHash as tp,randomUUID as Ta}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 ne=8,va=500,np="metadata-derived-index",rp="metadata-cache.json",op="metadata-cache-bodies.json",ip="metadata-cache-collections.json",sp="metadata-cache-delta.json",ap="metadata-cache-manifest.json",wa=4,cp=["comments","notes","learnings","files","tests","test_runs","docs"];function Ia(){return Ct(pe())}function In(e){let t={...e},n={};for(let r of cp)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function Aa(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function Ca(e,t,n,r){let o=tp("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 An(e){return T.join(e,"runtime",rp)}function Cn(e){return T.join(e,"runtime",op)}function xn(e){return T.join(e,"runtime",ip)}function io(e){return T.join(e,"runtime",sp)}function so(e){return T.join(e,"runtime",ap)}function Rn(e,t){let n=T.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var dp=24,q=new Map,kn=new WeakMap;function ao(e){return kn.get(e)??e.source_cursor}function lp(e,t){let n=ao(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){kn.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 up(e,t){if(!e)return;let n=ao(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){kn.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 fp(e,t){if(!e)return;let n=ao(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){kn.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 mp(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(lp(e,r),up(t,r),fp(n,r))}function oo(e,t){q.size>=dp&&!q.has(e)&&qi(q),q.set(e,t)}async function he(e,t){let n;try{n=await N.stat(e)}catch{return q.delete(e),null}let r=q.get(e);if(r&&Dt(r.signature,n.mtimeMs,n.ctimeMs,n.size))return q.delete(e),q.set(e,r),r.envelope;let o;try{o=t(await N.readFile(e,"utf8"))}catch{o=null}return oo(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function pp(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==ne||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=An(e),i=await he(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await he(Rn(o,t),r);return s===null&&Mt(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function _p(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==ne||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Cn(e),o=await he(r,n);return t&&o?.context_fingerprint!==t?await he(Rn(r,t),n):o}async function hp(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==ne||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=xn(e),o=await he(r,n);return t&&o?.context_fingerprint!==t?await he(Rn(r,t),n):o}async function co(e){let t=io(e),n=await he(t,r=>{let o=JSON.parse(r);return o.version!==ne||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 lo(e){let t=so(e),n=await he(t,r=>{let o=JSON.parse(r);return o.version!==ne||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 Ge(e)}catch{}return null}async function Nt(e,t){await N.mkdir(T.dirname(e),{recursive:!0}),await v(e,JSON.stringify(t));try{let r=await N.stat(e);oo(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{q.delete(e)}let n=T.dirname(T.dirname(e));if(e===An(n)||e===Cn(n)||e===xn(n)){let r=Rn(e,t.context_fingerprint);await v(r,JSON.stringify(t));try{let c=await N.stat(r);oo(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{q.delete(r)}let o=T.dirname(e),i=T.extname(e),s=T.basename(e,i),a=(await N.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==T.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>T.join(o,c.name));if(a.length>wa){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-wa)))await N.rm(d.path,{force:!0}),q.delete(d.path)}}}function yp(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function xa(e,t,n){return e===void 0||yp(e,t,n)}function Mt(e,t){e&&!e.includes(t)&&e.push(t)}function Dt(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function gp(e,t,n){let r=T.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&&!$(o)&&Mt(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function wp(e,t){try{let n=await N.stat(T.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 vn(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await wp(e,n))))}function Lt(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&&Dt(o,r.mtime_ms,r.ctime_ms,r.size)})}function Ep(e){return Jt.some(t=>e.toLowerCase().endsWith(t))}function bp(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function Sp(e,t,n){if(n)for(let r of await ve({path:e,scope:"project"}))Mt(t,r)}function Ea(e,t,n,r){if(e)return t&&n?n.collections:r}async function Tp(e,t,n){let r=await N.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=dt(e);await Sp(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],d=!n.forceSourceRead&&c!==void 0&&Dt(c,o,i,s),l=n.previousBodies[t],u=!n.forceSourceRead&&l!==void 0&&Dt(l,o,i,s),f=n.previousCollections[t],_=!n.forceSourceRead&&f!==void 0&&Dt(f,o,i,s);if(!(!d||n.includeBody&&!u||n.includeCollections&&!_))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:Ea(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=>Mt(n.warnings,w)}),h=In(g.metadata);return bp(n.state.misses,n.includeBody,n.includeCollections,d,u,_),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:d?c.metadata:h.light,heavyMetadata:Ea(n.includeCollections,_,f,h.heavy),bodyLength:d?c.body_length:g.body.length,body:n.includeBody?g.body:void 0}}function vp(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?Aa(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};xa(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function Ip(e,t,n,r){try{let o=await Tp(t,n,r);vp(t,n,r,o)}catch{Mt(r.warnings,`item_list_item_read_failed:${e}/${T.basename(t)}`)}}function Ap(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function Cp(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function xp(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function Rp(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function kp(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!Ep(s))continue;let a=T.join(o,s),c=T.relative(t.pmRoot,a);n.push(Ip(r,a,c,t)),n.length===32&&(await Promise.all(n),n.length=0)}await Promise.all(n)}async function Op(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Lt(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Nt(An(e.pmRoot),{version:ne,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Nt(so(e.pmRoot),{version:ne,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:T.relative(e.pmRoot,n.item_path),metadata:In(n.metadata).light,linkedFiles:n.metadata.files??[]}));t.length>=e.minimumIndexedItems?await ya({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:t}):await Tn(e.pmRoot)}catch{}}async function Dp(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 Nt(Cn(e.pmRoot),{version:ne,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function Np(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 Nt(xn(e.pmRoot),{version:ne,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function uo(e,t,n={}){let r=await lo(e);return n.required!==!0&&(r===null||r.entry_count<va)?async()=>{}:Te(e,np,30,t,!1,!1,3e3)}async function kv(e,t){let n=await lo(e);if(n===null)return null;let r=await co(e);if(r.invalid)return await Ge(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&&!Lt(i,await vn(e,t))?null:{source_cursor:o,entry_count:n.entry_count}}function ba(e,t){let n=T.relative(e,t);return n===""||n===".."||n.startsWith(`..${T.sep}`)||T.isAbsolute(n)?null:n}async function Ge(e){await Promise.all([An(e),Cn(e),xn(e),io(e),so(e)].map(async t=>{await N.rm(t,{force:!0}),q.delete(t)})),await Tn(e)}async function Lp(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await N.stat(e.mutation.itemPath),n=In(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 Mp(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function fo(e){let t=ba(e.pmRoot,e.itemPath),n=e.previousItemPath?ba(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await Ge(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=Ca(e.preferredFormat,e.typeToFolder,e.schema,Ia()),o=await lo(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await co(e.pmRoot);if(s.invalid)return await Ge(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=Mp(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 Lp({mutation:e});let d=Ta();return await Nt(io(e.pmRoot),{version:ne,context_fingerprint:r,base_source_cursor:i,source_cursor:d,directory_signatures:await vn(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await ga({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:d,row:e.document===null?null:{relativePath:t,metadata:In(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Tn(e.pmRoot),[]}catch{return await Ge(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function $p(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 Pp(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function Fp(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=dt(n);if(!o)continue;let i=e.includeCollections?Aa(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);xa(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:T.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function jp(e){return e.forceSourceScan||kr()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Lt(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)&&Pp(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function $t(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=Ia(),d=Ca(t,n,o,c),l=await co(e);l.invalid&&await Ge(e);let u=await pp(e,d,i.cacheDiagnostics),f=s?await _p(e,d):null,_=a?await hp(e,d):null;mp(u,f,_,l.envelope);let y=Ap(u,d),g=Cp(f,d),h=xp(_,d),w=[...new Set(Object.values(n))],E=await vn(e,w),I=Object.keys(y),C=Math.max(1,Math.floor(i.derivedIndexMinimumItems??va));if(jp({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:d,existingCache:u,existingBodyCache:f,existingCollectionsCache:_,directorySignatures:E,entryKeys:I,minimumIndexedItems:C,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:h}))return Fp({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:y,previousBodies:g,previousCollections:h});let M=await Promise.all(w.map(Kt=>gp(e,Kt,r))),x=kr(),D=Rp(),J={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 kp(M,J);let ae=await vn(e,w),Z=Lt(E,ae)?ae:{},H=D.misses.metadata||Object.keys(y).length!==Object.keys(D.newEntries).length||!Lt(u?.directory_signatures,Z)||u===null?Ta():u.source_cursor;return await Op({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCache:u,previousEntries:y,directorySignatures:Z,state:D,minimumIndexedItems:C}),s&&await Dp({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingBodyCache:f,previousBodies:g,state:D}),a&&await Np({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCollectionsCache:_,previousCollections:h,state:D}),$p(D)}async function Ra(e,t,n,r,o){return(await $t(e,t,n,r,o,{includeBody:!1})).map(i=>({metadata:i.metadata,body:i.body??""}))}async function ka(e,t,n,r,o){return(await $t(e,t,n,r,o,{includeBody:!1,includeCollections:!1})).map(i=>({metadata:i.metadata,body:i.body??""}))}import ye from"node:fs/promises";import{statSync as zp}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 Up(e,t){let n=-1,r=structuredClone(_t);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=xt(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;la(a,e).historyIndex===n&&(s=a)}return{version:i,target:s}}async function Oa(e,t,n){let r=new Set([le(t,n),We(t)]);for(let o of r){let i=ee(e,o);if(!zp(i,{throwIfNoEntry:!1})?.isFile())continue;let s=await pt(i,o),a=-1;if(s.forEach((_,y)=>{_.op==="delete"&&(a=y)}),a<0)continue;let c=ua(s,s.length-1);if(Object.keys(c.metadata).length!==0)continue;let{version:d,target:l}=Up(s,o),u=l===void 0?["history",o,"--verify"]:["get",o,"--at",l],f=be(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."]:[be(["restore",o,l])]],recovery:{suggested_retry:f,suggested_retry_args:u}})}}import{AsyncLocalStorage as Vp}from"node:async_hooks";import Da 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 Na=new Vp;function Wv(e,t){return Na.run({...e,pmRoot:Da.resolve(e.pmRoot)},t)}function La(e,t){let n=Na.getStore();return n?.pmRoot===Da.resolve(e)&&n.itemId===t?{bulk_checkpoint:n.checkpointId}:void 0}import mo from"node:path";import{isUtf8 as Hp}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]="2fda779c-a87f-517c-b71a-626c4fef98e5")}catch{}})();async function qp(e){try{return await ye.access(e),!0}catch{return!1}}function Wp(e,t){e&&(e.includes(t)||e.push(t))}function po(e){return e??Ct(pe())}function Bp(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Ke(e,t,n="pm-",r,o=Q){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=le(t,n),c=We(t),d=[...new Set([s,a,c])].filter(f=>f.length>0),l=Object.entries(o),u=Bp(r);for(let f of d){let _=new Map;for(let[y]of l)for(let g of u){let h=ze(e,y,f,g,o);await qp(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 Pt(e,t={}){let n=await Yp(e,t);if(n.error!==null)throw n.error;return{raw:n.raw,document:n.document}}async function Yp(e,t={}){let n=await ye.readFile(e.itemPath);if(!Hp(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 ve({path:e.itemPath,scope:"project"});let o;try{o=ce(r,{format:e.item_format,requireSupportedFormat:!0,schema:t.schema,extensionFieldNames:po(t.extensionFieldNames),onWarning:i=>Wp(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 $a(e,t,n=Q,r,o){await cn(e);let i=await Ra(e,t,n,r,o);return wn(i.length),i.map(s=>s.metadata)}async function Gp(e,t,n=Q,r,o){await cn(e);let i=await ka(e,t,n,r,o);return wn(i.length),i.map(s=>s.metadata)}async function vI(e,t,n=Q,r,o,i={}){await cn(e);let s=await $t(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan});return wn(s.length),s.map(a=>({...a.metadata,body:a.body}))}function _o(e){return{async get(t){let n=await Ke(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Pt(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>$a(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function Kp(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await ye.readdir(mo.join(e,o));for(let s of i)for(let a of Jt)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function Xp(e,t,n,r){let o=le(t,n),i=await Kp(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(a=>({id:a,distance:Se(a,o,s)})).filter(a=>a.distance!==null).sort((a,c)=>a.distance-c.distance).slice(0,3).map(a=>a.id)}async function Pa(e,t,n,r){let o=await Oa(e,t,n);if(o)return o;let i=await Xp(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 Jp(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 Fa(e){let t=e.typeToFolder??ct(e.settings,pe()).type_to_folder,n=await Ke(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await Pa(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await Sr(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 Pt(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:i}),c=a.metadata.assignee?.trim(),d=Ui(c),l=a.metadata.claim_principal?.trim()||c,u=vr(e.author),f=ss(e.settings);if(d&&l!==u&&!e.force&&!Jp(e.op,e.bypassAssigneeConflict)){if(f.ownership_enforcement==="strict")throw new p(`Item ${n.id} is assigned to ${d}. Use --force to override.`,m.CONFLICT);f.ownership_enforcement==="warn"&&i.push(`ownership_warning:assignee_conflict:${n.id}:${d}`)}return{typeToFolder:t,located:n,originalRaw:s,document:a,warnings:i,releaseLock:o,lease:r}}catch(i){throw await o(),i}}function ja(e){return Object.keys(e).length===0?void 0:e}async function za(e,t,n,r){return e.fence(async()=>{let o;try{o=await ye.readFile(t.itemPath,"utf8")}catch(i){if(!$(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 Zp(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 Ua(e){try{let t=await Ke(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return{document:mr};let n=ce(await ye.readFile(t.itemPath,"utf8"),{format:t.item_format,requireSupportedFormat:!0,schema:e.settings.schema,extensionFieldNames:po(e.extensionFieldNames)});return n.metadata.id===e.embeddedId?{document:n}:{document:e.fallback,revision:Ma}}catch{return{document:e.fallback,revision:Ma}}}var Ma="unreadable-after-storage-override";async function Qp(e){let t=await sn("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 e_(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await v(e.originalItemPath,e.originalRaw),await ye.rm(e.effectiveTargetItemPath,{force:!0});return}await v(e.originalItemPath,e.originalRaw)}}function t_(e,t){Ki(e.metadata)&&t.push("deferred_fields")}async function ho(e){Bi(e.op);let t=await Fa({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{Ar(e.pmRoot,i,r.id);let d=Ve(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=Ve(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(l,{storageId:r.id});if(t_(l,u.changedFields),e.skipNoop===!0&&u.changedFields.length===0)return{item:d.metadata,body:d.body,changedFields:[],warnings:[...s,...u.warnings??[]]};let f={...e.resolveHistoryContext?.(),...La(e.pmRoot,r.id),...ts(e.pmRoot,[r.id,i.metadata.id])},_=Math.max(Er(d.metadata),Er(l.metadata));as(gr(e.pmRoot),_),_>Gi(l.metadata)&&(l.metadata.pm_format_version=_,u.changedFields.push("pm_format_version")),l.metadata.updated_at=P();let y=Ve(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=await eo({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:d,after:y});await on({pm_root:e.pmRoot,operation:e.op,before:d,after:y,changed_fields:u.changedFields,author:e.author,sdk:_o({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let h=await pn({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),w="toon",E=ft(y,{format:w,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),I=ze(e.pmRoot,y.metadata.type,r.id,w,n),C=ee(e.pmRoot,r.id),M=await za(c,r,o,async()=>{let Z=await sn("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:C,item_format:w,before:d,after:y,contents:E}),{effectiveTargetItemPath:H,effectiveSerializedAfter:Kt,skipItemWrite:ot}=Zp(Z,I,E),Xl=await uo(e.pmRoot,e.author),xi=[];try{ot||await v(H,Kt),!ot&&H!==r.itemPath&&await ye.rm(r.itemPath);let Zl=tn({nowIso:y.metadata.updated_at,author:e.author,op:e.op,before:d,after:y,message:e.message,context:ja({...f,...g.decisions.length===0?{}:{workflow_policies:g.decisions},...xr(e.pmRoot,[r.id,i.metadata.id],e.op)})});try{await nn(C,Zl)}catch(Ql){throw await e_({skipItemWrite:ot,effectiveTargetItemPath:H,originalItemPath:r.itemPath,originalRaw:o}),Ql}ot||(xi=await fo({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:H,previousItemPath:r.itemPath,document:y}))}finally{await Xl()}let Jl=ot||H!==I||Kt!==E;return{derivedIndexWarnings:xi,effectiveTargetItemPath:H,overrideWarnings:Z.warnings,stored:Jl?await Ua({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:J}=M;Cr(e.pmRoot,J.document,r.id,[y.metadata.id],J.revision);let ae=[...await U({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 U({path:C,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 rn({id:y.metadata.id,op:e.op,item_type:y.metadata.type,previous_status:d.metadata.status,status:y.metadata.status,previous:wt(d.metadata,u.changedFields),current:wt(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,...M.overrideWarnings,...x,...ae]}}finally{await a()}}async function n_(e){let{historyContext:t,...n}=e;return ho({...n,resolveHistoryContext:()=>t})}async function II(e){return ho(e)}async function r_(e){return ho(e)}async function o_(e){let t=await Fa({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{Ar(e.pmRoot,o,n.id);let c=po(void 0),d=Ve(o,{schema:e.settings.schema,extensionFieldNames:c}),l=await eo({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:d,after:null,dryRun:e.dryRun});await on({pm_root:e.pmRoot,operation:"delete",before:d,after:null,changed_fields:["deleted"],author:e.author,dry_run:e.dryRun===!0,sdk:_o({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let u=await pn({pmRoot:e.pmRoot,settings:e.settings,itemId:n.id,commandLabel:"delete"}),f=P(),_=mr,y=tn({nowIso:f,author:e.author,op:"delete",before:d,after:_,message:e.message,context:ja({...l.decisions.length===0?{}:{workflow_policies:l.decisions},...xr(e.pmRoot,[n.id,o.metadata.id],"delete")})}),g=ee(e.pmRoot,n.id),h=()=>Qp({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 za(a,n,r,async()=>{let{effectiveItemPath:x,skipDelete:D,warnings:J}=await h(),ae=await uo(e.pmRoot,e.author),Z=[];try{D||await ye.rm(x);try{await nn(g,y)}catch(H){throw D||await v(x,r),H}D||(Z=await fo({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:J,stored:D||x!==n.itemPath?await Ua({pmRoot:e.pmRoot,settings:e.settings,id:n.id,typeToFolder:t.typeToFolder,fallback:_,embeddedId:o.metadata.id}):{document:_}}}),{derivedIndexWarnings:E,effectiveItemPath:I,stored:C}=w;Cr(e.pmRoot,C.document,n.id,[o.metadata.id],C.revision);let M=[...await U({path:I,scope:"project",op:"delete",item_id:d.metadata.id,item_type:d.metadata.type,before:d,after:_,changed_fields:["deleted"]}),...await U({path:g,scope:"project",op:"delete:history",item_id:d.metadata.id,item_type:d.metadata.type,before:d,after:_,changed_fields:["deleted"]})];return rn({id:d.metadata.id,op:"delete",item_type:d.metadata.type,previous_status:d.metadata.status,previous:wt(d.metadata,Object.keys(d.metadata)),changed_fields:["deleted"]}),{item:d.metadata,changedFields:["deleted"],warnings:[...i,...l.warnings,...u.warnings,...w.overrideWarnings,...E,...M]}}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 i_=3e4,Ft=class extends Error{status;constructor(t,n){super(t),this.name="SearchHttpError",this.status=n}};function xe(e,t,n=i_){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 Re(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 s_(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${S(t)})`}}async function On(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 s_(r),i=o.length>0?`: ${o}`:"";throw new Ft(`${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 OI(e,t){let n=b(e);if(!n)return"unconfigured";let r=b(t);return r&&r.toLowerCase()===n.toLowerCase()?"configured":"auto-detected"}function a_(e){let t=lt(e),n=t.toLowerCase();return n.endsWith("/embeddings")?t:n.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function Ha(e){let t=e.search?.embedding_model;return b(t)||null}function c_(e){let t=b(e.providers?.openai?.base_url),n=b(e.providers?.openai?.model);if(!t||!n)return null;let r=Ha(e),o=b(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:r??n,...o?{api_key:o}:{}}}function d_(e){let t=b(e.providers?.ollama?.base_url),n=b(e.providers?.ollama?.model);if(!t||!n)return null;let r=Ha(e);return{name:"ollama",base_url:t,model:r??n}}function qa(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 l_(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 u_(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 Dn(e){let t=c_(e),n=d_(e),r=[t,n].filter(s=>s!==null),o=b(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 Va(e){let t=lt(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:a_(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function f_(e,t){let n=qa(t);return e.name==="openai"?{target:Va(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:Va(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:n}}}function m_(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 u_(o).map((i,s)=>{let a=i.embedding;if(!Ue(a))throw new Error(`OpenAI embedding response entry at index ${s} is missing a numeric embedding vector`);return[...a]})}let n=t.embedding;if(Ue(n))return[[...n]];let r=t.embeddings;if(Array.isArray(r)&&r.length>0)return r.map((o,i)=>{if(!Ue(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 Wa(e,t,n={}){let r=xe(n.timeout_ms,"Embedding request"),o=Re(n.fetcher,"Embedding request"),i=qa(t),s=l_(i),a=f_(e,s.uniqueInputs),c=await On({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:r,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),d=m_(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 Nn=["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 go(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...Nn];let n=new Set(Nn),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:[...Nn]}var p_=8e3,__=3200,ke="...[semantic corpus truncated]",h_="search_embedding_corpus_max_characters_invalid:using_provider_default";function oe(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function y_(e){return(e.reminders??[]).map(t=>oe([t.at,t.text]))}function g_(e){return(e.events??[]).map(t=>oe([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 w_(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 E_(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 LI(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??[])w_(t,n);return E_(t,e),t.filter(n=>typeof n=="string"&&n.length>0).join(" ")}function b_(e){let t=(e.plan_steps??[]).map(i=>oe([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=>oe([s.kind,s.id,s.note])).join(" "),(i.files??[]).map(s=>oe([s.path,s.note])).join(" "),(i.tests??[]).map(s=>oe([s.command,s.path,s.note])).join(" "),(i.docs??[]).map(s=>oe([s.path,s.note])).join(" ")])),n=(e.plan_decisions??[]).map(i=>oe([i.decision,i.rationale,i.evidence,i.step_id])),r=(e.plan_discoveries??[]).map(i=>oe([i.text,i.step_id])),o=(e.plan_validation??[]).map(i=>oe([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 yo(e){return(e??[]).flatMap(t=>Object.prototype.toString.call(t)==="[object Object]"&&typeof t.text=="string"?[t.text]:[])}function re(e){return typeof e=="string"&&e.trim().length>0}var S_={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=>re(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>re(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>re(e.metadata.goal)?e.metadata.goal:void 0,value:e=>re(e.metadata.value)?e.metadata.value:void 0,why_now:e=>re(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>re(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=>re(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>re(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>re(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>re(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>yo(e.metadata.comments),notes:e=>yo(e.metadata.notes),learnings:e=>yo(e.metadata.learnings),reminders:e=>y_(e.metadata),events:e=>g_(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>b_(e.metadata)};function Ba(e,t={}){let n=t.fields??Nn,r={};for(let o of n){let i=S_[o];if(!i)continue;let s=i(e);s!==void 0&&(r[o]=s)}return r}function T_(e){return e?.trim().toLowerCase()==="ollama"?__:p_}function Xe(e,t){let n=T_(e),r=Hi(t);return r!==null?{maxCharacters:r,warning:null}:{maxCharacters:n,warning:t==null?null:h_}}function wo(e,t={}){let n=JSON.stringify(Ba(e,{fields:t.fields})),r=Xe(t.providerName,t.maxCharacters).maxCharacters;if(n.length<=r)return n;if(r<=ke.length)return ke.slice(0,r);let o=Math.max(0,r-ke.length);return`${n.slice(0,o)}${ke}`}(function(){try{var e=typeof window<"u"?window:typeof 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 v_(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 I_(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 A_(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let n=Math.max(0,t-ke.length);return`${e.slice(0,n)}${ke}`.slice(0,t)}function Ya(e){let t=S(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function C_(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 Ya(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 x_(e){return e instanceof Ft?e.status===413?"payload_too_large":null:Ya(e)?"timeout":null}async function Eo(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 Wa(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=x_(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 Eo(e,f,`${n}.1`,r,o,i,s),...await Eo(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(C_(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=Xe(e.name,t.search.embedding_corpus_max_characters);c.warning&&a.push(c.warning);let d=v_(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=A_(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=I_(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 Eo(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 R_,readFile as k_,stat as vo,unlink as O_}from"node:fs/promises";import{basename as Ga,dirname as So,isAbsolute as D_,join as N_,resolve as Io}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 Ao="pm_items",L_=/[^a-zA-Z0-9_-]/g,M_=128,$_=".pm-cli-local-vectors",To=1,Oe=new Map;function zt(e){return(b(e.collection_name)??Ao).replaceAll(L_,"_").slice(0,M_)}function Ln(e){if(!Ue(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function Xa(e){if(!Number.isFinite(e)||e<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(e)}function P_(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=b(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=b(e.result?.status);if(t)return{status:t};let n=b(e.status);if(n)return{status:n};throw new Error("Qdrant upsert response must include status metadata")}async function jt(e,t,n,r,o){return await On({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:n,fetcher:r,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function F_(e){let t=b(e.vector_store?.qdrant?.url);if(!t)return null;let n=b(e.vector_store?.collection_name),r=b(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...n&&n!==Ao?{collection_name:n}:{},...r?{api_key:r}:{}}}function j_(e){let t=Io(e),n=So(t);return Ga(t)==="pm"&&Ga(n)===".agents"?So(n):t}function z_(e,t){return!t||D_(e)?e:Io(j_(t),e)}function U_(e,t){let n=b(e.vector_store?.lancedb?.path);if(!n)return null;let r=b(e.vector_store?.collection_name);return{name:"lancedb",path:z_(n,t),...r&&r!==Ao?{collection_name:r}:{}}}function V_(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=b(t.id);if(!r)throw new Error(`Vector upsert record at index ${n} is missing a non-empty id`);let o=Ln(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 H_(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=b(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 q_(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function W_(e){return e.replace(/\/points\?wait=true$/,"")}function Mn(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function $n(e,t){return Je(e,t)}function Je(e,t){return N_(Io(e),$_,`${t}.json`)}function B_(e,t,n){let r=b(e.id);if(!r)throw new Error(`LanceDB local snapshot '${n}' record at index ${t} is missing a non-empty id`);let o=Ln(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 Y_(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!==To)throw new Error(`LanceDB local snapshot at '${e}' must include version=${To}`);let o=b(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=B_(i[a],a,e);s.set(c.id,c)}return s}async function G_(e){try{let t=await vo(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!$(t))throw t;return null}}function K_(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 Oe.set(e,{records:n,mtimeMs:null,size:null}),n}function X_(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function xo(e,t){let n=$n(e,t),r=Je(e,t),o=await G_(r),i=Oe.get(n);if(!o){let a=K_(n,i);if(a)return a}if(X_(i,o))return i.records;let s=new Map;try{let a=await k_(r,"utf8");s=Y_(r,t,a)}catch(a){if(!$(a))throw a}return Oe.set(n,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function J_(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 Ja(e){try{await O_(e)}catch(t){if(!$(t))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${S(t)}`)}}async function Za(e,t,n){let r=Je(e,t);if(n.size===0){await Ja(r);return}let o=So(r);try{await R_(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${S(s)}`)}let i=`${JSON.stringify({version:To,table:t,records:J_(n)})}
105
- `;try{await v(r,i)}catch(s){throw new Error(`LanceDB local snapshot write failed at '${r}': ${S(s)}`)}}async function Z_(e,t){let n=$n(e,t),r=Je(e,t);await Ja(r),Oe.delete(n)}function Ka(e){let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.sqrt(t)}function Q_(e,t){let n=0;for(let i=0;i<e.length;i+=1)n+=e[i]*t[i];let r=Ka(e),o=Ka(t);return r===0||o===0?0:n/(r*o)}function Pn(e,t){let n=F_(e),r=U_(e,t),o=[n,r].filter(a=>a!==null),i=b(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 Fn(e){let t=zt(e);if(e.name==="qdrant"){let o=lt(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 eh(e,t,n){let r=Fn(e),o=Ln(t),i=Xa(n);return e.name==="qdrant"?{target:r,method:"POST",headers:Mn(e),body:{vector:o,limit:i,with_payload:!0}}:{target:r,method:"LOCAL",headers:{},body:{table:zt(e),vector:o,limit:i}}}function th(e,t){let n=Fn(e),r=V_(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Mn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:zt(e),records:r}}}function nh(e,t){let n=Fn(e),r=H_(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Mn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:zt(e),ids:r}}}async function BI(e,t,n,r={}){let o=eh(e,t,n);if(o.method==="LOCAL"){let c=e,d=o.body,l=await xo(c.path,d.table);if(l.size===0)return[];let u=Ln(d.vector),f=Xa(d.limit),_=[],y=0;for(let g of l.values()){if(g.vector.length!==u.length){y++;continue}_.push({id:g.id,score:Q_(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=xe(r.timeout_ms,"Vector request"),s=Re(r.fetcher,"Vector request"),a=await jt(o.target.query_target,{method:"POST",headers:o.headers,body:o.body},i,s,"query");return P_(a)}async function Ro(e,t,n={}){let r=th(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=$n(a.path,c.table),l=await xo(a.path,c.table);for(let _ of c.records)l.set(_.id,_);await Za(a.path,c.table,l);let u=Je(a.path,c.table),f=await vo(u);return Oe.set(d,{records:l,mtimeMs:f.mtimeMs,size:f.size}),{status:"ok"}}let o=xe(n.timeout_ms,"Vector request"),i=Re(n.fetcher,"Vector request"),s=await jt(r.target.upsert_target,{method:"POST",headers:r.headers,body:r.body},o,i,"upsert");return Co(s)}async function jn(e,t,n={}){let r=nh(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=$n(a.path,c.table),l=await xo(a.path,c.table);if(l.size===0)return{status:"ok"};for(let u of c.ids)l.delete(u);if(await Za(a.path,c.table,l),l.size===0)Oe.delete(d);else{let u=Je(a.path,c.table),f=await vo(u);Oe.set(d,{records:l,mtimeMs:f.mtimeMs,size:f.size})}return{status:"ok"}}let o=xe(n.timeout_ms,"Vector request"),i=Re(n.fetcher,"Vector request"),s=await jt(q_(r.target.upsert_target),{method:"POST",headers:r.headers,body:r.body},o,i,"delete");return Co(s)}async function Qa(e,t=[],n={},r){if(e.name==="lancedb")return await Z_(e.path,zt(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=Fn(e),s=W_(i.upsert_target),a=xe(n.timeout_ms,"Vector request"),c=Re(n.fetcher,"Vector request"),d=Mn(e);try{await jt(s,{method:"DELETE",headers:d,body:{}},a,c,"delete")}catch(u){if(!S(u).includes("failed with status 404"))throw u}let l=await jt(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 jn(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 zn(e,t){let n=b(e),r=b(t);return!n||!r?null:{provider:n,model:r}}function ec(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=zn(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 ko(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 Oo(e,t){return!e||e.provider!==t.provider||e.model!==t.model}function Do(e,t){return!!(e&&e.vector_dimension!==t)}function No(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 Lo 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 rh=["index/manifest.json","search/embeddings.jsonl"],nc="search/vectorization-status.json";function oh(e,t){return`search_cache_invalidation_failed:${e}:${String(t)}`}function Ze(e){return[...new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function rc(e){return typeof e=="string"&&e.trim().length>0&&Number.isFinite(Date.parse(e))}function oc(e){let t=new Map;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!rc(r)||t.set(o,r)}return Object.fromEntries([...t.entries()].sort((n,r)=>n[0].localeCompare(r[0])))}async function ic(e){let t=Lo.join(e,nc),n=await A(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||!rc(c))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};o.set(a.trim(),c)}let i=null;try{i=ec(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 sc(e,t,n){let r=oc(t),o=Lo.join(e,nc),i=`${JSON.stringify({version:1,generated_at:P(),...n?{embedding:n}:{},items:Object.entries(r).map(([s,a])=>({id:s,updated_at:a}))},null,2)}
106
- `;await v(o,i)}function ih(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function sh(e){let t=zn(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function Ut(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function ah(e,t,n){if(!n.settings&&!await j(Ee(e)))return Ut(t,"search_semantic_refresh_skipped:settings_not_initialized");let r;try{if(n.settings)r=n.settings;else{let a=await He(e),c=a.warnings.find(d=>d.startsWith("settings_read_"));if(c)return Ut(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);r=a.settings}}catch(a){return Ut(t,`search_semantic_refresh_skipped:settings_read_failed:${S(a)}`)}let o=n.apply_runtime_defaults?Be(r).settings:r,i=Dn(o).active;if(!i)return Ut(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=Pn(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:Ut(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function ch(e,t,n,r,o,i){let s=[],a=new Set,c=new Set,d=[];for(let l of r){let u=await Ke(e,l,t,n,o);if(!u){c.add(l);continue}try{let f=await Pt(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:Ze(c),skippedIds:Ze(a),warnings:s}}async function dh(e,t,n){let r=Xe(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=go(e),i=n.map(a=>wo(a.document,{providerName:t.name,maxCharacters:r,fields:o})),s=await bo(t,e,i);return{vectors:s.vectors,vector_dimension:No(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function lh(e,t,n){return await Ro(e,t.map((r,o)=>({id:r.id,vector:n[o],payload:ih(r.document.metadata)}))),{refreshed:t.map(r=>r.id),skipped:[],warnings:[]}}async function uh(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await jn(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(n){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${S(n)}`]}}}async function fh(e){let t=[],n=[];for(let r of rh){let o=Lo.join(e,r);try{if(!await j(o))continue;await st(o),t.push(r)}catch(i){n.push(oh(r,i))}}return{invalidated:t,warnings:n}}async function tc(e,t,n={}){let r=Ze(t);if(r.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await ah(e,r,n);if(!("settings"in o))return o;let i=ct(o.settings,pe()),s=await ch(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 ic(e):{entries:{},embedding:null,warnings:[]},c=sh(o.provider),d=a.entries,l={refreshed:[],skipped:[],warnings:[]},u=a.embedding;if(s.documents.length>0)if(a.embedding&&Oo(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 dh(o.settings,o.provider,s.documents);if(Do(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=ko(c,h.vector_dimension);let w=await lh(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 uh(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,...oc(y)};for(let w of s.missingIds)delete h[w];try{await sc(e,h,u)}catch(w){g.push(`search_vectorization_status_ledger_write_failed:${S(w)}`)}g.push(...a.warnings)}return{refreshed:Ze([...l.refreshed,...f.refreshed]),skipped:Ze([...s.skippedIds,...l.skipped,...f.skipped]),warnings:[...s.warnings,...l.warnings,...f.warnings,...g]}}function mh(e,t){let n=t?Be(e).settings:e;return!!(Dn(n).active&&Pn(n).active)}async function ph(e,t,n={}){let r=await fh(e),o=Ze(t);if(o.length===0)return{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:r.warnings};if(!await j(Ee(e))){let c=await tc(e,o);return{invalidated:r.invalidated,refreshed:c.refreshed,skipped:c.skipped,warnings:[...r.warnings,...c.warnings]}}let i;try{let c=await He(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&&mh(i,s))return await da(e,o),{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:[...r.warnings,"search_semantic_refresh_scheduled_background"],scheduled:!0};let a=await tc(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 _h}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]="1bd63c38-5dff-5f7d-b733-3be3fcc6605e")}catch{}})();var hh=new Set(["1","true","yes","on"]),Un=["user","automation","test","dogfood"],ac=new Set(Un);function Qe(e={},t=process.env,n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let r=(t.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase(),o=Mo(t);if(ac.has(r)&&(!o||r==="test"))return{source_context:r,source_context_source:"env_override"};let i=r&&!ac.has(r)?"env_override_rejected":"inferred";return o?{source_context:"test",source_context_source:i}:{source_context:!n||Vt("CI",t)||e.json===!0||e.quiet===!0?"automation":"user",source_context_source:i}}function cc(e=process.env){return typeof e.VITEST=="string"?"VITEST":typeof e.VITEST_WORKER_ID=="string"?"VITEST_WORKER_ID":typeof e.NODE_TEST_CONTEXT=="string"?"NODE_TEST_CONTEXT":(e.NODE_ENV??"").trim().toLowerCase()==="test"?"NODE_ENV":void 0}function Mo(e=process.env){return cc(e)!==void 0}var Vn=new Set(["stats","ops stats","list","get","next","context","activity","aggregate"]);function dc(e,t,n=process.env){let r=n.PM_TELEMETRY_READ_SAMPLE_RATE?.trim();if(!r||!t||!Vn.has(e))return 1;let o=Number(r);return Number.isFinite(o)&&o>0&&o<=1?o:1}function Vt(e,t){return hh.has((t[e]??"").trim().toLowerCase())}function z(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 Ht(e,t=z().endpoint){if(t===null)return e;let n=_h("sha256").update(t).digest("hex").slice(0,16);return e.replace(/\.(jsonl|json)$/u,`.${n}.$1`)}function yh(e){return e.replaceAll(/(\/\/)[^/?#\s]*@/gu,"$1")}function Hn(e){let t=e.trim();if(!URL.canParse(t))return yh(t).replace(/[?#].*$/su,"");let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}function qn(e){return e.replaceAll(/\b[a-z][a-z\d+.-]*:\/\/[^\s"'<>]+/giu,t=>Hn(t))}function pA(e,t=process.env){return z(t).endpoint??e}function gh(e,t){return Vt("DO_NOT_TRACK",e)?"env:DO_NOT_TRACK":Vt("PM_TELEMETRY_DISABLED",e)?"env:PM_TELEMETRY_DISABLED":Vt("PM_NO_TELEMETRY",e)?"env:PM_NO_TELEMETRY":t?"env:PM_TELEMETRY_ENDPOINT":void 0}function G(e=process.env){let t=z(e),n=(e.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase(),r=cc(e),o=n==="test"?"env:PM_TELEMETRY_SOURCE_CONTEXT":Vt("PM_TELEMETRY_SEND_TEST_EVENTS",e)?"env:PM_TELEMETRY_SEND_TEST_EVENTS":void 0,i=r!==void 0&&o===void 0,s=gh(e,t.invalid),a=r===void 0?void 0:o??`env:${r}`;return{telemetry_disabled:s!==void 0||i,do_not_track:s==="env:DO_NOT_TRACK",test_suppressed:i,endpoint_override:t.endpoint===null?null:Hn(t.endpoint),endpoint_override_invalid:t.invalid,decided_by:s??a??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]="a483f454-e261-5232-bae0-da3cdb8c0518")}catch{}})();var De=Object.freeze({max_bytes:4096,max_depth:8}),lc=160,wh=new Set(["not_plain_object","unsupported_value","non_finite_number","malformed_unicode","reserved_key","depth_limit","byte_limit","diagnostic_budget"]),fc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,Eh=new Set(["__proto__"]),L=class extends Error{reason;path;constructor(t,n){super(t),this.reason=t,this.path=n}};function Po(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bh(e,t){return/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function mc(e){if(Buffer.byteLength(e,"utf8")<=lc)return e;let t="",n=Buffer.byteLength("\u2026","utf8");for(let r of e){if(n+=Buffer.byteLength(r,"utf8"),n>lc)break;t+=r}return`${t}\u2026`}function Wn(e,t,n){if(e.bytes+=t,!(e.bytes<=De.max_bytes))throw new L("byte_limit",n)}function pc(e,t,n){if(e.bytes+t>De.max_bytes)throw new L("byte_limit",n)}function $o(e,t,n){let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||!("value"in r))throw new L("unsupported_value",n);return r.value}function Sh(e,t,n){if(typeof e=="number"&&!Number.isFinite(e))throw new L("non_finite_number",t);if(typeof e=="string"&&(pc(n,e.length+2,t),fc.test(e)))throw new L("malformed_unicode",t);if(e!==null&&!["boolean","number","string"].includes(typeof e))throw new L("unsupported_value",t);return Wn(n,Buffer.byteLength(JSON.stringify(e),"utf8"),t),e}function _c(e,t,n,r){if(typeof e!="object"||e===null)return Sh(e,t,r);if(n>=De.max_depth)throw new L("depth_limit",t);if(Array.isArray(e)){let o=$o(e,"length",t);if(typeof o!="number"||!Number.isSafeInteger(o)||o<0)throw new L("unsupported_value",t);Wn(r,o>0?o+1:2,t);let i=[];for(let s=0;s<o;s+=1){let a=`${t}[${s}]`;i.push(_c($o(e,String(s),a),a,n+1,r))}return i}if(!Po(e))throw new L("unsupported_value",t);return hc(e,t,n+1,r)}function hc(e,t,n,r){let o=Object.keys(e);Wn(r,o.length>0?o.length+1:2,t);let i={};for(let s of o){pc(r,s.length+3,t);let a=bh(t,s);if(Eh.has(s))throw new L("reserved_key",a);if(fc.test(s))throw new L("malformed_unicode",a);Wn(r,Buffer.byteLength(JSON.stringify(s),"utf8")+1,a),i[s]=_c($o(e,s,a),a,n,r)}return i}function Th(e){try{if(e instanceof L)return e}catch{}return new L("unsupported_value","details")}function Yn(e){let t=De.max_bytes,n={bytes:0};try{if(!Po(e))throw new L("not_plain_object","details");return{ok:!0,details:hc(e,"details",0,n),byte_length:n.bytes}}catch(r){let o=Th(r);return{ok:!1,omission:o.reason==="byte_limit"?{reason:"byte_limit",byte_limit:t}:{reason:o.reason,path:mc(o.path),byte_limit:t}}}}function vh(e){return Yn(e).ok}function yc(e){if(e===void 0)return;let t=Yn(e);return t.ok?{details:t.details}:{details_omitted:t.omission}}function Bn(){return{reason:"unsupported_value",path:"details",byte_limit:De.max_bytes}}function uc(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n?n.value:void 0}function Ih(e){if(!Po(e))return;let t=uc(e,"reason");if(typeof t!="string"||!wh.has(t))return;let n=uc(e,"path"),r=typeof n=="string"?mc(n):void 0;return{reason:t,...r===void 0?{}:{path:r},byte_limit:De.max_bytes}}function gc(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=Bn()));return t}catch{return{}}}function wc(e){if(!(typeof e!="object"||e===null))try{let t=Object.getOwnPropertyDescriptor(e,"details");if(t!==void 0&&!("value"in t))return{details_omitted:Bn()};if(t!==void 0&&t.value!==void 0)return yc(t.value);let n=Object.getOwnPropertyDescriptor(e,"details_omitted"),r=n!==void 0&&"value"in n?Ih(n.value):void 0;return r===void 0?void 0:{details_omitted:r}}catch{return{details_omitted:Bn()}}}var Ec=new Set(["details","details_omitted"]);function Ah(e){let t={};for(let n of Object.keys(e)){if(Ec.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 Ch(e){if(typeof e!="object"||e===null)return e;try{return Array.isArray(e)?e:{...Ah(e),...wc(e)}}catch{return{details_omitted:Bn()}}}function et(e){let t={};for(let[n,r]of Object.entries(gc(e)))Ec.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 xh=12,Rh=new Set(["context","error_context"]),kh=new Set(["arguments"]);function bc(e){let t=new WeakSet,n=(r,o)=>{if(typeof r!="object"||r===null||o>xh||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=Rh.has(a)?{}:kh.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 Fo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function bA(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!Fo(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return Fo(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&Fo(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 Oh="PmCliError";function SA(e){if(!qt(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 Dh(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 Nh(e){if(e==null)return{};if(!Object.hasOwn(e,"details"))return e;let t=Object.getOwnPropertyDescriptor(e,"details");if(!("value"in t))throw Sc("unsupported_value","details");if(t.value===void 0)return e;let n=Yn(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 Sc(n.omission.reason,n.omission.path)}function Sc(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 TA(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,Dh(t.exitCode??m.USAGE),Nh(t.context));return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function qt(e){try{if(!(e instanceof Error)||e.name!==Oh)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 Vh}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 Gn=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,Lh=new RegExp(`(?:\\b|(?<=_))(${Gn.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");function Kn(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 vc(e,t){let n=/["']|u(?:0022|0027)/gi;n.lastIndex=t.end;for(let r of e.matchAll(n)){let o=Kn(e,r.index,r[0]);if(o?.identity===t.identity)return o.end}return e.length}function Mh(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 $h(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=Kn(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=Mh(n,i,i.end,e.length);if(a!==void 0)return a;continue}r.lastIndex=vc(e,i)}return e.length}function Ph(e,t,n){let r=/^(\\*)(["'{[]|u(?:0022|0027|007b|005b))/i.exec(e.slice(t)),o=r?Kn(e,t+r[1].length,r[2]):void 0;return o?.character==="{"||o?.character==="["?$h(e,o):o?vc(e,o):n}function Fh(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 Tc="(?:\\s|\\\\+u(?:0009|000a|000d|0020))*",jh=new RegExp("^"+Tc+"(?::|=|\\\\+u(?:003a|003d))"+Tc,"iu");function zh(e,t,n){let r=Fh(t);if(!Gn.test(r)&&!/\\u/iu.test(r))return;let o=e.slice(n),i=jh.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 Uh(e){let t=new Map,n=[];for(let r of e.matchAll(/["']|u(?:0022|0027)/gi)){let o=Kn(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=zh(e,e.slice(i,o.index),s);a&&n.push(a)}return n}function Ic(e){let t=Uh(e);for(let o of e.matchAll(Lh)){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=Ph(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 kc=new Set(["1","true","yes","on"]);function Oc(){return!!(kc.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||G().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}var Hh=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,qh=/file:\/\/\/?[^\s"'`),;]+/giu,Wh=/\b[A-Za-z]:\\[^\s"'`),;]+/g,Bh=/\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,Yh=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i;var Gh=["[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 Ac(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&&Yh.test(t)&&Ac(e))return"[scrubbed_path]";let n=Ic(Zt(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(Bh,"[scrubbed_ip]").replaceAll(qh,"[scrubbed_path]").replaceAll(Wh,"[scrubbed_path]").replaceAll(Hh,(r,o)=>`${o}[scrubbed_path]`);return Ac(n)?"[scrubbed_path]":n}function K(e){let t={};for(let[n,r]of Object.entries(e))Gn.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"?K(o):o):r&&typeof r=="object"?t[n]=K(r):t[n]=r;return t}function Kh(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=K(e.vars)),e.data&&typeof e.data=="object"&&(e.data=K(e.data))}var Xh=Vh(import.meta.url),Jh=()=>Xh("@sentry/node"),Xn,Cc=!1,Zh=Jh,Qh="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function jo(e){return/^\s*PmCliError:/.test(e)}function zo(e){let t=e.trim().toLowerCase();return t.length===0?!1:Gh.some(n=>t.includes(n))}function ey(e){return e.logger!=="console"?!1:typeof e.message=="string"&&zo(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(t=>typeof t.value=="string"&&zo(t.value))}function ty(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 ny(e,t){return t instanceof Error?qt(t):!!(e.exception?.values?.some(n=>n.type==="PmCliError")||e.exception?.values?.some(n=>typeof n.value=="string"&&jo(n.value))||e.logger==="console"&&typeof e.message=="string"&&jo(e.message))}function Dc(e){return e.category==="console"&&typeof e.message=="string"&&jo(e.message)}function Nc(e){return e.category==="console"&&typeof e.message=="string"&&zo(e.message)}function ry(){return Rr(import.meta.url,["../../.."])??"0.0.0"}function oy(){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=Qe().source_context;return t==="user"?"production":t}var xc=.2;function Lc(){let e=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!e)return xc;let t=Number(e);return!Number.isFinite(t)||t<0||t>1?xc:t}function iy(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)Kh(n)}}function Mc(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=K(t.data))}function $c(e){if(e.contexts)for(let[t,n]of Object.entries(e.contexts))n&&typeof n=="object"&&(e.contexts[t]=K(n))}function Rc(e,t){let n=e,r=n[t];r&&typeof r=="object"&&(n[t]=K(r))}function Uo(e){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(e==="automation"||e==="test"||e==="dogfood"||e==="user"))return e==="user"?"production":e}function Pc(e){let t=Uo(e.tags?.["pm.source_context"]);t&&(e.environment=t)}function Fc(e,t){let n=sy(e.extra);bc([e.contexts,e.extra,e.breadcrumbs]),ay(e.contexts,t),n!==void 0&&(e.extra.error_context=et(n))}function sy(e){if(!(typeof e!="object"||e===null||!Object.hasOwn(e,"error_context")))return e.error_context}function ay(e,t){if(typeof e!="object"||e===null||typeof t!="object"||t===null)return;let n=e,r=new Set(cy(t)),o=dy(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 cy(e){try{return[e.name,e.constructor?.name].filter(t=>typeof t=="string"&&t.length>0)}catch{return[]}}function dy(e){try{let t=et(e),n=Object.getOwnPropertyDescriptor(e,"context");return n!==void 0&&"value"in n&&(t.context=et(n.value)),t}catch{return}}var ly=(e,t)=>{if(ny(e,t?.originalException)||ey(e))return null;Fc(e,t?.originalException),Pc(e),ty(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")),iy(e),Mc(e),Rc(e,"extra"),$c(e);for(let n of["request","user","tags"])Rc(e,n);return e},uy=e=>(Fc(e),Pc(e),e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(t=>!Dc(t)&&!Nc(t)),Mc(e)),$c(e),e),fy=e=>K(e),my=e=>{if(e.message=W(e.message),e.attributes){let t=Uo(e.attributes["pm.source_context"]);t&&(e.attributes["sentry.environment"]=t),e.attributes=K(e.attributes)}return e};function py(e){let t=Uo(e["pm.source_context"]?.value);t&&(e["sentry.environment"]={type:"string",value:t})}function _y(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){py(r);for(let[o,i]of Object.entries(r)){let s=K({[o]:i.value})[o];typeof s=="string"&&(r[o]={type:"string",value:s})}}}}var hy=e=>Dc(e)||Nc(e)?null:(e.message&&(e.message=W(e.message,"message")),e.data&&typeof e.data=="object"&&(e.data=K(e.data)),e);async function jc(){if(Cc)return Xn;if(Cc=!0,Oc())return;let e=Zh(),t=process.env.SENTRY_DSN?.trim()||Qh,n=ry();e.init({dsn:t,release:`pm-cli@${n}`,environment:oy(),tracesSampleRate:Lc(),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:ly,beforeSendTransaction:uy,beforeSendSpan:e.withStreamedSpan(fy),beforeSendLog:my,beforeBreadcrumb:hy});let r=e.getClient();if(!r)return;let o=Qe();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",_y),Xn=e,e}async function yy(e){if(e!==!0||!kc.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||Lc()===0||Oc())return!1;try{return await jc()!==void 0}catch{return Xn=void 0,!1}}function Ne(){return Xn}(function(){try{var e=typeof window<"u"?window:typeof 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 Wt=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 $A(e,t){let n=t.warnings[0]??"extension_command_handler_failed",r=t.errorMessage?.trim();return new Wt(`Command "${e}" failed in extension handler (${n}).${r?` ${r}`:""}`,{code:t.errorCode??"command_failed",nextSteps:t.remediation?[t.remediation]:void 0},t.cause)}function PA(e){return e instanceof p||e instanceof Error?e.message:"Unknown failure"}function gy(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 wy(e){let t=Math.trunc(e);return t>m.SUCCESS?t:m.GENERIC_FAILURE}function FA(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function jA(e,t){if(e instanceof Error)return e;let n=new Error(t),r=gy(e);return r!==void 0&&(n.exitCode=wy(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 Ey=new Set(["init","config","completion","completion-statuses","completion-tags","completion-types"]),by=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"]),Sy=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"]),Ty=new Set(["test","test-all","test-runs","test-verify","trace-test","test-ping"]),vy=new Set(["health","validate","normalize","reindex","gc","telemetry","extension-doctor"]);function Iy(e){return e.trim().replaceAll(/\s+/g," ").toLowerCase()}function zc(e){let t=e?.trim().toLowerCase();return t&&t.length>0?t:void 0}var Ay=[{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")}],Cy=new Map([[m.USAGE,"invalid_command_usage"],[m.NOT_FOUND,"item_not_found"],[m.CONFLICT,"lock_conflict"],[m.DEPENDENCY_FAILED,"dependency_failed"]]);function Le(e){let t=Iy(e),n=t.length>0?t.split(" "):["<unknown>"],r=n[0],o=n[n.length-1],i="other";return Ey.has(r)?i="setup":by.has(r)?i="query":Sy.has(r)?i="mutation":Ty.has(r)?i="testing":r==="extension"?i="extension":vy.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 Vo(e){if(e.ok)return;let t=zc(e.errorCode);if(t)return t;let n=(e.errorMessage??"").trim().toLowerCase();for(let o of Ay)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?Cy.get(r)??"command_failed":"command_failed"}function tt(e){if(e.ok)return"success";let t=zc(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 Me;function ge(e,t,n){if(n===void 0)return;let r=e;typeof r.setAttribute=="function"&&r.setAttribute(t,n)}function nt(e,t,n){typeof n=="string"&&n.trim().length>0&&e.setTag(t,n)}function xy(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))),nt(e,"pm.error_code",n?.error_code),nt(e,"pm.error_category",n?.error_category),nt(e,"pm.command_resolution",n?.command_resolution),nt(e,"pm.resolution_stage",n?.resolution_stage)}function Ry(e,t,n,r){ge(e,"pm.ok",t),ge(e,"pm.command_ok",t),ge(e,"pm.exit_code",n),ge(e,"pm.command_exit_code",n),ge(e,"pm.error_code",r?.error_code),ge(e,"pm.error_category",r?.error_category),ge(e,"pm.command_resolution",r?.command_resolution),ge(e,"pm.resolution_stage",r?.resolution_stage)}function ky(e,t,n,r){let o=Ne();if(!o)return;let i=Le(e);o.setTag("pm.command",e),o.setTag("pm.command_root",i.command_root),o.setTag("pm.command_family",i.command_family),nt(o,"pm.version",r?.pm_version),nt(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 Oy(e){let t=Ne();if(!t)return;let n=Le(e);Me=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 Dy(){Me=void 0}function Ny(e,t,n){if(!Me)return;let r=e?"true":"false",o=typeof n?.exit_code=="number"?String(n.exit_code):void 0,i=Ne();i&&xy(i,r,n),Ry(Me,r,o,n),Me.setStatus(e?{code:1}:{code:2,message:t??"command_failed"}),Me.end(),Me=void 0}var Ly="unclassified_runtime_error";function My(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:Ly,exit_code:r}}function $y(e){let t=My(e);return{"pm.error_code":t.error_code,"pm.exit_code":String(t.exit_code)}}function Py(e){if(!jy(e))return;let t=Ne();if(!t)return;let n=$y(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=et(e.context)),t.captureException(e,{extra:r,tags:n})}else t.captureException(new Error(String(e)),{tags:n})}function Fy(e){let t=Ne();if(!t)return;let n=e.command_resolution??tt({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 jy(e){if(e instanceof Wt)return!0;if(e instanceof p||qt(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 zy(e=3e3){let t=Ne();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]="b93aa43d-6c3e-5a34-9139-88000581c39f")}catch{}})();var Pe=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,R="[/\\\\]+",Uy="[\\p{L}\\p{N}._@-]+",Fe=Uy+"(?:"+R+Pe+")*",Jn="(?:(?:home|users)"+R+Fe+"|root"+R+Fe+")",Vy="[/\\\\]"+Jn,Hy="[/\\\\]{2,}"+Jn,qy="/?[a-z]:"+R+"users"+R+Fe,Wy=Pe+"(?: +"+Pe+")*",Yo="(?:"+Wy+R+")?users"+R+Fe,By="[/\\\\]{2,}"+Pe+R+Yo,Yy="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+Pe+")",rd="[/\\\\]{2}[?.]"+R+"(?:unc"+R+Pe+R+Yo+"|"+Yy+R+"users"+R+Fe+")",Gy="file:(?:"+rd+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+R+")(?:"+Jn+"|[a-z]:"+R+"users"+R+Fe+")|[/\\\\]{2}(?:[a-z]:"+R+"users"+R+Fe+"|"+Pe+R+"(?:"+Jn+"|"+Yo+")))",Ky=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+Vy+"|"+qy+"|"+Gy+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+Hy+"|"+By+"|"+rd+")","giu"),Uc=4,Xy=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,Jy=new TextDecoder("utf-8");function Zy(e){return e.replace(/(?:%[a-f0-9]{2})+/giu,t=>Jy.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 Qy(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 eg(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 tg(e,t){for(let[n,r]of[["percent_decode",Zy],["json_unescape",Qy],["unicode_fold",eg]]){let o=r(e);o!==e&&!t.includes(n)&&t.push(n),e=o}return e}function*ng(e,t,n){let r=e,o=[];for(let i=0;i<Uc;i+=1){let s=r;if(r=tg(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===Uc-1&&Xy.test(r)&&(yield{index:0,normalizations:[...o],normalization_incomplete:!0})}}function*rg(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 ng(r,t,o))yield{...i,index:n};n+=r.length+1}}var Vc="password|passphrase",Zn=4,ie=4096,rt=e=>`${e}+(?!${e})`,Hc=String.raw`'[^'\r\n]*'|"[^"\\\r\n]*(?:\\.[^"\\\r\n]*){0,${ie}}"`,og=String.raw`\$\{(?:${rt(String.raw`[^{}$'"\\\r\n]`)}|\\[^\r\n]|${Hc}|\$(?!\{)|\$\{[^{}\r\n]*\}){0,${ie}}\}`+String.raw`|\$\((?:${rt(String.raw`[^()$'"\\\r\n]`)}|\\[^\r\n]|${Hc}|\$(?!\()|\$\([^()\r\n]*\)){0,${ie}}\)`,od=String.raw`${og}|<[^<>\r\n]*>|${rt(String.raw`[A-Za-z0-9!@#%^&*._+\-=]`)}|\$(?![{(])`,ig=String.raw`"[^"]*"|'[^']*'`,qc=String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${od}){0,${ie}}`,Wc=new RegExp(String.raw`(?!config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))`+`((?:${od}){1,${ie}}(?:${qc}){0,${Zn}}|(?:${qc}){1,${Zn}}|${ig})`),sg=8,Bc="token|secret|password|passwd|api[_-]?key",Ho="(?<![a-z0-9_]|[a-z0-9_]-)(?:(?:[a-z0-9]+_)+(?:password|passphrase)|(?:[a-z0-9]+[_-])*(?:secret|token|(?:api|secret|private|access)[_-]?key|client[_-]?secret|passwd|pwd))",ue=4096,id=String.raw`"(?=[^"\s]{8}[^"\s]*")|'(?=[^'\s]{8}[^'\s]*')|(?!["'])`,sd=String.raw`(?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.){1,${ue}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${ue}}|(?:[\w.-]+\/){1,${ue}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.){1,${ue}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${ue}}|(?:[\w.-]+\/){1,${ue}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+){0,${ue}}(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.){1,${ue}}[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/){1,${ue}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}(?=[\s,;)}\]]|$)|(?<!["'])[\w$.]+\()(?:(?<=")[^\s"]{8}[^\s"]*|(?<=')[^\s']{8}[^\s']*|(?<==)[A-Za-z0-9!@#$%^&*._+\-=/~?:|]{8,}|(?<!["'=])[A-Za-z0-9!@#$%^&*._+\-=/~]{8,})`,qo=new RegExp(`(?:${id})(${sd})`,"iy"),ag=8,cg=String.raw`[A-Za-z0-9!@#%^*._+\-=/~]`,ad=String.raw`&(?!&)`,dg=64,Yc=String.raw`'[^'\s]*'|"[^"\\\s]*(?:\\\S[^"\\\s]*){0,${ie}}"`,cd=String.raw`\$\{(?:${rt(String.raw`[^{}$'"\\\s]`)}|\\\S|${Yc}|\$(?!\{)|\$\{[^{}\s]*\}){0,${ie}}\}`+String.raw`|\$\((?:${rt(String.raw`[^()$'"\\\s]`)}|\\\S|${Yc}|\$(?!\()|\$\([^()\s]*\)){0,${ie}}\)`+String.raw`|<[^<>\s]*>|\$[A-Za-z_]\w*(?!\w)`,dd=e=>String.raw`${cd}|${rt(e)}|${ad}|\$(?![{(A-Za-z_])`,ld=e=>String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${dd(e)}){0,${ie}}`,lg=e=>String.raw`(?:(?:${e}|${ad}){1,${dg}}(?=[$<]))?(?:${cd})`+String.raw`(?:${dd(e)}){0,${ie}}(?:${ld(e)}){0,${Zn}}`,ug=e=>String.raw`(?:${ld(e)}){1,${Zn}}`,Gc=e=>String.raw`(?<!["'])(?:${e(cg)})`,Kc=String.raw`(?:[\w@#~]|!(?![.+\-*/%=^!(]))`,fg=String.raw`(?=(?:"[^"\s]*"|'[^'\s]*')[$<"']`+String.raw`|"(?=[^"\s]*[$<])[^"\s]*"${Kc}|'(?=[^'\s]*[$<])[^'\s]*'${Kc})`,mg=String.raw`(?<=")(?=[^"\s]*[$<])[^"\s]+|(?<=')(?=[^'\s]*[$<])[^'\s]+`,Xc=new RegExp(`(?:${fg}|${id})((?=["'])(?:${Gc(ug)})|${mg}|${Gc(lg)}|${sd})`),Jc=/["']?([A-Za-z0-9+/=_-]{24,})/,Go=[{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(?:${Vc})\s*[:=]\s*`+Wc.source,"gi"),structured:{keys:Vc,value:Wc.source,element:!0},minimumLiteralLength:sg},{name:"absolute-home-path",mutationRule:"absolute_home_path",regex:Ky,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",regex:/(?<![A-Za-z0-9._-])[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(?:${Bc})\s*[:=]\s*`+Jc.source,"gi"),structured:{keys:Bc,value:Jc.source},mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.",minimumEntropy:3.5},{name:"credential-key-assignment",mutationRule:"credential_key_assignment",regex:new RegExp(String.raw`\b(?:${Ho})\s*[:=]\s*`+Xc.source,"gi"),structured:{keys:Ho,value:Xc.source,element:!0,elementValue:!0},mutationOnlyReason:"Key-named assignments in source code and test fixtures are identifiers and synthetic data; repository scans keep the token-format rules, which recognize real credentials there.",minimumEntropy:3,minimumLiteralLength:ag,literalValue:qo,baseline:{regex:new RegExp(String.raw`\b(?:${Ho})\s*[:=]\s*`+qo.source,"gi"),value:qo.source},rejectValue:/^(?:[\w.-]+\/)*id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(?:\.pub)?$/u,rejectStatementReference:/^[A-Z]+(?:_[A-Z]+)+$/u}];function*ud(e,t){if(e.mutationRule==="absolute_home_path"){yield*rg(t,e.regex);return}for(let n of fd(e))yield*Eg(n,t),n.structured&&(yield*iw(n,n.structured,t))}var Zc=new WeakMap;function fd(e){let t=e.baseline;if(t===void 0)return[e];let n=Zc.get(e);return n===void 0&&(n={...e,regex:t.regex,minimumLiteralLength:void 0,literalValue:void 0,baseline:void 0},e.structured&&(n.structured={...e.structured,value:t.value}),Zc.set(e,n)),[e,n]}function pg(e,t){let n=e[t-1]==="#"||e[t-1]==="!"?t-1:t;return e[n-1]==="{"&&e[n-2]==="$"}var Ko=new WeakSet,md=new WeakMap,_g=4096;function hg(e,t,n){let r=[],o=[],i=t+n.length;return Qc(e,t,i,o,r),Qc(e,i,Math.min(e.length,i+_g),o),r}function Qc(e,t,n,r,o){for(let i=t;i<n&&(o!==void 0||r.length>0);i+=1){let s=r.at(-1);if(e[i]==="$"&&(e[i+1]==="{"||e[i+1]==="(")&&s?.quoted!=="'"){let a={open:i,close:n,command:e[i+1]==="(",quoted:[]};o?.push(a),r.push({span:a,closer:e[i+1]==="{"?"}":")"}),i+=1}else s!==void 0&&(i=yg(e,i,r))}}function yg(e,t,n){let r=n.at(-1),o=e[t];return o==="\\"&&r.quoted!=="'"?t+1:(r.quoted!==void 0?o===r.quoted&&(r.span.quoted.push([r.quoteStart,t]),r.quoted=void 0):o==="'"||o==='"'?(r.quoted=o,r.quoteStart=t):o===r.closer&&(n.pop().span.close=t),t)}function gg(e){let t=[],n=0;return r=>{for(;n<e.length&&e[n].open<r;n+=1){for(;t.length>0&&t.at(-1).close<e[n].open;)t.pop();t.push(e[n])}for(;t.length>0&&t.at(-1).close<r;)t.pop();return t.at(-1)}}function wg(e,t){let n=0,r=e.quoted.length-1;for(;n<=r;){let o=n+r>>1,[i,s]=e.quoted[o];if(t<i)r=o-1;else if(t>s)n=o+1;else return!0}return!1}var pd=/\$[({A-Za-z_]|</u;function*Eg(e,t){let n=e.regex;n.lastIndex=0;let r=bg(e),o;for(let i of t.matchAll(n))er(e,i)?yield{index:i.index}:r!==void 0&&pd.test(i[1])&&(o??=new RegExp(n),yield*Sg(e,o,t,i,r==="deep"))}function bg(e){return e.minimumLiteralLength===void 0?void 0:e.minimumEntropy===void 0&&e.literalValue===void 0&&e.rejectValue===void 0?"deep":"shallow"}function*Sg(e,t,n,r,o){let i=r.index+r[0].length;t.lastIndex=i-r[1].length;let s;for(let a=t.exec(n);a!==null&&a.index<i;a=t.exec(n)){if(pg(n,a.index)){t.lastIndex=a.index+1;continue}s??=gg(hg(n,i-r[1].length,r[1]));let c=s(a.index);c!==void 0&&(md.set(a,c.close),c.command&&!wg(c,a.index)&&Ko.add(a)),er(e,a)?yield{index:a.index}:o&&pd.test(a[1])&&(t.lastIndex=a.index+a[0].length-a[1].length)}}var ed=new Map,td=/[\r\n\u2028\u2029]/u;function Xo(e){let t=`${e.keys}\0${e.value}\0${e.element===!0}`,n=ed.get(t);return n||(n={key:new RegExp(String.raw`\b(?:${e.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(e.value,"iyd"),...e.element?{element:{open:new RegExp(String.raw`<(?:${e.keys})(?:\s[^<>]*)?>`,"gi"),close:new RegExp(String.raw`<\/(?:${e.keys})\s*>`,"iy"),span:new RegExp(String.raw`<(?!\/?(?:${e.keys})\b)[^<>]*>`,"iy")}}:{}},ed.set(t,n)),n}function _d(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 Tg(e,t){return _d(e,t).end}function vg(e,t,n){return e.at(-1)==="}"?n:t}function Ig(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&&vg(o,n,r)(s))return{found:!0,end:s};s=Tg(e,s)-1;break;default:break}}return{found:!1,end:e.length}}var Ag=/\\(?: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,Cg={n:`
108
- `,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function xg(e,t){let n=e[0],r=e.slice(1,t?-1:void 0).replaceAll(Ag,s=>{let a=s[1];if((a==="u"||a==="x")&&s.length>2)return String.fromCharCode(Number.parseInt(s.slice(2),16));if(/^[0-7]$/u.test(a))return String.fromCharCode(Number.parseInt(s.slice(1),8));if(a==="U"&&s.length===10){let c=Number.parseInt(s.slice(2),16);return c<=1114111?String.fromCodePoint(c):"\uFFFD"}return Cg[a]??a}),o=r.replaceAll(n,n==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," "),i=t?n:"";return{reading:`${n}${o}${i}`,...hd(`${n}${r}${i}`,t)}}function hd(e,t){return{original:e,bodyStart:1,bodyEnd:e.length-(t?1:0)}}var Rg=64;function yd(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-Rg);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 gd(e,t,n,r=!1){let o=(a,c,d)=>{t.lastIndex=c;let l=t.exec(a);if(l===null||td.test(l[0]))return null;let u=l.indices?.[1];return d!==void 0&&u!==void 0&&(l[1]=d.original.slice(Math.max(u[0],d.bodyStart),Math.min(u[1],d.bodyEnd)),Jo.add(l)),er(e,l)?l:null},i=a=>{if(n[a]!=='"'&&n[a]!=="'")return;let{end:c,terminated:d}=_d(n,a),l=n.slice(a,c);if(!r&&!l.includes("\\"))return;if(td.test(l))return[];let u=xg(l,d);return(n[a]==="'"?[u,{reading:l,...hd(l,d)}]:[u]).map(f=>o(f.reading,0,f)).filter(f=>f!==null)},s=a=>{let c=i(a);if(c!==void 0)return c;let d=o(n,a);return d===null?[]:[d]};return{direct:a=>o(n,a)!==null,escaped:a=>(i(a)?.length??0)>0,accepts:a=>c=>s(c).some(d=>!(a&&/\s/u.test(kg(e,d))))}}function kg(e,t){return e.minimumLiteralLength===void 0?t[0]:wd(t)}var Jo=new WeakSet;function wd(e){let t=Ko.has(e)&&!$e(Bt(e))?Og(e[1]):void 0,n=t??e[1],r=t!==void 0||Ng(e);return Jo.has(e)||$e(Bt(e))?vd(n,r):Iw(n,r)}function Og(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="'"||n==='"')t=Ed(e,t);else if(n==="$"&&(e[t+1]==="{"||e[t+1]==="("))t=Math.max(t,Wo(e,t)-1);else if(/[|&;<>]/u.test(n))return e.slice(0,t)}}var Dg=/^[;,)}\]]{0,64}/u;function Ng(e){let t=e.input,n=e.index+e[0].length,r=$e(Bt(e))&&$e(t[n])?n+1:$e(e[0].at(-1))?n:-1,o=r===-1?n:r,i=Dg.exec(t.slice(o,o+zg))[0].length,s=o+i;if(s===t.length||/\s/u.test(t[s])||md.get(e)===o||Ko.has(e)&&/[|&;<>]/u.test(t[o]))return!0;if(r===-1||i===0)return!1;let a=Lg(e,r===n+1),c=t.slice(s,s+40),d=/[}\]]/u.test(t.slice(o,s));return a!==void 0&&(Fg.test(c)||(a==="element"||d)&&jg.test(c))}function Lg(e,t){let n=e.input,r=e.index+e[0].length-e[1].length-(t?1:0),o=n.slice(Math.max(0,r-Mg),r);return Pg.test(o)?"element":$g.test(o)?"key":void 0}var Mg=512,$g=/[{,]\s*(["'])[^"'\r\n]{1,256}\1\s*[:=]\s*$/u,Pg=/[[,]\s*$/u,Fg=/^(?:["'`]|[{[](?:[\s"'`{[\]}]|$|(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]))/u,jg=/^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]/u,zg=64,Ug=/^\s{0,16}\(/u,Vg=/(?<![=!<>])=[ \t]{0,16}$/u;function Bt(e){return e.input[e.index+e[0].length-e[1].length-1]}function $e(e){return e==='"'||e==="'"}var Hg=/[$<"']/u;function qg(e){if(Jo.has(e)||$e(Bt(e))||!/^[$<]/u.test(e[1]))return!1;let t=e.index+e[0].length,n=t-e[1].length,r=e.input.slice(t,t+18);if(e[1][0]==="<"&&(Jg(e[1])||Vg.test(e.input.slice(Math.max(0,n-18),n))||Qg.test(r)))return!0;let o=Wg(e[1]),i=e[1][o]==="!"?e[1][o+1]:e[1][o];return Zg.test(i??"")||Ug.test(r)}function Wg(e){let t=0;for(let n=Wo(e,t);n!==-1;n=Wo(e,t))t=n;return t}function Wo(e,t){let n=e[t];if(n==="<")return Bg(e,t);if(n!=="$")return-1;let r=e[t+1];if(r==="{"||r==="(")return Yg(e,t+1,r);Qn.lastIndex=t;let o=Qn.exec(e)?.[0];return o===void 0?-1:t+o.length}function Bg(e,t){let n=e.indexOf(">",t+1),r=e.indexOf("<",t+1);return n!==-1&&(r===-1||n<r)?n+1:-1}function Yg(e,t,n){let r=n==="{"?"}":")",o=0;for(let i=t;i<e.length;i+=1){let s=e[i];if(s==="\\")i+=1;else if(s==="'"||s==='"')i=Ed(e,i);else if(s===n)o+=1;else if(s===r&&--o===0)return i+1}return-1}function Ed(e,t){let n=e[t];for(let r=t+1;r<e.length;r+=1){if(e[r]===n)return r;n==='"'&&e[r]==="\\"&&(r+=1)}return e.length}var Gg=/^[\w$.[\]|&,{}:;?]+$/u,Kg=/^(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?)(?:\|(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?|[A-Za-z_$][\w$.]*))*$/u,Xg=/\b(?:string|number|boolean|bigint|symbol|any|unknown|object|never|void|undefined|null)\b/u;function Jg(e){let t=e.slice(1,e.indexOf(">"));return Kg.test(t)?!0:Gg.test(t)?Xg.test(t)||/[.|&[{]/u.test(t)||/^[A-Z][\w$]*$/u.test(t)&&(t.length===1||/[a-z]/u.test(t)):!1}var Zg=/[.+\-*/%=^&]/u,Qg=/^\s{0,16}(?:\?\.|\?\?|\|\||&&|[([])/u;function ew(e,t,n){if(n)return!1;let r=t.replaceAll('"',"'");return e.lastIndex=0,e.exec(`"${r}"`)?.[1]===r}function bd(e,t){if(!e.structured)return;let n=`${JSON.stringify(t)}:`,r=Xo(e.structured).key;r.lastIndex=0;for(let o=r.exec(n);o;o=r.exec(n)){if(o.index+o[0].length!==n.length)continue;let i=yd(n,o.index,o[1]);if(i!=="malformed")return i}}function Sd(e,t,n){if(!e.structured)return!1;let r=JSON.stringify(t).replaceAll("\u2028","\\u2028").replaceAll("\u2029","\\u2029");return fd(e).some(o=>gd(o,Xo(o.structured).value,r,!0).accepts(n)(0))}function*tw(e,t,n){let r=new RegExp(e.open);for(let o=r.exec(t);o;o=r.exec(t)){let i=o.index+o[0].length,s=nw(e,t,i);if(s===void 0){r.lastIndex=o.index+1;continue}n(t.slice(i,s.start).trim())&&(yield{index:o.index}),r.lastIndex=s.end}}function nw(e,t,n){for(let r=t.indexOf("<",n);r!==-1;){e.close.lastIndex=r;let o=e.close.exec(t);if(o!==null)return{start:r,end:r+o[0].length};e.span.lastIndex=r;let i=e.span.exec(t);if(i===null)return;r=t.indexOf("<",r+i[0].length)}}function rw(e,t,n){return t<e.exact||n&&t<e.compact}function ow(e,t,n,r){return(n||e.escaped(r)&&!e.direct(r))&&t(r)}function*iw(e,t,n){let r=Xo(t),o=gd(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=yd(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(rw(s,f,l))continue;let y=Ig(n,f,u,o.accepts(!0));s[l?"compact":"exact"]=y.end,y.found&&(yield{index:a.index})}else ow(o,u,c,f)&&(yield{index:a.index})}r.element&&(yield*tw(r.element,n,aw(e,t,r)))}var sw=8;function aw(e,t,n){if(!t.elementValue){let r=e.minimumLiteralLength??sw;return o=>vd(o).length>=r}return r=>{let o=r.replaceAll('"',"'");n.value.lastIndex=0;let i=n.value.exec(`"${o}"`);return i===null||i[1]!==o?!1:(i[1]=r,er(e,i))}}function cw(e,t,n){let r=t.index+t[0].length;return/^[ \t]*;/u.test(t.input.slice(r,r+64))&&!$e(Bt(t))&&e.test(n)}function dw(e,t){for(let n=t+1;n<e.length;n+=1){if(e[n]===">")return n;if(e[n]==="<")return-1}return-1}function Bo(e,t){e.raw+=t,e.literal+=t}function lw(e,t,n){let r=e[t+1];if(e[t]!=="$"||r!=="{"&&r!=="(")return-1;let o=r==="{"?e.slice(t+2,t+2+gw(e,t+2)):"",i=n[0],s=n.length===1&&i.quote!==void 0&&i.literal.length===i.pieceStart;return n.push({close:r==="{"?"}":")",keep:o!=="",raw:`$${r}${o}`,literal:"",opensPiece:s}),t+2+o.length}var uw=/[A-Za-z_]/u,fw=/\w/u,mw=/[{(A-Za-z_]/u,Qn=/\$[A-Za-z_]\w*/y,pw=/^_*[A-Z][A-Z0-9_]*$/u,_w=/^\$[A-Za-z_]\w*$/u,hw=/^(["'])\$[A-Za-z_]\w*\1$/u;function yw(e,t,n){Qn.lastIndex=t;let r=Qn.exec(e)?.[0];return r===void 0?-1:(n.literal===""&&pw.test(r.slice(1))?n.raw+=r:Bo(n,r),t+r.length)}function gw(e,t){if(!uw.test(e[t]??""))return 0;let n=t+1;for(;n<e.length&&fw.test(e[n]);)n+=1;e[n]===":"&&(n+=1);let r=e[n];return r==="-"||r==="="||r==="+"?n+1-t:0}function ww(e,t){let n=e.pop(),r=e.at(-1);r.raw+=`${n.raw}${t}`,n.keep&&(r.literal+=n.literal)}var nd=/[^$<"'\\})]+/y,Ew='$`"\\\n';function bw(e,t){return e===`
110
- `?"":t==='"'&&!Ew.includes(e)?`\\${e}`:e}function Sw(e,t,n){let r=e[t],o=n.quote;if(o==='"'&&r==="$"&&mw.test(e[t+1]??""))return-1;let i=1,s=r;if(r==="\\"&&o!=="'"&&t+1<e.length)i=2,s=bw(e[t+1],o);else if(o===void 0){if(r!=='"'&&r!=="'")return-1;n.quote=r,s=""}else r===o&&(n.quote=void 0,s="");return n.raw+=e.slice(t,t+i),n.keep&&(n.literal+=s),t+i}function Tw(e,t,n,r,o){let i=n.at(-1);nd.lastIndex=t;let s=nd.exec(e)?.[0];if(s!==void 0)return Bo(i,s),t+s.length;if(n.length>1){let f=Sw(e,t,i);if(f!==-1)return f}else if(r&&vw(e[t],i))return t+1;let a=lw(e,t,n);if(a!==-1)return a;let c=n.at(-1),d=e[t],l=o&&d==="$"?yw(e,t,c):-1;if(l!==-1)return l;if(n.length>1&&d===c.close)return ww(n,d),t+1;let u=d==="<"?dw(e,t):-1;return u!==-1?(c.raw+=e.slice(t,u+1),u+1):(Bo(c,d),t+1)}function vw(e,t){return e!=='"'&&e!=="'"?!1:t.quote===void 0?(t.quote=e,t.pieceStart=t.literal.length,!0):e!==t.quote?!1:(t.quote=void 0,!0)}function Td(e,t,n){if(n&&(_w.test(e)||t&&hw.test(e)))return"";let r={close:"}",keep:!0,raw:"",literal:""},o=[r];for(let i=0;i<e.length;)i=Tw(e,i,o,t,n);for(let i=o.length-1;i>0;i-=1){let s=o[i],a=o[i-1];a.raw+=s.raw,t&&i===1&&s.opensPiece===!0||(a.literal+=s.raw)}return r.literal}function vd(e,t=!0){return Td(e,!1,t)}function Iw(e,t=!0){return Td(e,!0,t)}function er(e,t){let n=e.minimumLiteralLength===void 0?t[1]:wd(t);if(e.minimumLiteralLength!==void 0&&n.length<e.minimumLiteralLength||e.literalValue&&Hg.test(t[1])&&!ew(e.literalValue,n,qg(t))||e.rejectValue?.test(n)===!0||e.rejectStatementReference&&cw(e.rejectStatementReference,t,n))return!1;if(e.minimumEntropy===void 0)return!0;let r=[...n],o=new Map;for(let s of r)o.set(s,(o.get(s)??0)+1);let i=0;for(let s of o.values()){let a=s/r.length;i-=a*Math.log2(a)}return i>=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]="6175fcf6-186d-50f6-8642-ba3432cf4b64")}catch{}})();var Aw=[{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"}],Zo=new Map(Aw.map(e=>[e.action,e])),Cw=/^(?:0|[1-9]\d*)$/u,xw=2**32-2;function Rw(e){return Cw.test(e)&&Number(e)<=xw}function Cd(e){let t=[];for(let n of Go){let r=Ow(n,e);r&&t.push({rule:n,match:r})}return t}function kw(e,t){let n=t.names.get(e);return n===void 0&&(n=Cd(e),t.names.set(e,n)),n}function xd(e,t){let n=t.entries.get(e);return n===void 0&&(n=Array.isArray(e)?Object.getOwnPropertyNames(e).filter(Rw).map(r=>({name:r,value:e[Number(r)],segment:`[${r}]`,nameMatches:[]})):Object.entries(e).map(([r,o],i)=>{let s=kw(r,t);return{name:r,value:o,segment:s.length>0?`[key ${i}]`:`.${r}`,nameMatches:s}}),t.entries.set(e,n)),n}function Id({rule:e,match:t},n,r){let o={rule:e.mutationRule,path:n};return r&&(o.property_name=!0),t.normalizations&&(o.normalizations=t.normalizations),t.normalization_incomplete&&(o.normalization_incomplete=!0),o}function Rd(e,t){for(let n=t.length-1;n>=0;n-=1)e.push(t[n])}function Ow(e,t){try{return Dw(e,t)}catch(n){return kd(n)}}function kd(e){if(!(e instanceof RangeError))throw e;return{index:0,normalization_incomplete:!0}}function Dw(e,t){let n=ud(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 Nw(e,t){let n=[],r=new WeakSet,o=[{value:e,path:"$"}];for(let i=o.pop();i!==void 0;i=o.pop()){let{value:s,path:a}=i;if(typeof s=="string")for(let c of Cd(s))n.push(Id(c,a,!1));else if(typeof s=="object"&&s!==null&&!r.has(s)){r.add(s);let c=xd(s,t);for(let d of c)for(let l of d.nameMatches)n.push(Id(l,`${a}${d.segment}`,!0));Rd(o,c.map(d=>({value:d.value,path:`${a}${d.segment}`})))}}return n}var tr=Go.filter(e=>"structured"in e),Lw=tr.map(()=>({named:!1,exact:!1})),Od=/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/gu,Mw=3;function Ad(e){return e.replace(Od,"_")}function $w(e){let t=[...e.matchAll(Od)].map(n=>n.index).slice(-Mw).map(n=>`${Ad(e.slice(0,n))}_${e.slice(n)}`);return[...new Set([e,Ad(e),...t])]}function Pw(e){let t=$w(e);return tr.map(n=>{let r=t.map(o=>bd(n,o));return r.includes("exact")?"exact":r.includes("prefixed")?"prefixed":void 0})}var Fw=tr.map(()=>{});function jw(e,t,n,r){let o=xd(e,r);if(Array.isArray(e)){let i=n.map(({named:s,exact:a})=>a?"lenient":s?"compact":void 0);return o.map(s=>({value:s.value,path:`${t}${s.segment}`,contexts:n,judgments:i}))}return o.map(({name:i,value:s,segment:a})=>{let c=Pw(i);return{value:s,path:`${t}${a}`,contexts:n.map(({named:d,exact:l},u)=>({named:d||c[u]!==void 0,exact:l||c[u]==="exact"})),judgments:c.map((d,l)=>d==="exact"?"lenient":d==="prefixed"||n[l].named?"compact":void 0)}})}function zw(e,t){let n=[],r=new WeakMap,o=[{value:e,path:"$",contexts:Lw,judgments:Fw}];for(let i=o.pop();i!==void 0;i=o.pop()){let{value:s,path:a,contexts:c,judgments:d}=i;if(typeof s=="string"){d.forEach((f,_)=>{let y=tr[_];if(f===void 0)return;let g;try{g=Sd(y,s,f==="compact")}catch(h){kd(h),n.push({rule:y.mutationRule,path:a,normalization_incomplete:!0});return}g&&n.push({rule:y.mutationRule,path:a})});continue}if(typeof s!="object"||s===null)continue;let l=c.map(({named:f,exact:_})=>_?"e":f?"n":"-").join(""),u=r.get(s)??new Set;u.has(l)||(r.set(s,u.add(l)),Rd(o,jw(s,a,c,t)))}return n}function Dd(e){let t=new Set,n={entries:new WeakMap,names:new Map};return[...Nw(e,n),...zw(e,n)].filter(r=>{let o=`${r.rule}\0${r.path}\0${r.property_name===!0}`;return t.has(o)?!1:(t.add(o),!0)})}function Uw(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=Dd(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 Vw(e){return Zo.has(e.trim().toLowerCase())}function Hw(){return[...Zo.keys()].sort((e,t)=>e.localeCompare(t))}function tC(e){return Zo.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 qw=/\b([a-z][a-z0-9]*)-(\d+)(?:-[a-z0-9]+)*\b/giu,Ww=/^(?:utf|iso|sha|tls|http|covid|match)$/iu;function Qo(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Ld(e){return[...new Set(Qo(e).match(/[\p{L}\p{N}]+/gu)??[])]}function Nd(e){let t=Qo(e);return{normalized:t,tokens:Ld(t),issueCodes:[...new Set([...e.matchAll(qw)].filter(n=>{let r=n[1],o=n.index,i=e.slice(o+n[0].length);return!Ww.test(r)&&(r===r.toUpperCase()||r.length<=2||o===0&&/^\s*(?::|—|–|\])/u.test(i))}).map(n=>n[0].toLowerCase()))]}}function Bw(e,t){return Yw(Nd(e),Nd(t))}function Yw(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:en(e.tokens,t.tokens),reason:"title_token_jaccard"}}import Gw 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]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var Md=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){let s=o;o+=1,r[s]=await n(e[s])}});return await Promise.all(i),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]="f65cb540-c93d-5da7-b4c3-bd189b2e4967")}catch{}})();var pC="mutation_guard.stale_in_progress_hours",jd=36e5,_C=["claim_record_unavailable","discarded_history_tail","rewritten_history","workspace_restored"],Kw=new Set(["history_repair","history_redact","merge_reconcile"]);function $d(e){return e==="history_salvage"||Kw.has(e)}function Pd(e){let t=e.reanchor_evidence;if(t===void 0)return!1;if(!Array.isArray(t))return!0;let n=Ir(e.patch);return t.some(r=>!ti(r)||r.patch_hash!==n)}var Xw=16;function Fd(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function zd(e){return Math.max(1,Math.trunc(e))}function Ud(e,t){let n;for(let r of[e,t]){let o=Date.parse(r??"");typeof r=="string"&&Number.isFinite(o)&&(n===void 0||o>n.time)&&(n={value:r,time:o})}return n?.value}function Vd(e,t){return Math.max(0,Math.floor((t-Date.parse(e))/jd))}var Jw=864e13;function hC(e,t){let n=Date.parse(e)+t*jd;return Math.abs(n)<=Jw?new Date(n).toISOString():null}function Hd(e){let t=e.status_registry;if(t===void 0){let r=Fd(e.in_progress_status);return o=>Fd(String(o.status))===r}let n=Qt(e.in_progress_status??t.in_progress_status,t);return r=>Qt(r.status,t)===n}function qd(e){let t=e.assignee?.trim();return t!==void 0&&t.length>0?t:void 0}function ei(e){return e.sort((t,n)=>(n.age_hours??-1)-(t.age_hours??-1)||t.id.localeCompare(n.id))}var Zw="Claim active work with `pm claim <id>` or return abandoned work to open with `pm update <id> --status open`.";function Qw(e,t,n,r){let o=qd(e);if(t===void 0)return o===void 0?{unowned:{id:e.id,last_activity_at:null,age_hours:null}}:{};let i={id:e.id,last_activity_at:t,age_hours:Vd(t,r)},s=i.age_hours>=n;return o!==void 0?s?{idle:{...i,assignee:zi(o)}}:{}:s?{unowned:{...i},idle:{...i},stale:{...i}}:{unowned:{...i}}}function Wd(e,t){let n=zd(t.threshold_hours),r=(t.now??new Date).getTime(),o=Hd(t),i=[],s=[],a=[];for(let c of e){if(!o(c))continue;let d=Qw(c,Ud(c.updated_at,t.last_history_activity?.(c)),n,r);d.unowned&&i.push(d.unowned),d.idle&&s.push(d.idle),d.stale&&a.push(d.stale)}return{threshold_hours:n,unowned:{count:i.length,items:ei(i)},idle:{count:s.length,items:ei(s)},stale:{threshold_hours:n,count:a.length,items:ei(a),remediation:Zw}}}function eE(e,t){return Wd(e,t).stale}function Bd(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.ts=="string"&&typeof t.op=="string"&&Array.isArray(t.patch)&&t.patch.every(n=>n!==null&&typeof n=="object"&&typeof n.path=="string")}function tE(e){if(Bd(e)){if(e.op==="history_compact_baseline"){let t=ni(e);return t.kind==="recorded"?t.at??void 0:e.ts}return Zi(e)==="substantive"?e.ts:void 0}}function ti(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ni(e){let t=e.context;if(t===void 0)return{kind:"legacy"};if(!ti(t))return{kind:"malformed"};let n=t.history_compaction;if(n===void 0)return{kind:"legacy"};if(!ti(n))return{kind:"malformed"};if(!("last_activity_at"in n))return{kind:"legacy"};let r=n.last_activity_at;return r===null?{kind:"recorded",at:null}:typeof r=="string"&&Number.isFinite(Date.parse(r))?{kind:"recorded",at:r}:{kind:"malformed"}}function yC(e){return Bd(e)&&Number.isFinite(Date.parse(e.ts))&&(e.op!=="history_compact_baseline"||ni(e).kind!=="malformed")}function gC(e,t){let n=e[t];if(n===void 0||n.op==="history_compact_baseline"||$d(n.op))return"claim_record_unavailable";if(Pd(n))return"rewritten_history";for(let r of e.slice(t+1)){if($d(r.op))return r.op==="history_salvage"?"discarded_history_tail":"rewritten_history";if(Pd(r))return"rewritten_history"}}function wC(e){let t=ni(e);return t.kind==="recorded"?t.at:void 0}function Yd(e){let t;for(let n of e){let r=tE(n),o=Date.parse(r??"");r!==void 0&&Number.isFinite(o)&&(t===void 0||o>t.time)&&(t={value:r,time:o})}return t?.value}function EC(e){return Yd(e)??null}async function nE(e,t){let n;try{n=await pt(Gw.join(e,"history",`${t}.jsonl`),t)}catch{return}return Yd(n)}async function rE(e,t,n){let r=zd(n.threshold_hours),o=(n.now??new Date).getTime(),i=Hd(n),s=new Map,a=t.filter(c=>{if(!i(c))return!1;if(qd(c)===void 0)return!0;let d=Ud(c.updated_at,void 0);return d===void 0||Vd(d,o)>=r});return await Md(a,Xw,async c=>{let d=await nE(e,c.id);d!==void 0&&s.set(c.id,d)}),Wd(t,{...n,now:new Date(o),last_history_activity:c=>s.get(c.id)})}async function oE(e,t,n){return(await rE(e,t,n)).stale}(function(){try{var e=typeof window<"u"?window:typeof 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 iE=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"}),sE=/&(?:lt|gt|quot|#39|amp);/g;function aE(e){return typeof e!="string"||!e.includes("&lt;")&&!e.includes("&gt;")?e:e.replace(sE,t=>iE[t])}function cE(e){return ri(e,new WeakMap)}function ri(e,t){if(typeof e=="string")return aE(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(ri(r,t));return n}if(e!==null&&typeof e=="object"){if(!dE(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:ri(i,t),enumerable:!0,writable:!0,configurable:!0});return r}return e}function dE(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 lE(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 Gd(e){return e.split(/[\s,|]+/).map(t=>t.trim()).filter(t=>t.startsWith("--"))}function uE(e){return Gd(e)[0]??null}function fE(e,t){let n=uE(t);if(n===null)return!1;let r=o=>o.slice(2).replaceAll("-","_");return Gd(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 mE(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 oi from"node:fs/promises";import nr 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 pE(e){return"json_markdown"}function Kd(e,t){return nr.relative(e,t).replaceAll("\\","/")}function _E(e){return String(e).replaceAll(/[^a-zA-Z0-9._-]+/g,"_").slice(0,120)}async function hE(e,t,n){e!==t&&ce(await oi.readFile(t,"utf8"),{format:"json_markdown",requireSupportedFormat:!0,schema:n})}async function yE(e,t,n="item_format:migrate",r=Q,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=pE(t),l=Object.entries(r);for(let[u,f]of l){let _=nr.join(e,f),y=[];try{y=await oi.readdir(_)}catch{continue}let g=new Map;for(let w of y){let E=nr.join(_,w),I=dt(E);if(!I)continue;let C=nr.extname(w),M=w.slice(0,w.length-C.length).trim();if(M.length===0)continue;let x=g.get(M)??{};x[I]=E,g.set(M,x)}let h=[...g.keys()].sort((w,E)=>w.localeCompare(E));for(let w of h){let E=g.get(w);c+=1;let I=E[d];if(!I)continue;let C=E[t]??I,M=C===E[t]?t:d;try{let x=await oi.readFile(C,"utf8"),D=ce(x,{format:M,requireSupportedFormat:!0,schema:o,onWarning:Z=>a.push(`item_format_migration_parse_warning:${w}:${Z}`)});await hE(C,I,o);let J=ze(e,u,w,t,r),ae=ft(D,{format:t,schema:o});await A(J)!==ae&&(await v(J,ae),a.push(...await U({path:J,scope:"project",op:n})),i.add(w)),await st(I),s.add(Kd(e,I)),a.push(...await U({path:I,scope:"project",op:`${n}:remove`})),i.add(w)}catch(x){a.push(`item_format_migration_skipped:${Kd(e,C)}:${_E(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 gE=new Set(["completed","superseded"]);function wE(e){return e!==void 0&&gE.has(e)}function EE(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 bE}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 SE=/^[a-z][a-z0-9_-]{0,63}$/u,TE=new Set(["constructor","prototype"]),Xd="settings:section:write",vE=240;function rr(e){return`sha256:${bE("sha256").update(ii(e)).digest("hex")}`}function ii(e){return Array.isArray(e)?`[${e.map(t=>ii(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ii(Object.getOwnPropertyDescriptor(e,t)?.value)}`).join(",")}}`:String(JSON.stringify(e))}function Zd(e){if(!SE.test(e)||TE.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(is.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 Qd(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 si(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,vE)}`,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 el(e){return typeof Reflect.get(e,"toJSON")=="function"}function ai(e){return e.length===0?"the value":e.join(".")}function tl(e,t){return Object.values(Object.getOwnPropertyDescriptors(e)).every(n=>"value"in n&&(!t||n.enumerable===!0))}function IE(e){if(Object.getPrototypeOf(e)!==Array.prototype||!tl(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&&!el(e)}function AE(e){let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&tl(e,!0)&&Object.getOwnPropertySymbols(e).length===0&&!el(e)}function CE(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return null;let n=ai(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 nl(e,t=[],n=new Set){if(typeof e!="object"||e===null)return CE(e,t);let r=ai(t);if(n.has(e))return{detail:`${r} is a circular reference`,representable:!1};if(!(Array.isArray(e)?IE(e):AE(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=nl(i,[...t,o],n);if(s!==null)return s}return n.delete(e),null}function rl(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 ai(o);let i=rl(r,o);if(i!==null)return i}return null}function Jd(e,t,n){return si(e,t,()=>{throw new Error(n)})}function xE(e,t){let n=nl(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 Jd(e,t,o)}let r=rl(t);return r!==null?Jd(e,t,`${r} is a reserved key that settings history cannot record`):JSON.parse(JSON.stringify(t))}function ol(e,t){return Object.hasOwn(e,t)?e[t]:void 0}async function RE(e,t,n={}){Zd(t);let r=Ee(e);await ve({path:r,scope:"project"});let o=await A(r),i=o===null?void 0:ol(Qd(o),t);if(i===void 0)return{section:t,source:"default",value:n.defaultValue,revision:null};let s=rr(i);return{section:t,source:"stored",value:si(t,structuredClone(i),n.validate),revision:s}}async function kE(e,t,n,r={}){Zd(t);let o=n===void 0?void 0:xE(t,si(t,n,r.validate)),i=Ee(e),s=await B(e);try{let a=await Dr({pmRoot:e,filePath:i,op:Xd,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=Qd(c),l=ol(d,t),u=l===void 0?null:rr(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:rr(o)};return it(l,o)?{raw:c,result:f}:(o===void 0?delete d[t]:d[t]=o,{raw:`${JSON.stringify(d,null,2)}
111
- `,result:{...f,changed:!0}})}});return a.changed&&await U({path:i,scope:"project",op:Xd}),a.result}finally{an(e)}}import OE from"node:readline/promises";import{stdin as DE,stdout as il}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 NE="PM_TELEMETRY_PROMPT",sl=new Set(["0","false","no","off"]),LE=new Set(["init","completion","completion-statuses","completion-tags","completion-types"]);function ME(e){return typeof e!="string"?!1:sl.has(e.trim().toLowerCase())}function $E(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t.length===0?!1:!sl.has(t)}function PE(e,t){if(t.json===!0||t.quiet===!0||process.stdin.isTTY!==!0||process.stdout.isTTY!==!0||ME(process.env[NE])||$E(process.env.CI))return!0;let n=e.trim().toLowerCase();return n.length===0?!0:LE.has(n)}function FE(e){let t=e.trim().toLowerCase();return!(t==="n"||t==="no")}async function jE(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 vn(e){await Ce.rm(Ye(e),{force:!0})}import N from"node:fs/promises";import v from"node:path";import{createHash as ip,randomUUID as va}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 ne=8,Ta=500,sp="metadata-derived-index",ap="metadata-cache.json",cp="metadata-cache-bodies.json",dp="metadata-cache-collections.json",lp="metadata-cache-delta.json",up="metadata-cache-manifest.json",wa=4,fp=["comments","notes","learnings","files","tests","test_runs","docs"];function Ia(){return Ct(pe())}function In(e){let t={...e},n={};for(let r of fp)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function Aa(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function Ca(e,t,n,r){let o=ip("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 An(e){return v.join(e,"runtime",ap)}function Cn(e){return v.join(e,"runtime",cp)}function Rn(e){return v.join(e,"runtime",dp)}function so(e){return v.join(e,"runtime",lp)}function ao(e){return v.join(e,"runtime",up)}function xn(e,t){let n=v.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var mp=24,q=new Map,On=new WeakMap;function co(e){return On.get(e)??e.source_cursor}function pp(e,t){let n=co(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){On.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 _p(e,t){if(!e)return;let n=co(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){On.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 yp(e,t){if(!e)return;let n=co(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){On.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 hp(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(pp(e,r),_p(t,r),yp(n,r))}function io(e,t){q.size>=mp&&!q.has(e)&&qi(q),q.set(e,t)}async function ye(e,t){let n;try{n=await N.stat(e)}catch{return q.delete(e),null}let r=q.get(e);if(r&&Dt(r.signature,n.mtimeMs,n.ctimeMs,n.size))return q.delete(e),q.set(e,r),r.envelope;let o;try{o=t(await N.readFile(e,"utf8"))}catch{o=null}return io(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function gp(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==ne||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=An(e),i=await ye(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await ye(xn(o,t),r);return s===null&&Mt(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function wp(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==ne||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Cn(e),o=await ye(r,n);return t&&o?.context_fingerprint!==t?await ye(xn(r,t),n):o}async function Ep(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==ne||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=Rn(e),o=await ye(r,n);return t&&o?.context_fingerprint!==t?await ye(xn(r,t),n):o}async function lo(e){let t=so(e),n=await ye(t,r=>{let o=JSON.parse(r);return o.version!==ne||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 uo(e){let t=ao(e),n=await ye(t,r=>{let o=JSON.parse(r);return o.version!==ne||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 Ge(e)}catch{}return null}async function Nt(e,t){await N.mkdir(v.dirname(e),{recursive:!0}),await T(e,JSON.stringify(t));try{let r=await N.stat(e);io(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{q.delete(e)}let n=v.dirname(v.dirname(e));if(e===An(n)||e===Cn(n)||e===Rn(n)){let r=xn(e,t.context_fingerprint);await T(r,JSON.stringify(t));try{let c=await N.stat(r);io(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{q.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>wa){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-wa)))await N.rm(d.path,{force:!0}),q.delete(d.path)}}}function bp(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function Ra(e,t,n){return e===void 0||bp(e,t,n)}function Mt(e,t){e&&!e.includes(t)&&e.push(t)}function Dt(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function Sp(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&&!$(o)&&Mt(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function vp(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 Tn(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await vp(e,n))))}function Lt(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&&Dt(o,r.mtime_ms,r.ctime_ms,r.size)})}function Tp(e){return Jt.some(t=>e.toLowerCase().endsWith(t))}function Ip(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function Ap(e,t,n){if(n)for(let r of await Te({path:e,scope:"project"}))Mt(t,r)}function Ea(e,t,n,r){if(e)return t&&n?n.collections:r}async function Cp(e,t,n){let r=await N.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=dt(e);await Ap(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],d=!n.forceSourceRead&&c!==void 0&&Dt(c,o,i,s),l=n.previousBodies[t],u=!n.forceSourceRead&&l!==void 0&&Dt(l,o,i,s),f=n.previousCollections[t],_=!n.forceSourceRead&&f!==void 0&&Dt(f,o,i,s);if(!(!d||n.includeBody&&!u||n.includeCollections&&!_))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:Ea(n.includeCollections,_,f,void 0),bodyLength:c.body_length,body:n.includeBody?l.body:void 0};let h=await N.readFile(e,"utf8"),g=ce(h,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:w=>Mt(n.warnings,w)}),y=In(g.metadata);return Ip(n.state.misses,n.includeBody,n.includeCollections,d,u,_),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:d?c.metadata:y.light,heavyMetadata:Ea(n.includeCollections,_,f,y.heavy),bodyLength:d?c.body_length:g.body.length,body:n.includeBody?g.body:void 0}}function Rp(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?Aa(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};Ra(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function xp(e,t,n,r){try{let o=await Cp(t,n,r);Rp(t,n,r,o)}catch{Mt(r.warnings,`item_list_item_read_failed:${e}/${v.basename(t)}`)}}function Op(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function kp(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function Dp(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function Np(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function Lp(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!Tp(s))continue;let a=v.join(o,s),c=v.relative(t.pmRoot,a);n.push(xp(r,a,c,t)),n.length===32&&(await Promise.all(n),n.length=0)}await Promise.all(n)}async function Mp(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Lt(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Nt(An(e.pmRoot),{version:ne,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Nt(ao(e.pmRoot),{version:ne,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:In(n.metadata).light,linkedFiles:n.metadata.files??[]}));t.length>=e.minimumIndexedItems?await ha({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:t}):await vn(e.pmRoot)}catch{}}async function $p(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 Nt(Cn(e.pmRoot),{version:ne,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function Pp(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 Nt(Rn(e.pmRoot),{version:ne,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function fo(e,t,n={}){let r=await uo(e);return n.required!==!0&&(r===null||r.entry_count<Ta)?async()=>{}:ve(e,sp,30,t,!1,!1,3e3)}async function PT(e,t){let n=await uo(e);if(n===null)return null;let r=await lo(e);if(r.invalid)return await Ge(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&&!Lt(i,await Tn(e,t))?null:{source_cursor:o,entry_count:n.entry_count}}function ba(e,t){let n=v.relative(e,t);return n===""||n===".."||n.startsWith(`..${v.sep}`)||v.isAbsolute(n)?null:n}async function Ge(e){await Promise.all([An(e),Cn(e),Rn(e),so(e),ao(e)].map(async t=>{await N.rm(t,{force:!0}),q.delete(t)})),await vn(e)}async function Fp(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await N.stat(e.mutation.itemPath),n=In(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 jp(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function mo(e){let t=ba(e.pmRoot,e.itemPath),n=e.previousItemPath?ba(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await Ge(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=Ca(e.preferredFormat,e.typeToFolder,e.schema,Ia()),o=await uo(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await lo(e.pmRoot);if(s.invalid)return await Ge(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=jp(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 Fp({mutation:e});let d=va();return await Nt(so(e.pmRoot),{version:ne,context_fingerprint:r,base_source_cursor:i,source_cursor:d,directory_signatures:await Tn(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await ga({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:d,row:e.document===null?null:{relativePath:t,metadata:In(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await vn(e.pmRoot),[]}catch{return await Ge(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function zp(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 Up(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function Vp(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=dt(n);if(!o)continue;let i=e.includeCollections?Aa(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);Ra(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 Hp(e){return e.forceSourceScan||kr()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Lt(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)&&Up(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function $t(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=Ia(),d=Ca(t,n,o,c),l=await lo(e);l.invalid&&await Ge(e);let u=await gp(e,d,i.cacheDiagnostics),f=s?await wp(e,d):null,_=a?await Ep(e,d):null;hp(u,f,_,l.envelope);let h=Op(u,d),g=kp(f,d),y=Dp(_,d),w=[...new Set(Object.values(n))],E=await Tn(e,w),I=Object.keys(h),C=Math.max(1,Math.floor(i.derivedIndexMinimumItems??Ta));if(Hp({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:d,existingCache:u,existingBodyCache:f,existingCollectionsCache:_,directorySignatures:E,entryKeys:I,minimumIndexedItems:C,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:y}))return Vp({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:h,previousBodies:g,previousCollections:y});let M=await Promise.all(w.map(Kt=>Sp(e,Kt,r))),R=kr(),D=Np(),J={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:R,previousEntries:h,previousBodies:g,previousCollections:y,state:D};await Lp(M,J);let ae=await Tn(e,w),Z=Lt(E,ae)?ae:{},H=D.misses.metadata||Object.keys(h).length!==Object.keys(D.newEntries).length||!Lt(u?.directory_signatures,Z)||u===null?va():u.source_cursor;return await Mp({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCache:u,previousEntries:h,directorySignatures:Z,state:D,minimumIndexedItems:C}),s&&await $p({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingBodyCache:f,previousBodies:g,state:D}),a&&await Pp({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCollectionsCache:_,previousCollections:y,state:D}),zp(D)}async function xa(e,t,n,r,o){return(await $t(e,t,n,r,o,{includeBody:!1})).map(i=>({metadata:i.metadata,body:i.body??""}))}async function Oa(e,t,n,r,o){return(await $t(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 qp}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 Bp(e,t){let n=-1,r=structuredClone(_t);for(let[a,c]of e.entries()){if(r=eo(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=Rt(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;la(a,e).historyIndex===n&&(s=a)}return{version:i,target:s}}async function ka(e,t,n){let r=new Set([le(t,n),Be(t)]);for(let o of r){let i=ee(e,o);if(!qp(i,{throwIfNoEntry:!1})?.isFile())continue;let s=await pt(i,o),a=-1;if(s.forEach((_,h)=>{_.op==="delete"&&(a=h)}),a<0)continue;let c=ua(s,s.length-1);if(Object.keys(c.metadata).length!==0)continue;let{version:d,target:l}=Bp(s,o),u=l===void 0?["history",o,"--verify"]:["get",o,"--at",l],f=be(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."]:[be(["restore",o,l])]],recovery:{suggested_retry:f,suggested_retry_args:u}})}}import{AsyncLocalStorage as Wp}from"node:async_hooks";import Da 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 Na=new Wp;function ZT(e,t){return Na.run({...e,pmRoot:Da.resolve(e.pmRoot)},t)}function La(e,t){let n=Na.getStore();return n?.pmRoot===Da.resolve(e)&&n.itemId===t?{bulk_checkpoint:n.checkpointId}:void 0}import po from"node:path";import{isUtf8 as Yp}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]="2fda779c-a87f-517c-b71a-626c4fef98e5")}catch{}})();async function Gp(e){try{return await he.access(e),!0}catch{return!1}}function Kp(e,t){e&&(e.includes(t)||e.push(t))}function _o(e){return e??Ct(pe())}function Xp(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Ke(e,t,n="pm-",r,o=Q){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=le(t,n),c=Be(t),d=[...new Set([s,a,c])].filter(f=>f.length>0),l=Object.entries(o),u=Xp(r);for(let f of d){let _=new Map;for(let[h]of l)for(let g of u){let y=ze(e,h,f,g,o);await Gp(y)&&_.set(y,_.get(y)??{id:f,type:h,itemPath:y,item_format:g})}if(_.size>1){let h=[..._.keys()].map(g=>po.relative(e,g).split(po.sep).join("/")).sort();throw new p(`Item ${f} has ambiguous identity across ${h.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:h})}for(let h of _.values())return h}return null}async function Pt(e,t={}){let n=await Jp(e,t);if(n.error!==null)throw n.error;return{raw:n.raw,document:n.document}}async function Jp(e,t={}){let n=await he.readFile(e.itemPath);if(!Yp(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 Te({path:e.itemPath,scope:"project"});let o;try{o=ce(r,{format:e.item_format,requireSupportedFormat:!0,schema:t.schema,extensionFieldNames:_o(t.extensionFieldNames),onWarning:i=>Kp(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 $a(e,t,n=Q,r,o){await cn(e);let i=await xa(e,t,n,r,o);return wn(i.length),i.map(s=>s.metadata)}async function Zp(e,t,n=Q,r,o){await cn(e);let i=await Oa(e,t,n,r,o);return wn(i.length),i.map(s=>s.metadata)}async function kI(e,t,n=Q,r,o,i={}){await cn(e);let s=await $t(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan});return wn(s.length),s.map(a=>({...a.metadata,body:a.body}))}function yo(e){return{async get(t){let n=await Ke(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Pt(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>$a(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function Qp(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await he.readdir(po.join(e,o));for(let s of i)for(let a of Jt)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function e_(e,t,n,r){let o=le(t,n),i=await Qp(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(a=>({id:a,distance:Se(a,o,s)})).filter(a=>a.distance!==null).sort((a,c)=>a.distance-c.distance).slice(0,3).map(a=>a.id)}async function Pa(e,t,n,r){let o=await ka(e,t,n);if(o)return o;let i=await e_(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 t_(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 Fa(e){let t=e.typeToFolder??ct(e.settings,pe()).type_to_folder,n=await Ke(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await Pa(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await vr(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 Pt(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:i}),c=a.metadata.assignee?.trim(),d=Ui(c),l=a.metadata.claim_principal?.trim()||c,u=Ir(e.author),f=ss(e.settings);if(d&&l!==u&&!e.force&&!t_(e.op,e.bypassAssigneeConflict)){if(f.ownership_enforcement==="strict")throw new p(`Item ${n.id} is assigned to ${d}. Use --force to override.`,m.CONFLICT);f.ownership_enforcement==="warn"&&i.push(`ownership_warning:assignee_conflict:${n.id}:${d}`)}return{typeToFolder:t,located:n,originalRaw:s,document:a,warnings:i,releaseLock:o,lease:r}}catch(i){throw await o(),i}}function ja(e){return Object.keys(e).length===0?void 0:e}async function za(e,t,n,r){return e.fence(async()=>{let o;try{o=await he.readFile(t.itemPath,"utf8")}catch(i){if(!$(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 n_(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 Ua(e){try{let t=await Ke(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return{document:pr};let n=ce(await he.readFile(t.itemPath,"utf8"),{format:t.item_format,requireSupportedFormat:!0,schema:e.settings.schema,extensionFieldNames:_o(e.extensionFieldNames)});return n.metadata.id===e.embeddedId?{document:n}:{document:e.fallback,revision:Ma}}catch{return{document:e.fallback,revision:Ma}}}var Ma="unreadable-after-storage-override";async function r_(e){let t=await sn("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 o_(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)}}function i_(e,t){Ki(e.metadata)&&t.push("deferred_fields")}async function ho(e){Wi(e.op);let t=await Fa({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{Cr(e.pmRoot,i,r.id);let d=Ve(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=Ve(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(l,{storageId:r.id});if(i_(l,u.changedFields),e.skipNoop===!0&&u.changedFields.length===0)return{item:d.metadata,body:d.body,changedFields:[],warnings:[...s,...u.warnings??[]]};let f={...e.resolveHistoryContext?.(),...La(e.pmRoot,r.id),...ts(e.pmRoot,[r.id,i.metadata.id])},_=Math.max(br(d.metadata),br(l.metadata));as(wr(e.pmRoot),_),_>Gi(l.metadata)&&(l.metadata.pm_format_version=_,u.changedFields.push("pm_format_version")),l.metadata.updated_at=P();let h=Ve(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=await to({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:d,after:h});await on({pm_root:e.pmRoot,operation:e.op,before:d,after:h,changed_fields:u.changedFields,author:e.author,sdk:yo({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let y=await pn({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),w="toon",E=ft(h,{format:w,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),I=ze(e.pmRoot,h.metadata.type,r.id,w,n),C=ee(e.pmRoot,r.id),M=await za(c,r,o,async()=>{let Z=await sn("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:C,item_format:w,before:d,after:h,contents:E}),{effectiveTargetItemPath:H,effectiveSerializedAfter:Kt,skipItemWrite:ot}=n_(Z,I,E),eu=await fo(e.pmRoot,e.author),Ri=[];try{ot||await T(H,Kt),!ot&&H!==r.itemPath&&await he.rm(r.itemPath);let nu=tn({nowIso:h.metadata.updated_at,author:e.author,op:e.op,before:d,after:h,message:e.message,context:ja({...f,...g.decisions.length===0?{}:{workflow_policies:g.decisions},...xr(e.pmRoot,[r.id,i.metadata.id],e.op)})});try{await nn(C,nu)}catch(ru){throw await o_({skipItemWrite:ot,effectiveTargetItemPath:H,originalItemPath:r.itemPath,originalRaw:o}),ru}ot||(Ri=await mo({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:H,previousItemPath:r.itemPath,document:h}))}finally{await eu()}let tu=ot||H!==I||Kt!==E;return{derivedIndexWarnings:Ri,effectiveTargetItemPath:H,overrideWarnings:Z.warnings,stored:tu?await Ua({pmRoot:e.pmRoot,settings:e.settings,id:r.id,typeToFolder:n,extensionFieldNames:e.extensionFieldNames,fallback:h,embeddedId:h.metadata.id}):{document:h}}}),{derivedIndexWarnings:R,effectiveTargetItemPath:D,stored:J}=M;Rr(e.pmRoot,J.document,r.id,[h.metadata.id],J.revision);let ae=[...await U({path:D,scope:"project",op:e.op,item_id:h.metadata.id,item_type:h.metadata.type,before:d,after:h,changed_fields:u.changedFields}),...await U({path:C,scope:"project",op:`${e.op}:history`,item_id:h.metadata.id,item_type:h.metadata.type,before:d,after:h,changed_fields:u.changedFields})];return rn({id:h.metadata.id,op:e.op,item_type:h.metadata.type,previous_status:d.metadata.status,status:h.metadata.status,previous:wt(d.metadata,u.changedFields),current:wt(h.metadata,u.changedFields),changed_fields:u.changedFields}),{item:h.metadata,body:h.body,changedFields:u.changedFields,warnings:[...s,...u.warnings??[],...g.warnings,...y.warnings,...M.overrideWarnings,...R,...ae]}}finally{await a()}}async function s_(e){let{historyContext:t,...n}=e;return ho({...n,resolveHistoryContext:()=>t})}async function DI(e){return ho(e)}async function a_(e){return ho(e)}async function c_(e){let t=await Fa({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{Cr(e.pmRoot,o,n.id);let c=_o(void 0),d=Ve(o,{schema:e.settings.schema,extensionFieldNames:c}),l=await to({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:d,after:null,dryRun:e.dryRun});await on({pm_root:e.pmRoot,operation:"delete",before:d,after:null,changed_fields:["deleted"],author:e.author,dry_run:e.dryRun===!0,sdk:yo({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let u=await pn({pmRoot:e.pmRoot,settings:e.settings,itemId:n.id,commandLabel:"delete"}),f=P(),_=pr,h=tn({nowIso:f,author:e.author,op:"delete",before:d,after:_,message:e.message,context:ja({...l.decisions.length===0?{}:{workflow_policies:l.decisions},...xr(e.pmRoot,[n.id,o.metadata.id],"delete")})}),g=ee(e.pmRoot,n.id),y=()=>r_({op:"delete",pm_root:e.pmRoot,item_id:n.id,item_path:n.itemPath,history_path:g,before:d});if(e.dryRun===!0){let R=await y();return{item:d.metadata,changedFields:["deleted"],targetPath:R.effectiveItemPath,warnings:[...i,...l.warnings,...u.warnings,...R.warnings]}}let w=await za(a,n,r,async()=>{let{effectiveItemPath:R,skipDelete:D,warnings:J}=await y(),ae=await fo(e.pmRoot,e.author),Z=[];try{D||await he.rm(R);try{await nn(g,h)}catch(H){throw D||await T(R,r),H}D||(Z=await mo({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:R,document:null}))}finally{await ae()}return{derivedIndexWarnings:Z,effectiveItemPath:R,overrideWarnings:J,stored:D||R!==n.itemPath?await Ua({pmRoot:e.pmRoot,settings:e.settings,id:n.id,typeToFolder:t.typeToFolder,fallback:_,embeddedId:o.metadata.id}):{document:_}}}),{derivedIndexWarnings:E,effectiveItemPath:I,stored:C}=w;Rr(e.pmRoot,C.document,n.id,[o.metadata.id],C.revision);let M=[...await U({path:I,scope:"project",op:"delete",item_id:d.metadata.id,item_type:d.metadata.type,before:d,after:_,changed_fields:["deleted"]}),...await U({path:g,scope:"project",op:"delete:history",item_id:d.metadata.id,item_type:d.metadata.type,before:d,after:_,changed_fields:["deleted"]})];return rn({id:d.metadata.id,op:"delete",item_type:d.metadata.type,previous_status:d.metadata.status,previous:wt(d.metadata,Object.keys(d.metadata)),changed_fields:["deleted"]}),{item:d.metadata,changedFields:["deleted"],warnings:[...i,...l.warnings,...u.warnings,...w.overrideWarnings,...E,...M]}}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 d_=3e4,Ft=class extends Error{status;constructor(t,n){super(t),this.name="SearchHttpError",this.status=n}};function Re(e,t,n=d_){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 xe(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 l_(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${S(t)})`}}async function kn(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 l_(r),i=o.length>0?`: ${o}`:"";throw new Ft(`${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 FI(e,t){let n=b(e);if(!n)return"unconfigured";let r=b(t);return r&&r.toLowerCase()===n.toLowerCase()?"configured":"auto-detected"}function u_(e){let t=lt(e),n=t.toLowerCase();return n.endsWith("/embeddings")?t:n.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function Ha(e){let t=e.search?.embedding_model;return b(t)||null}function f_(e){let t=b(e.providers?.openai?.base_url),n=b(e.providers?.openai?.model);if(!t||!n)return null;let r=Ha(e),o=b(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:r??n,...o?{api_key:o}:{}}}function m_(e){let t=b(e.providers?.ollama?.base_url),n=b(e.providers?.ollama?.model);if(!t||!n)return null;let r=Ha(e);return{name:"ollama",base_url:t,model:r??n}}function qa(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 __(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 Dn(e){let t=f_(e),n=m_(e),r=[t,n].filter(s=>s!==null),o=b(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 Va(e){let t=lt(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:u_(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function y_(e,t){let n=qa(t);return e.name==="openai"?{target:Va(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:Va(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:n}}}function h_(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 __(o).map((i,s)=>{let a=i.embedding;if(!Ue(a))throw new Error(`OpenAI embedding response entry at index ${s} is missing a numeric embedding vector`);return[...a]})}let n=t.embedding;if(Ue(n))return[[...n]];let r=t.embeddings;if(Array.isArray(r)&&r.length>0)return r.map((o,i)=>{if(!Ue(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 Ba(e,t,n={}){let r=Re(n.timeout_ms,"Embedding request"),o=xe(n.fetcher,"Embedding request"),i=qa(t),s=p_(i),a=y_(e,s.uniqueInputs),c=await kn({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:r,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),d=h_(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 Nn=["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 wo(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...Nn];let n=new Set(Nn),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:[...Nn]}var g_=8e3,w_=3200,Oe="...[semantic corpus truncated]",E_="search_embedding_corpus_max_characters_invalid:using_provider_default";function oe(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function b_(e){return(e.reminders??[]).map(t=>oe([t.at,t.text]))}function S_(e){return(e.events??[]).map(t=>oe([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 v_(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 T_(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 UI(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??[])v_(t,n);return T_(t,e),t.filter(n=>typeof n=="string"&&n.length>0).join(" ")}function I_(e){let t=(e.plan_steps??[]).map(i=>oe([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=>oe([s.kind,s.id,s.note])).join(" "),(i.files??[]).map(s=>oe([s.path,s.note])).join(" "),(i.tests??[]).map(s=>oe([s.command,s.path,s.note])).join(" "),(i.docs??[]).map(s=>oe([s.path,s.note])).join(" ")])),n=(e.plan_decisions??[]).map(i=>oe([i.decision,i.rationale,i.evidence,i.step_id])),r=(e.plan_discoveries??[]).map(i=>oe([i.text,i.step_id])),o=(e.plan_validation??[]).map(i=>oe([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 go(e){return(e??[]).flatMap(t=>Object.prototype.toString.call(t)==="[object Object]"&&typeof t.text=="string"?[t.text]:[])}function re(e){return typeof e=="string"&&e.trim().length>0}var A_={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=>re(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>re(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>re(e.metadata.goal)?e.metadata.goal:void 0,value:e=>re(e.metadata.value)?e.metadata.value:void 0,why_now:e=>re(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>re(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=>re(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>re(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>re(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>re(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>go(e.metadata.comments),notes:e=>go(e.metadata.notes),learnings:e=>go(e.metadata.learnings),reminders:e=>b_(e.metadata),events:e=>S_(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>I_(e.metadata)};function Wa(e,t={}){let n=t.fields??Nn,r={};for(let o of n){let i=A_[o];if(!i)continue;let s=i(e);s!==void 0&&(r[o]=s)}return r}function C_(e){return e?.trim().toLowerCase()==="ollama"?w_:g_}function Xe(e,t){let n=C_(e),r=Hi(t);return r!==null?{maxCharacters:r,warning:null}:{maxCharacters:n,warning:t==null?null:E_}}function Eo(e,t={}){let n=JSON.stringify(Wa(e,{fields:t.fields})),r=Xe(t.providerName,t.maxCharacters).maxCharacters;if(n.length<=r)return n;if(r<=Oe.length)return Oe.slice(0,r);let o=Math.max(0,r-Oe.length);return`${n.slice(0,o)}${Oe}`}(function(){try{var e=typeof window<"u"?window:typeof 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 R_(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 x_(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 O_(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let n=Math.max(0,t-Oe.length);return`${e.slice(0,n)}${Oe}`.slice(0,t)}function Ya(e){let t=S(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function k_(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 Ya(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 D_(e){return e instanceof Ft?e.status===413?"payload_too_large":null:Ya(e)?"timeout":null}async function bo(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 Ba(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=D_(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 bo(e,f,`${n}.1`,r,o,i,s),...await bo(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(k_(e,n,t.length,r,o+1,a))}async function So(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=Xe(e.name,t.search.embedding_corpus_max_characters);c.warning&&a.push(c.warning);let d=R_(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 y=O_(g,d.maxInputCharacters);return y.length<g.length&&(l+=1),y});l>0&&a.push(`search_embedding_input_truncated:count=${l}:max_characters=${d.maxInputCharacters}`);let f=x_(e,u,d.batchSize,d.maxRequestBytes);s.planned_batches=f.length;let _=[],h=0;for(let g=0;g<f.length;g+=1){let y=f[g];r.onProgress?.({batch_index:g+1,batch_total:f.length,batch_size:y.length,completed_inputs:h,total_inputs:u.length,phase:"start"}),_.push(...await bo(e,y,String(g+1),d.timeoutMs,d.maxRetries,a,s)),h+=y.length,r.onProgress?.({batch_index:g+1,batch_total:f.length,batch_size:y.length,completed_inputs:h,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 N_,readFile as L_,stat as Io,unlink as M_}from"node:fs/promises";import{basename as Ga,dirname as vo,isAbsolute as $_,join as P_,resolve as Ao}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 Co="pm_items",F_=/[^a-zA-Z0-9_-]/g,j_=128,z_=".pm-cli-local-vectors",To=1,ke=new Map;function zt(e){return(b(e.collection_name)??Co).replaceAll(F_,"_").slice(0,j_)}function Ln(e){if(!Ue(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function Xa(e){if(!Number.isFinite(e)||e<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(e)}function U_(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=b(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 Ro(e){let t=b(e.result?.status);if(t)return{status:t};let n=b(e.status);if(n)return{status:n};throw new Error("Qdrant upsert response must include status metadata")}async function jt(e,t,n,r,o){return await kn({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:n,fetcher:r,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function V_(e){let t=b(e.vector_store?.qdrant?.url);if(!t)return null;let n=b(e.vector_store?.collection_name),r=b(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...n&&n!==Co?{collection_name:n}:{},...r?{api_key:r}:{}}}function H_(e){let t=Ao(e),n=vo(t);return Ga(t)==="pm"&&Ga(n)===".agents"?vo(n):t}function q_(e,t){return!t||$_(e)?e:Ao(H_(t),e)}function B_(e,t){let n=b(e.vector_store?.lancedb?.path);if(!n)return null;let r=b(e.vector_store?.collection_name);return{name:"lancedb",path:q_(n,t),...r&&r!==Co?{collection_name:r}:{}}}function W_(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=b(t.id);if(!r)throw new Error(`Vector upsert record at index ${n} is missing a non-empty id`);let o=Ln(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 Y_(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=b(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 G_(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function K_(e){return e.replace(/\/points\?wait=true$/,"")}function Mn(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function $n(e,t){return Je(e,t)}function Je(e,t){return P_(Ao(e),z_,`${t}.json`)}function X_(e,t,n){let r=b(e.id);if(!r)throw new Error(`LanceDB local snapshot '${n}' record at index ${t} is missing a non-empty id`);let o=Ln(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 J_(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!==To)throw new Error(`LanceDB local snapshot at '${e}' must include version=${To}`);let o=b(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=X_(i[a],a,e);s.set(c.id,c)}return s}async function Z_(e){try{let t=await Io(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!$(t))throw t;return null}}function Q_(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 ke.set(e,{records:n,mtimeMs:null,size:null}),n}function ey(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function xo(e,t){let n=$n(e,t),r=Je(e,t),o=await Z_(r),i=ke.get(n);if(!o){let a=Q_(n,i);if(a)return a}if(ey(i,o))return i.records;let s=new Map;try{let a=await L_(r,"utf8");s=J_(r,t,a)}catch(a){if(!$(a))throw a}return ke.set(n,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function ty(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 Ja(e){try{await M_(e)}catch(t){if(!$(t))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${S(t)}`)}}async function Za(e,t,n){let r=Je(e,t);if(n.size===0){await Ja(r);return}let o=vo(r);try{await N_(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${S(s)}`)}let i=`${JSON.stringify({version:To,table:t,records:ty(n)})}
105
+ `;try{await T(r,i)}catch(s){throw new Error(`LanceDB local snapshot write failed at '${r}': ${S(s)}`)}}async function ny(e,t){let n=$n(e,t),r=Je(e,t);await Ja(r),ke.delete(n)}function Ka(e){let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.sqrt(t)}function ry(e,t){let n=0;for(let i=0;i<e.length;i+=1)n+=e[i]*t[i];let r=Ka(e),o=Ka(t);return r===0||o===0?0:n/(r*o)}function Pn(e,t){let n=V_(e),r=B_(e,t),o=[n,r].filter(a=>a!==null),i=b(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 Fn(e){let t=zt(e);if(e.name==="qdrant"){let o=lt(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 oy(e,t,n){let r=Fn(e),o=Ln(t),i=Xa(n);return e.name==="qdrant"?{target:r,method:"POST",headers:Mn(e),body:{vector:o,limit:i,with_payload:!0}}:{target:r,method:"LOCAL",headers:{},body:{table:zt(e),vector:o,limit:i}}}function iy(e,t){let n=Fn(e),r=W_(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Mn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:zt(e),records:r}}}function sy(e,t){let n=Fn(e),r=Y_(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Mn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:zt(e),ids:r}}}async function QI(e,t,n,r={}){let o=oy(e,t,n);if(o.method==="LOCAL"){let c=e,d=o.body,l=await xo(c.path,d.table);if(l.size===0)return[];let u=Ln(d.vector),f=Xa(d.limit),_=[],h=0;for(let g of l.values()){if(g.vector.length!==u.length){h++;continue}_.push({id:g.id,score:ry(u,g.vector),...g.payload?{payload:g.payload}:{}})}return h>0&&r.warnings&&r.warnings.push(`vector_dimension_mismatch:${h} records skipped (expected ${u.length} dimensions)`),_.sort((g,y)=>g.score!==y.score?y.score-g.score:g.id.localeCompare(y.id)),_.slice(0,f)}let i=Re(r.timeout_ms,"Vector request"),s=xe(r.fetcher,"Vector request"),a=await jt(o.target.query_target,{method:"POST",headers:o.headers,body:o.body},i,s,"query");return U_(a)}async function Oo(e,t,n={}){let r=iy(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=$n(a.path,c.table),l=await xo(a.path,c.table);for(let _ of c.records)l.set(_.id,_);await Za(a.path,c.table,l);let u=Je(a.path,c.table),f=await Io(u);return ke.set(d,{records:l,mtimeMs:f.mtimeMs,size:f.size}),{status:"ok"}}let o=Re(n.timeout_ms,"Vector request"),i=xe(n.fetcher,"Vector request"),s=await jt(r.target.upsert_target,{method:"POST",headers:r.headers,body:r.body},o,i,"upsert");return Ro(s)}async function jn(e,t,n={}){let r=sy(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=$n(a.path,c.table),l=await xo(a.path,c.table);if(l.size===0)return{status:"ok"};for(let u of c.ids)l.delete(u);if(await Za(a.path,c.table,l),l.size===0)ke.delete(d);else{let u=Je(a.path,c.table),f=await Io(u);ke.set(d,{records:l,mtimeMs:f.mtimeMs,size:f.size})}return{status:"ok"}}let o=Re(n.timeout_ms,"Vector request"),i=xe(n.fetcher,"Vector request"),s=await jt(G_(r.target.upsert_target),{method:"POST",headers:r.headers,body:r.body},o,i,"delete");return Ro(s)}async function Qa(e,t=[],n={},r){if(e.name==="lancedb")return await ny(e.path,zt(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=Fn(e),s=K_(i.upsert_target),a=Re(n.timeout_ms,"Vector request"),c=xe(n.fetcher,"Vector request"),d=Mn(e);try{await jt(s,{method:"DELETE",headers:d,body:{}},a,c,"delete")}catch(u){if(!S(u).includes("failed with status 404"))throw u}let l=await jt(s,{method:"PUT",headers:d,body:{vectors:{size:r,distance:"Cosine"}}},a,c,"upsert");return Ro(l)}let o=t.map(i=>i.trim()).filter(i=>i.length>0);return o.length===0?{status:"ok"}:await jn(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 zn(e,t){let n=b(e),r=b(t);return!n||!r?null:{provider:n,model:r}}function ec(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=zn(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 ko(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 Do(e,t){return!e||e.provider!==t.provider||e.model!==t.model}function No(e,t){return!!(e&&e.vector_dimension!==t)}function Lo(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 Mo 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 ay=["index/manifest.json","search/embeddings.jsonl"],nc="search/vectorization-status.json";function cy(e,t){return`search_cache_invalidation_failed:${e}:${String(t)}`}function Ze(e){return[...new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function rc(e){return typeof e=="string"&&e.trim().length>0&&Number.isFinite(Date.parse(e))}function oc(e){let t=new Map;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!rc(r)||t.set(o,r)}return Object.fromEntries([...t.entries()].sort((n,r)=>n[0].localeCompare(r[0])))}async function ic(e){let t=Mo.join(e,nc),n=await A(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||!rc(c))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};o.set(a.trim(),c)}let i=null;try{i=ec(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 sc(e,t,n){let r=oc(t),o=Mo.join(e,nc),i=`${JSON.stringify({version:1,generated_at:P(),...n?{embedding:n}:{},items:Object.entries(r).map(([s,a])=>({id:s,updated_at:a}))},null,2)}
106
+ `;await T(o,i)}function dy(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function ly(e){let t=zn(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function Ut(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function uy(e,t,n){if(!n.settings&&!await j(Ee(e)))return Ut(t,"search_semantic_refresh_skipped:settings_not_initialized");let r;try{if(n.settings)r=n.settings;else{let a=await He(e),c=a.warnings.find(d=>d.startsWith("settings_read_"));if(c)return Ut(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);r=a.settings}}catch(a){return Ut(t,`search_semantic_refresh_skipped:settings_read_failed:${S(a)}`)}let o=n.apply_runtime_defaults?We(r).settings:r,i=Dn(o).active;if(!i)return Ut(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=Pn(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:Ut(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function fy(e,t,n,r,o,i){let s=[],a=new Set,c=new Set,d=[];for(let l of r){let u=await Ke(e,l,t,n,o);if(!u){c.add(l);continue}try{let f=await Pt(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:Ze(c),skippedIds:Ze(a),warnings:s}}async function my(e,t,n){let r=Xe(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=wo(e),i=n.map(a=>Eo(a.document,{providerName:t.name,maxCharacters:r,fields:o})),s=await So(t,e,i);return{vectors:s.vectors,vector_dimension:Lo(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function py(e,t,n){return await Oo(e,t.map((r,o)=>({id:r.id,vector:n[o],payload:dy(r.document.metadata)}))),{refreshed:t.map(r=>r.id),skipped:[],warnings:[]}}async function _y(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await jn(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(n){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${S(n)}`]}}}async function yy(e){let t=[],n=[];for(let r of ay){let o=Mo.join(e,r);try{if(!await j(o))continue;await st(o),t.push(r)}catch(i){n.push(cy(r,i))}}return{invalidated:t,warnings:n}}async function tc(e,t,n={}){let r=Ze(t);if(r.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await uy(e,r,n);if(!("settings"in o))return o;let i=ct(o.settings,pe()),s=await fy(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 ic(e):{entries:{},embedding:null,warnings:[]},c=ly(o.provider),d=a.entries,l={refreshed:[],skipped:[],warnings:[]},u=a.embedding;if(s.documents.length>0)if(a.embedding&&Do(a.embedding,c))l={refreshed:[],skipped:s.documents.map(y=>y.id),warnings:["search_semantic_refresh_requires_reindex:embedding_identity_changed"]};else try{let y=await my(o.settings,o.provider,s.documents);if(No(a.embedding,y.vector_dimension))l={refreshed:[],skipped:s.documents.map(w=>w.id),warnings:[...y.warnings,"search_semantic_refresh_requires_reindex:vector_dimension_changed"]};else{u=ko(c,y.vector_dimension);let w=await py(o.vectorStore,s.documents,y.vectors);l={refreshed:w.refreshed,skipped:w.skipped,warnings:[...y.warnings,...w.warnings]}}}catch(y){l={refreshed:[],skipped:s.documents.map(w=>w.id),warnings:[`search_semantic_refresh_failed:${S(y)}`]}}let f=await _y(o.vectorStore,s.missingIds),_=new Set(l.refreshed),h=Object.fromEntries(s.documents.filter(y=>_.has(y.id)).map(y=>[y.id,y.document.metadata.updated_at])),g=[];if(Object.keys(h).length>0||s.missingIds.length>0){let y={...d,...oc(h)};for(let w of s.missingIds)delete y[w];try{await sc(e,y,u)}catch(w){g.push(`search_vectorization_status_ledger_write_failed:${S(w)}`)}g.push(...a.warnings)}return{refreshed:Ze([...l.refreshed,...f.refreshed]),skipped:Ze([...s.skippedIds,...l.skipped,...f.skipped]),warnings:[...s.warnings,...l.warnings,...f.warnings,...g]}}function hy(e,t){let n=t?We(e).settings:e;return!!(Dn(n).active&&Pn(n).active)}async function gy(e,t,n={}){let r=await yy(e),o=Ze(t);if(o.length===0)return{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:r.warnings};if(!await j(Ee(e))){let c=await tc(e,o);return{invalidated:r.invalidated,refreshed:c.refreshed,skipped:c.skipped,warnings:[...r.warnings,...c.warnings]}}let i;try{let c=await He(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&&hy(i,s))return await da(e,o),{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:[...r.warnings,"search_semantic_refresh_scheduled_background"],scheduled:!0};let a=await tc(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 wy}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]="1bd63c38-5dff-5f7d-b733-3be3fcc6605e")}catch{}})();var Ey=new Set(["1","true","yes","on"]),Un=["user","automation","test","dogfood"],ac=new Set(Un);function Qe(e={},t=process.env,n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let r=(t.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase(),o=$o(t);if(ac.has(r)&&(!o||r==="test"))return{source_context:r,source_context_source:"env_override"};let i=r&&!ac.has(r)?"env_override_rejected":"inferred";return o?{source_context:"test",source_context_source:i}:{source_context:!n||Vt("CI",t)||e.json===!0||e.quiet===!0?"automation":"user",source_context_source:i}}function cc(e=process.env){return typeof e.VITEST=="string"?"VITEST":typeof e.VITEST_WORKER_ID=="string"?"VITEST_WORKER_ID":typeof e.NODE_TEST_CONTEXT=="string"?"NODE_TEST_CONTEXT":(e.NODE_ENV??"").trim().toLowerCase()==="test"?"NODE_ENV":void 0}function $o(e=process.env){return cc(e)!==void 0}var Vn=new Set(["stats","ops stats","list","get","next","context","activity","aggregate"]);function dc(e,t,n=process.env){let r=n.PM_TELEMETRY_READ_SAMPLE_RATE?.trim();if(!r||!t||!Vn.has(e))return 1;let o=Number(r);return Number.isFinite(o)&&o>0&&o<=1?o:1}function Vt(e,t){return Ey.has((t[e]??"").trim().toLowerCase())}function z(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 Ht(e,t=z().endpoint){if(t===null)return e;let n=wy("sha256").update(t).digest("hex").slice(0,16);return e.replace(/\.(jsonl|json)$/u,`.${n}.$1`)}function by(e){return e.replaceAll(/(\/\/)[^/?#\s]*@/gu,"$1")}function Hn(e){let t=e.trim();if(!URL.canParse(t))return by(t).replace(/[?#].*$/su,"");let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}function qn(e){return e.replaceAll(/\b[a-z][a-z\d+.-]*:\/\/[^\s"'<>]+/giu,t=>Hn(t))}function bA(e,t=process.env){return z(t).endpoint??e}function Sy(e,t){return Vt("DO_NOT_TRACK",e)?"env:DO_NOT_TRACK":Vt("PM_TELEMETRY_DISABLED",e)?"env:PM_TELEMETRY_DISABLED":Vt("PM_NO_TELEMETRY",e)?"env:PM_NO_TELEMETRY":t?"env:PM_TELEMETRY_ENDPOINT":void 0}function G(e=process.env){let t=z(e),n=(e.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase(),r=cc(e),o=n==="test"?"env:PM_TELEMETRY_SOURCE_CONTEXT":Vt("PM_TELEMETRY_SEND_TEST_EVENTS",e)?"env:PM_TELEMETRY_SEND_TEST_EVENTS":void 0,i=r!==void 0&&o===void 0,s=Sy(e,t.invalid),a=r===void 0?void 0:o??`env:${r}`;return{telemetry_disabled:s!==void 0||i,do_not_track:s==="env:DO_NOT_TRACK",test_suppressed:i,endpoint_override:t.endpoint===null?null:Hn(t.endpoint),endpoint_override_invalid:t.invalid,decided_by:s??a??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]="a483f454-e261-5232-bae0-da3cdb8c0518")}catch{}})();var De=Object.freeze({max_bytes:4096,max_depth:8}),lc=160,vy=new Set(["not_plain_object","unsupported_value","non_finite_number","malformed_unicode","reserved_key","depth_limit","byte_limit","diagnostic_budget"]),fc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,Ty=new Set(["__proto__"]),L=class extends Error{reason;path;constructor(t,n){super(t),this.reason=t,this.path=n}};function Fo(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Iy(e,t){return/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function mc(e){if(Buffer.byteLength(e,"utf8")<=lc)return e;let t="",n=Buffer.byteLength("\u2026","utf8");for(let r of e){if(n+=Buffer.byteLength(r,"utf8"),n>lc)break;t+=r}return`${t}\u2026`}function Bn(e,t,n){if(e.bytes+=t,!(e.bytes<=De.max_bytes))throw new L("byte_limit",n)}function pc(e,t,n){if(e.bytes+t>De.max_bytes)throw new L("byte_limit",n)}function Po(e,t,n){let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||!("value"in r))throw new L("unsupported_value",n);return r.value}function Ay(e,t,n){if(typeof e=="number"&&!Number.isFinite(e))throw new L("non_finite_number",t);if(typeof e=="string"&&(pc(n,e.length+2,t),fc.test(e)))throw new L("malformed_unicode",t);if(e!==null&&!["boolean","number","string"].includes(typeof e))throw new L("unsupported_value",t);return Bn(n,Buffer.byteLength(JSON.stringify(e),"utf8"),t),e}function _c(e,t,n,r){if(typeof e!="object"||e===null)return Ay(e,t,r);if(n>=De.max_depth)throw new L("depth_limit",t);if(Array.isArray(e)){let o=Po(e,"length",t);if(typeof o!="number"||!Number.isSafeInteger(o)||o<0)throw new L("unsupported_value",t);Bn(r,o>0?o+1:2,t);let i=[];for(let s=0;s<o;s+=1){let a=`${t}[${s}]`;i.push(_c(Po(e,String(s),a),a,n+1,r))}return i}if(!Fo(e))throw new L("unsupported_value",t);return yc(e,t,n+1,r)}function yc(e,t,n,r){let o=Object.keys(e);Bn(r,o.length>0?o.length+1:2,t);let i={};for(let s of o){pc(r,s.length+3,t);let a=Iy(t,s);if(Ty.has(s))throw new L("reserved_key",a);if(fc.test(s))throw new L("malformed_unicode",a);Bn(r,Buffer.byteLength(JSON.stringify(s),"utf8")+1,a),i[s]=_c(Po(e,s,a),a,n,r)}return i}function Cy(e){try{if(e instanceof L)return e}catch{}return new L("unsupported_value","details")}function Yn(e){let t=De.max_bytes,n={bytes:0};try{if(!Fo(e))throw new L("not_plain_object","details");return{ok:!0,details:yc(e,"details",0,n),byte_length:n.bytes}}catch(r){let o=Cy(r);return{ok:!1,omission:o.reason==="byte_limit"?{reason:"byte_limit",byte_limit:t}:{reason:o.reason,path:mc(o.path),byte_limit:t}}}}function Ry(e){return Yn(e).ok}function hc(e){if(e===void 0)return;let t=Yn(e);return t.ok?{details:t.details}:{details_omitted:t.omission}}function Wn(){return{reason:"unsupported_value",path:"details",byte_limit:De.max_bytes}}function uc(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n?n.value:void 0}function xy(e){if(!Fo(e))return;let t=uc(e,"reason");if(typeof t!="string"||!vy.has(t))return;let n=uc(e,"path"),r=typeof n=="string"?mc(n):void 0;return{reason:t,...r===void 0?{}:{path:r},byte_limit:De.max_bytes}}function gc(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=Wn()));return t}catch{return{}}}function wc(e){if(!(typeof e!="object"||e===null))try{let t=Object.getOwnPropertyDescriptor(e,"details");if(t!==void 0&&!("value"in t))return{details_omitted:Wn()};if(t!==void 0&&t.value!==void 0)return hc(t.value);let n=Object.getOwnPropertyDescriptor(e,"details_omitted"),r=n!==void 0&&"value"in n?xy(n.value):void 0;return r===void 0?void 0:{details_omitted:r}}catch{return{details_omitted:Wn()}}}var Ec=new Set(["details","details_omitted"]);function Oy(e){let t={};for(let n of Object.keys(e)){if(Ec.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 ky(e){if(typeof e!="object"||e===null)return e;try{return Array.isArray(e)?e:{...Oy(e),...wc(e)}}catch{return{details_omitted:Wn()}}}function et(e){let t={};for(let[n,r]of Object.entries(gc(e)))Ec.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 Dy=12,Ny=new Set(["context","error_context"]),Ly=new Set(["arguments"]);function bc(e){let t=new WeakSet,n=(r,o)=>{if(typeof r!="object"||r===null||o>Dy||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=Ny.has(a)?{}:Ly.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 jo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function RA(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!jo(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return jo(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&jo(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 My="PmCliError";function xA(e){if(!qt(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 $y(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 Py(e){if(e==null)return{};if(!Object.hasOwn(e,"details"))return e;let t=Object.getOwnPropertyDescriptor(e,"details");if(!("value"in t))throw Sc("unsupported_value","details");if(t.value===void 0)return e;let n=Yn(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 Sc(n.omission.reason,n.omission.path)}function Sc(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 OA(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,$y(t.exitCode??m.USAGE),Py(t.context));return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function qt(e){try{if(!(e instanceof Error)||e.name!==My)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 Wy}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 Gn=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,Fy=new RegExp(`(?:\\b|(?<=_))(${Gn.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");function Kn(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 Tc(e,t){let n=/["']|u(?:0022|0027)/gi;n.lastIndex=t.end;for(let r of e.matchAll(n)){let o=Kn(e,r.index,r[0]);if(o?.identity===t.identity)return o.end}return e.length}function jy(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 zy(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=Kn(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=jy(n,i,i.end,e.length);if(a!==void 0)return a;continue}r.lastIndex=Tc(e,i)}return e.length}function Uy(e,t,n){let r=/^(\\*)(["'{[]|u(?:0022|0027|007b|005b))/i.exec(e.slice(t)),o=r?Kn(e,t+r[1].length,r[2]):void 0;return o?.character==="{"||o?.character==="["?zy(e,o):o?Tc(e,o):n}function Vy(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 vc="(?:\\s|\\\\+u(?:0009|000a|000d|0020))*",Hy=new RegExp("^"+vc+"(?::|=|\\\\+u(?:003a|003d))"+vc,"iu");function qy(e,t,n){let r=Vy(t);if(!Gn.test(r)&&!/\\u/iu.test(r))return;let o=e.slice(n),i=Hy.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 By(e){let t=new Map,n=[];for(let r of e.matchAll(/["']|u(?:0022|0027)/gi)){let o=Kn(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=qy(e,e.slice(i,o.index),s);a&&n.push(a)}return n}function Ic(e){let t=By(e);for(let o of e.matchAll(Fy)){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=Uy(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 Oc=new Set(["1","true","yes","on"]);function kc(){return!!(Oc.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||G().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}var Yy=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,Gy=/file:\/\/\/?[^\s"'`),;]+/giu,Ky=/\b[A-Za-z]:\\[^\s"'`),;]+/g,Xy=/\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,Jy=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i;var Zy=["[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 Ac(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 B(e,t){if(t&&Jy.test(t)&&Ac(e))return"[scrubbed_path]";let n=Ic(Zt(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(Xy,"[scrubbed_ip]").replaceAll(Gy,"[scrubbed_path]").replaceAll(Ky,"[scrubbed_path]").replaceAll(Yy,(r,o)=>`${o}[scrubbed_path]`);return Ac(n)?"[scrubbed_path]":n}function K(e){let t={};for(let[n,r]of Object.entries(e))Gn.test(n)||n.startsWith("sentry.message.parameter.")?t[n]="[scrubbed]":typeof r=="string"?t[n]=B(r,n):Array.isArray(r)?t[n]=r.map(o=>typeof o=="string"?B(o,n):o&&typeof o=="object"?K(o):o):r&&typeof r=="object"?t[n]=K(r):t[n]=r;return t}function Qy(e){for(let n of["filename","absPath","abs_path","module"]){let r=e[n];typeof r=="string"&&(e[n]=B(r,n))}let t=e.context_line;typeof t=="string"&&(e.context_line=B(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"?B(o,n):o))}e.vars&&typeof e.vars=="object"&&(e.vars=K(e.vars)),e.data&&typeof e.data=="object"&&(e.data=K(e.data))}var eh=Wy(import.meta.url),th=()=>eh("@sentry/node"),Xn,Cc=!1,nh=th,rh="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function zo(e){return/^\s*PmCliError:/.test(e)}function Uo(e){let t=e.trim().toLowerCase();return t.length===0?!1:Zy.some(n=>t.includes(n))}function oh(e){return e.logger!=="console"?!1:typeof e.message=="string"&&Uo(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(t=>typeof t.value=="string"&&Uo(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?qt(t):!!(e.exception?.values?.some(n=>n.type==="PmCliError")||e.exception?.values?.some(n=>typeof n.value=="string"&&zo(n.value))||e.logger==="console"&&typeof e.message=="string"&&zo(e.message))}function Dc(e){return e.category==="console"&&typeof e.message=="string"&&zo(e.message)}function Nc(e){return e.category==="console"&&typeof e.message=="string"&&Uo(e.message)}function ah(){return Or(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=Qe().source_context;return t==="user"?"production":t}var Rc=.2;function Lc(){let e=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!e)return Rc;let t=Number(e);return!Number.isFinite(t)||t<0||t>1?Rc:t}function dh(e){if(e.exception?.values){for(let t of e.exception.values)if(t.value&&(t.value=B(t.value,"value")),t.stacktrace?.frames)for(let n of t.stacktrace.frames)Qy(n)}}function Mc(e){if(e.breadcrumbs)for(let t of e.breadcrumbs)t.message&&(t.message=B(t.message)),t.data&&typeof t.data=="object"&&(t.data=K(t.data))}function $c(e){if(e.contexts)for(let[t,n]of Object.entries(e.contexts))n&&typeof n=="object"&&(e.contexts[t]=K(n))}function xc(e,t){let n=e,r=n[t];r&&typeof r=="object"&&(n[t]=K(r))}function Vo(e){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(e==="automation"||e==="test"||e==="dogfood"||e==="user"))return e==="user"?"production":e}function Pc(e){let t=Vo(e.tags?.["pm.source_context"]);t&&(e.environment=t)}function Fc(e,t){let n=lh(e.extra);bc([e.contexts,e.extra,e.breadcrumbs]),uh(e.contexts,t),n!==void 0&&(e.extra.error_context=et(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(fh(t)),o=mh(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 fh(e){try{return[e.name,e.constructor?.name].filter(t=>typeof t=="string"&&t.length>0)}catch{return[]}}function mh(e){try{let t=et(e),n=Object.getOwnPropertyDescriptor(e,"context");return n!==void 0&&"value"in n&&(t.context=et(n.value)),t}catch{return}}var ph=(e,t)=>{if(sh(e,t?.originalException)||oh(e))return null;Fc(e,t?.originalException),Pc(e),ih(e)&&(e.level="warning",e.tags={...e.tags,"pm.diagnostic_class":"node_runtime_warning"}),e.message&&(e.message=B(e.message,"message")),e.transaction&&(e.transaction=B(e.transaction,"transaction")),dh(e),Mc(e),xc(e,"extra"),$c(e);for(let n of["request","user","tags"])xc(e,n);return e},_h=e=>(Fc(e),Pc(e),e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(t=>!Dc(t)&&!Nc(t)),Mc(e)),$c(e),e),yh=e=>K(e),hh=e=>{if(e.message=B(e.message),e.attributes){let t=Vo(e.attributes["pm.source_context"]);t&&(e.attributes["sentry.environment"]=t),e.attributes=K(e.attributes)}return e};function gh(e){let t=Vo(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=B(n.body);let r=n.attributes;if(r){gh(r);for(let[o,i]of Object.entries(r)){let s=K({[o]:i.value})[o];typeof s=="string"&&(r[o]={type:"string",value:s})}}}}var Eh=e=>Dc(e)||Nc(e)?null:(e.message&&(e.message=B(e.message,"message")),e.data&&typeof e.data=="object"&&(e.data=K(e.data)),e);async function jc(){if(Cc)return Xn;if(Cc=!0,kc())return;let e=nh(),t=process.env.SENTRY_DSN?.trim()||rh,n=ah();e.init({dsn:t,release:`pm-cli@${n}`,environment:ch(),tracesSampleRate:Lc(),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(yh),beforeSendLog:hh,beforeBreadcrumb:Eh});let r=e.getClient();if(!r)return;let o=Qe();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),Xn=e,e}async function bh(e){if(e!==!0||!Oc.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||Lc()===0||kc())return!1;try{return await jc()!==void 0}catch{return Xn=void 0,!1}}function Ne(){return Xn}(function(){try{var e=typeof window<"u"?window:typeof 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 Bt=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 HA(e,t){let n=t.warnings[0]??"extension_command_handler_failed",r=t.errorMessage?.trim();return new Bt(`Command "${e}" failed in extension handler (${n}).${r?` ${r}`:""}`,{code:t.errorCode??"command_failed",nextSteps:t.remediation?[t.remediation]:void 0},t.cause)}function qA(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 BA(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function WA(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"]),Ah=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"]),Ch=new Set(["test","test-all","test-runs","test-verify","trace-test","test-ping"]),Rh=new Set(["health","validate","normalize","reindex","gc","telemetry","extension-doctor"]);function xh(e){return e.trim().replaceAll(/\s+/g," ").toLowerCase()}function zc(e){let t=e?.trim().toLowerCase();return t&&t.length>0?t:void 0}var Oh=[{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")}],kh=new Map([[m.USAGE,"invalid_command_usage"],[m.NOT_FOUND,"item_not_found"],[m.CONFLICT,"lock_conflict"],[m.DEPENDENCY_FAILED,"dependency_failed"]]);function Le(e){let t=xh(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":Ah.has(r)?i="mutation":Ch.has(r)?i="testing":r==="extension"?i="extension":Rh.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 Ho(e){if(e.ok)return;let t=zc(e.errorCode);if(t)return t;let n=(e.errorMessage??"").trim().toLowerCase();for(let o of Oh)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?kh.get(r)??"command_failed":"command_failed"}function tt(e){if(e.ok)return"success";let t=zc(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 Me;function ge(e,t,n){if(n===void 0)return;let r=e;typeof r.setAttribute=="function"&&r.setAttribute(t,n)}function nt(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))),nt(e,"pm.error_code",n?.error_code),nt(e,"pm.error_category",n?.error_category),nt(e,"pm.command_resolution",n?.command_resolution),nt(e,"pm.resolution_stage",n?.resolution_stage)}function Nh(e,t,n,r){ge(e,"pm.ok",t),ge(e,"pm.command_ok",t),ge(e,"pm.exit_code",n),ge(e,"pm.command_exit_code",n),ge(e,"pm.error_code",r?.error_code),ge(e,"pm.error_category",r?.error_category),ge(e,"pm.command_resolution",r?.command_resolution),ge(e,"pm.resolution_stage",r?.resolution_stage)}function Lh(e,t,n,r){let o=Ne();if(!o)return;let i=Le(e);o.setTag("pm.command",e),o.setTag("pm.command_root",i.command_root),o.setTag("pm.command_family",i.command_family),nt(o,"pm.version",r?.pm_version),nt(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 Mh(e){let t=Ne();if(!t)return;let n=Le(e);Me=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 $h(){Me=void 0}function Ph(e,t,n){if(!Me)return;let r=e?"true":"false",o=typeof n?.exit_code=="number"?String(n.exit_code):void 0,i=Ne();i&&Dh(i,r,n),Nh(Me,r,o,n),Me.setStatus(e?{code:1}:{code:2,message:t??"command_failed"}),Me.end(),Me=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 zh(e){let t=jh(e);return{"pm.error_code":t.error_code,"pm.exit_code":String(t.exit_code)}}function Uh(e){if(!Hh(e))return;let t=Ne();if(!t)return;let n=zh(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=et(e.context)),t.captureException(e,{extra:r,tags:n})}else t.captureException(new Error(String(e)),{tags:n})}function Vh(e){let t=Ne();if(!t)return;let n=e.command_resolution??tt({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 Bt)return!0;if(e instanceof p||qt(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=Ne();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]="a5619fc7-2547-59c9-bfff-4d4cebd14967")}catch{}})();var Pe=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,x="[/\\\\]+",Bh="[\\p{L}\\p{N}._@-]+",Fe=Bh+"(?:"+x+Pe+")*",Jn="(?:(?:home|users)"+x+Fe+"|root"+x+Fe+")",Wh="[/\\\\]"+Jn,Yh="[/\\\\]{2,}"+Jn,Gh="/?[a-z]:"+x+"users"+x+Fe,Kh=Pe+"(?: +"+Pe+")*",Go="(?:"+Kh+x+")?users"+x+Fe,Xh="[/\\\\]{2,}"+Pe+x+Go,Jh="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+Pe+")",rd="[/\\\\]{2}[?.]"+x+"(?:unc"+x+Pe+x+Go+"|"+Jh+x+"users"+x+Fe+")",Zh="file:(?:"+rd+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+x+")(?:"+Jn+"|[a-z]:"+x+"users"+x+Fe+")|[/\\\\]{2}(?:[a-z]:"+x+"users"+x+Fe+"|"+Pe+x+"(?:"+Jn+"|"+Go+")))",Qh=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+Wh+"|"+Gh+"|"+Zh+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+Yh+"|"+Xh+"|"+rd+")","giu"),Uc=4,eg=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,tg=new TextDecoder("utf-8");function ng(e){return e.replace(/(?:%[a-f0-9]{2})+/giu,t=>tg.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 rg(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 og(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 ig(e,t){for(let[n,r]of[["percent_decode",ng],["json_unescape",rg],["unicode_fold",og]]){let o=r(e);o!==e&&!t.includes(n)&&t.push(n),e=o}return e}function*sg(e,t,n){let r=e,o=[];for(let i=0;i<Uc;i+=1){let s=r;if(r=ig(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===Uc-1&&eg.test(r)&&(yield{index:0,normalizations:[...o],normalization_incomplete:!0})}}function*ag(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 sg(r,t,o))yield{...i,index:n};n+=r.length+1}}var Vc="password|passphrase",Zn=4,ie=4096,rt=e=>`${e}+(?!${e})`,Hc=String.raw`'[^'\r\n]*'|"[^"\\\r\n]*(?:\\.[^"\\\r\n]*){0,${ie}}"`,cg=String.raw`\$\{(?:${rt(String.raw`[^{}$'"\\\r\n]`)}|\\[^\r\n]|${Hc}|\$(?!\{)|\$\{[^{}\r\n]*\}){0,${ie}}\}`+String.raw`|\$\((?:${rt(String.raw`[^()$'"\\\r\n]`)}|\\[^\r\n]|${Hc}|\$(?!\()|\$\([^()\r\n]*\)){0,${ie}}\)`,od=String.raw`${cg}|<[^<>\r\n]*>|${rt(String.raw`[A-Za-z0-9!@#%^&*._+\-=]`)}|\$(?![{(])`,dg=String.raw`"[^"]*"|'[^']*'`,qc=String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${od}){0,${ie}}`,Bc=new RegExp(String.raw`(?!config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))`+`((?:${od}){1,${ie}}(?:${qc}){0,${Zn}}|(?:${qc}){1,${Zn}}|${dg})`),lg=8,Wc="token|secret|password|passwd|api[_-]?key",qo="(?<![a-z0-9_]|[a-z0-9_]-)(?:(?:[a-z0-9]+_)+(?:password|passphrase)|(?:[a-z0-9]+[_-])*(?:secret|token|(?:api|secret|private|access)[_-]?key|client[_-]?secret|passwd|pwd))",ue=4096,id=String.raw`"(?=[^"\s]{8}[^"\s]*")|'(?=[^'\s]{8}[^'\s]*')|(?!["'])`,sd=String.raw`(?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.){1,${ue}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${ue}}|(?:[\w.-]+\/){1,${ue}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.){1,${ue}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${ue}}|(?:[\w.-]+\/){1,${ue}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+){0,${ue}}(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.){1,${ue}}[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/){1,${ue}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}(?=[\s,;)}\]]|$)|(?<!["'])[\w$.]+\()(?:(?<=")[^\s"]{8}[^\s"]*|(?<=')[^\s']{8}[^\s']*|(?<==)[A-Za-z0-9!@#$%^&*._+\-=/~?:|]{8,}|(?<!["'=])[A-Za-z0-9!@#$%^&*._+\-=/~]{8,})`,Bo=new RegExp(`(?:${id})(${sd})`,"iy"),ug=8,fg=String.raw`[A-Za-z0-9!@#%^*._+\-=/~]`,ad=String.raw`&(?!&)`,mg=64,Yc=String.raw`'[^'\s]*'|"[^"\\\s]*(?:\\\S[^"\\\s]*){0,${ie}}"`,cd=String.raw`\$\{(?:${rt(String.raw`[^{}$'"\\\s]`)}|\\\S|${Yc}|\$(?!\{)|\$\{[^{}\s]*\}){0,${ie}}\}`+String.raw`|\$\((?:${rt(String.raw`[^()$'"\\\s]`)}|\\\S|${Yc}|\$(?!\()|\$\([^()\s]*\)){0,${ie}}\)`+String.raw`|<[^<>\s]*>|\$[A-Za-z_]\w*(?!\w)`,dd=e=>String.raw`${cd}|${rt(e)}|${ad}|\$(?![{(A-Za-z_])`,ld=e=>String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${dd(e)}){0,${ie}}`,pg=e=>String.raw`(?:(?:${e}|${ad}){1,${mg}}(?=[$<]))?(?:${cd})`+String.raw`(?:${dd(e)}){0,${ie}}(?:${ld(e)}){0,${Zn}}`,_g=e=>String.raw`(?:${ld(e)}){1,${Zn}}`,Gc=e=>String.raw`(?<!["'])(?:${e(fg)})`,Kc=String.raw`(?:[\w@#~]|!(?![.+\-*/%=^!(]))`,yg=String.raw`(?=(?:"[^"\s]*"|'[^'\s]*')[$<"']`+String.raw`|"(?=[^"\s]*[$<])[^"\s]*"${Kc}|'(?=[^'\s]*[$<])[^'\s]*'${Kc})`,hg=String.raw`(?<=")(?=[^"\s]*[$<])[^"\s]+|(?<=')(?=[^'\s]*[$<])[^'\s]+`,Xc=new RegExp(`(?:${yg}|${id})((?=["'])(?:${Gc(_g)})|${hg}|${Gc(pg)}|${sd})`),Jc=/["']?([A-Za-z0-9+/=_-]{24,})/,er=[{name:"private-key",mutationRule:"private_key",category:"credential",regex:/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/g},{name:"github-token",mutationRule:"github_token",category:"credential",regex:/\b(?:gh[opsru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g},{name:"npm-token",mutationRule:"npm_token",category:"credential",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g},{name:"aws-access-key",mutationRule:"aws_access_key",category:"credential",regex:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g},{name:"google-api-key",mutationRule:"google_api_key",category:"credential",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"slack-token",mutationRule:"slack_token",category:"credential",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"anthropic-api-key",mutationRule:"anthropic_api_key",category:"credential",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"openai-api-key",mutationRule:"openai_api_key",category:"credential",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"gitlab-token",mutationRule:"gitlab_token",category:"credential",regex:/\bglpat-[A-Za-z0-9_.-]{20,}\b/g},{name:"jwt-like-token",mutationRule:"jwt_like_token",category:"credential",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",category:"credential",regex:/_authToken\s*=\s*\S+/g},{name:"sentry-user-token",mutationRule:"sentry_user_token",category:"credential",regex:/\bsntryu_[A-Za-z0-9]{20,}\b/g},{name:"sentry-org-token",mutationRule:"sentry_org_token",category:"credential",regex:/\bsntrys_[A-Za-z0-9_-]{20,}\b/g},{name:"private-ip",mutationRule:"private_ip",category:"network",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",category:"network",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",category:"credential",regex:/\bsshpass\s+-p\s+["'][^"']{6,}["']/g},{name:"password-assignment",mutationRule:"password_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${Vc})\s*[:=]\s*`+Bc.source,"gi"),structured:{keys:Vc,value:Bc.source,element:!0},minimumLiteralLength:lg},{name:"absolute-home-path",mutationRule:"absolute_home_path",category:"path",regex:Qh,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",category:"network",regex:/(?<![A-Za-z0-9._-])[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",category:"credential",regex:new RegExp(String.raw`\b(?:${Wc})\s*[:=]\s*`+Jc.source,"gi"),structured:{keys:Wc,value:Jc.source},mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.",minimumEntropy:3.5},{name:"credential-key-assignment",mutationRule:"credential_key_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${qo})\s*[:=]\s*`+Xc.source,"gi"),structured:{keys:qo,value:Xc.source,element:!0,elementValue:!0},mutationOnlyReason:"Key-named assignments in source code and test fixtures are identifiers and synthetic data; repository scans keep the token-format rules, which recognize real credentials there.",minimumEntropy:3,minimumLiteralLength:ug,literalValue:Bo,baseline:{regex:new RegExp(String.raw`\b(?:${qo})\s*[:=]\s*`+Bo.source,"gi"),value:Bo.source},rejectValue:/^(?:[\w.-]+\/)*id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(?:\.pub)?$/u,rejectStatementReference:/^[A-Z]+(?:_[A-Z]+)+$/u}];function*ud(e,t){if(e.mutationRule==="absolute_home_path"){yield*ag(t,e.regex);return}for(let n of fd(e))yield*Tg(n,t),n.structured&&(yield*dw(n,n.structured,t))}var Zc=new WeakMap;function fd(e){let t=e.baseline;if(t===void 0)return[e];let n=Zc.get(e);return n===void 0&&(n={...e,regex:t.regex,minimumLiteralLength:void 0,literalValue:void 0,baseline:void 0},e.structured&&(n.structured={...e.structured,value:t.value}),Zc.set(e,n)),[e,n]}function gg(e,t){let n=e[t-1]==="#"||e[t-1]==="!"?t-1:t;return e[n-1]==="{"&&e[n-2]==="$"}var Ko=new WeakSet,md=new WeakMap,wg=4096;function Eg(e,t,n){let r=[],o=[],i=t+n.length;return Qc(e,t,i,o,r),Qc(e,i,Math.min(e.length,i+wg),o),r}function Qc(e,t,n,r,o){for(let i=t;i<n&&(o!==void 0||r.length>0);i+=1){let s=r.at(-1);if(e[i]==="$"&&(e[i+1]==="{"||e[i+1]==="(")&&s?.quoted!=="'"){let a={open:i,close:n,command:e[i+1]==="(",quoted:[]};o?.push(a),r.push({span:a,closer:e[i+1]==="{"?"}":")"}),i+=1}else s!==void 0&&(i=bg(e,i,r))}}function bg(e,t,n){let r=n.at(-1),o=e[t];return o==="\\"&&r.quoted!=="'"?t+1:(r.quoted!==void 0?o===r.quoted&&(r.span.quoted.push([r.quoteStart,t]),r.quoted=void 0):o==="'"||o==='"'?(r.quoted=o,r.quoteStart=t):o===r.closer&&(n.pop().span.close=t),t)}function Sg(e){let t=[],n=0;return r=>{for(;n<e.length&&e[n].open<r;n+=1){for(;t.length>0&&t.at(-1).close<e[n].open;)t.pop();t.push(e[n])}for(;t.length>0&&t.at(-1).close<r;)t.pop();return t.at(-1)}}function vg(e,t){let n=0,r=e.quoted.length-1;for(;n<=r;){let o=n+r>>1,[i,s]=e.quoted[o];if(t<i)r=o-1;else if(t>s)n=o+1;else return!0}return!1}var pd=/\$[({A-Za-z_]|</u;function*Tg(e,t){let n=e.regex;n.lastIndex=0;let r=Ig(e),o;for(let i of t.matchAll(n))tr(e,i)?yield{index:i.index}:r!==void 0&&pd.test(i[1])&&(o??=new RegExp(n),yield*Ag(e,o,t,i,r==="deep"))}function Ig(e){return e.minimumLiteralLength===void 0?void 0:e.minimumEntropy===void 0&&e.literalValue===void 0&&e.rejectValue===void 0?"deep":"shallow"}function*Ag(e,t,n,r,o){let i=r.index+r[0].length;t.lastIndex=i-r[1].length;let s;for(let a=t.exec(n);a!==null&&a.index<i;a=t.exec(n)){if(gg(n,a.index)){t.lastIndex=a.index+1;continue}s??=Sg(Eg(n,i-r[1].length,r[1]));let c=s(a.index);c!==void 0&&(md.set(a,c.close),c.command&&!vg(c,a.index)&&Ko.add(a)),tr(e,a)?yield{index:a.index}:o&&pd.test(a[1])&&(t.lastIndex=a.index+a[0].length-a[1].length)}}var ed=new Map,td=/[\r\n\u2028\u2029]/u;function Xo(e){let t=`${e.keys}\0${e.value}\0${e.element===!0}`,n=ed.get(t);return n||(n={key:new RegExp(String.raw`\b(?:${e.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(e.value,"iyd"),...e.element?{element:{open:new RegExp(String.raw`<(?:${e.keys})(?:\s[^<>]*)?>`,"gi"),close:new RegExp(String.raw`<\/(?:${e.keys})\s*>`,"iy"),span:new RegExp(String.raw`<(?!\/?(?:${e.keys})\b)[^<>]*>`,"iy")}}:{}},ed.set(t,n)),n}function _d(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 Cg(e,t){return _d(e,t).end}function Rg(e,t,n){return e.at(-1)==="}"?n:t}function xg(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&&Rg(o,n,r)(s))return{found:!0,end:s};s=Cg(e,s)-1;break;default:break}}return{found:!1,end:e.length}}var Og=/\\(?: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,kg={n:`
108
+ `,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function Dg(e,t){let n=e[0],r=e.slice(1,t?-1:void 0).replaceAll(Og,s=>{let a=s[1];if((a==="u"||a==="x")&&s.length>2)return String.fromCharCode(Number.parseInt(s.slice(2),16));if(/^[0-7]$/u.test(a))return String.fromCharCode(Number.parseInt(s.slice(1),8));if(a==="U"&&s.length===10){let c=Number.parseInt(s.slice(2),16);return c<=1114111?String.fromCodePoint(c):"\uFFFD"}return kg[a]??a}),o=r.replaceAll(n,n==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," "),i=t?n:"";return{reading:`${n}${o}${i}`,...yd(`${n}${r}${i}`,t)}}function yd(e,t){return{original:e,bodyStart:1,bodyEnd:e.length-(t?1:0)}}var Ng=64;function hd(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-Ng);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 gd(e,t,n,r=!1){let o=(a,c,d)=>{t.lastIndex=c;let l=t.exec(a);if(l===null||td.test(l[0]))return null;let u=l.indices?.[1];return d!==void 0&&u!==void 0&&(l[1]=d.original.slice(Math.max(u[0],d.bodyStart),Math.min(u[1],d.bodyEnd)),Jo.add(l)),tr(e,l)?l:null},i=a=>{if(n[a]!=='"'&&n[a]!=="'")return;let{end:c,terminated:d}=_d(n,a),l=n.slice(a,c);if(!r&&!l.includes("\\"))return;if(td.test(l))return[];let u=Dg(l,d);return(n[a]==="'"?[u,{reading:l,...yd(l,d)}]:[u]).map(f=>o(f.reading,0,f)).filter(f=>f!==null)},s=a=>{let c=i(a);if(c!==void 0)return c;let d=o(n,a);return d===null?[]:[d]};return{direct:a=>o(n,a)!==null,escaped:a=>(i(a)?.length??0)>0,accepts:a=>c=>s(c).some(d=>!(a&&/\s/u.test(Lg(e,d))))}}function Lg(e,t){return e.minimumLiteralLength===void 0?t[0]:wd(t)}var Jo=new WeakSet;function wd(e){let t=Ko.has(e)&&!$e(Wt(e))?Mg(e[1]):void 0,n=t??e[1],r=t!==void 0||Pg(e);return Jo.has(e)||$e(Wt(e))?Td(n,r):xw(n,r)}function Mg(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="'"||n==='"')t=Ed(e,t);else if(n==="$"&&(e[t+1]==="{"||e[t+1]==="("))t=Math.max(t,Wo(e,t)-1);else if(/[|&;<>]/u.test(n))return e.slice(0,t)}}var $g=/^[;,)}\]]{0,64}/u;function Pg(e){let t=e.input,n=e.index+e[0].length,r=$e(Wt(e))&&$e(t[n])?n+1:$e(e[0].at(-1))?n:-1,o=r===-1?n:r,i=$g.exec(t.slice(o,o+qg))[0].length,s=o+i;if(s===t.length||/\s/u.test(t[s])||md.get(e)===o||Ko.has(e)&&/[|&;<>]/u.test(t[o]))return!0;if(r===-1||i===0)return!1;let a=Fg(e,r===n+1),c=t.slice(s,s+40),d=/[}\]]/u.test(t.slice(o,s));return a!==void 0&&(Vg.test(c)||(a==="element"||d)&&Hg.test(c))}function Fg(e,t){let n=e.input,r=e.index+e[0].length-e[1].length-(t?1:0),o=n.slice(Math.max(0,r-jg),r);return Ug.test(o)?"element":zg.test(o)?"key":void 0}var jg=512,zg=/[{,]\s*(["'])[^"'\r\n]{1,256}\1\s*[:=]\s*$/u,Ug=/[[,]\s*$/u,Vg=/^(?:["'`]|[{[](?:[\s"'`{[\]}]|$|(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]))/u,Hg=/^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]/u,qg=64,Bg=/^\s{0,16}\(/u,Wg=/(?<![=!<>])=[ \t]{0,16}$/u;function Wt(e){return e.input[e.index+e[0].length-e[1].length-1]}function $e(e){return e==='"'||e==="'"}var Yg=/[$<"']/u;function Gg(e){if(Jo.has(e)||$e(Wt(e))||!/^[$<]/u.test(e[1]))return!1;let t=e.index+e[0].length,n=t-e[1].length,r=e.input.slice(t,t+18);if(e[1][0]==="<"&&(tw(e[1])||Wg.test(e.input.slice(Math.max(0,n-18),n))||rw.test(r)))return!0;let o=Kg(e[1]),i=e[1][o]==="!"?e[1][o+1]:e[1][o];return nw.test(i??"")||Bg.test(r)}function Kg(e){let t=0;for(let n=Wo(e,t);n!==-1;n=Wo(e,t))t=n;return t}function Wo(e,t){let n=e[t];if(n==="<")return Xg(e,t);if(n!=="$")return-1;let r=e[t+1];if(r==="{"||r==="(")return Jg(e,t+1,r);Qn.lastIndex=t;let o=Qn.exec(e)?.[0];return o===void 0?-1:t+o.length}function Xg(e,t){let n=e.indexOf(">",t+1),r=e.indexOf("<",t+1);return n!==-1&&(r===-1||n<r)?n+1:-1}function Jg(e,t,n){let r=n==="{"?"}":")",o=0;for(let i=t;i<e.length;i+=1){let s=e[i];if(s==="\\")i+=1;else if(s==="'"||s==='"')i=Ed(e,i);else if(s===n)o+=1;else if(s===r&&--o===0)return i+1}return-1}function Ed(e,t){let n=e[t];for(let r=t+1;r<e.length;r+=1){if(e[r]===n)return r;n==='"'&&e[r]==="\\"&&(r+=1)}return e.length}var Zg=/^[\w$.[\]|&,{}:;?]+$/u,Qg=/^(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?)(?:\|(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?|[A-Za-z_$][\w$.]*))*$/u,ew=/\b(?:string|number|boolean|bigint|symbol|any|unknown|object|never|void|undefined|null)\b/u;function tw(e){let t=e.slice(1,e.indexOf(">"));return Qg.test(t)?!0:Zg.test(t)?ew.test(t)||/[.|&[{]/u.test(t)||/^[A-Z][\w$]*$/u.test(t)&&(t.length===1||/[a-z]/u.test(t)):!1}var nw=/[.+\-*/%=^&]/u,rw=/^\s{0,16}(?:\?\.|\?\?|\|\||&&|[([])/u;function ow(e,t,n){if(n)return!1;let r=t.replaceAll('"',"'");return e.lastIndex=0,e.exec(`"${r}"`)?.[1]===r}function bd(e,t){if(!e.structured)return;let n=`${JSON.stringify(t)}:`,r=Xo(e.structured).key;r.lastIndex=0;for(let o=r.exec(n);o;o=r.exec(n)){if(o.index+o[0].length!==n.length)continue;let i=hd(n,o.index,o[1]);if(i!=="malformed")return i}}function Sd(e,t,n){if(!e.structured)return!1;let r=JSON.stringify(t).replaceAll("\u2028","\\u2028").replaceAll("\u2029","\\u2029");return fd(e).some(o=>gd(o,Xo(o.structured).value,r,!0).accepts(n)(0))}function*iw(e,t,n){let r=new RegExp(e.open);for(let o=r.exec(t);o;o=r.exec(t)){let i=o.index+o[0].length,s=sw(e,t,i);if(s===void 0){r.lastIndex=o.index+1;continue}n(t.slice(i,s.start).trim())&&(yield{index:o.index}),r.lastIndex=s.end}}function sw(e,t,n){for(let r=t.indexOf("<",n);r!==-1;){e.close.lastIndex=r;let o=e.close.exec(t);if(o!==null)return{start:r,end:r+o[0].length};e.span.lastIndex=r;let i=e.span.exec(t);if(i===null)return;r=t.indexOf("<",r+i[0].length)}}function aw(e,t,n){return t<e.exact||n&&t<e.compact}function cw(e,t,n,r){return(n||e.escaped(r)&&!e.direct(r))&&t(r)}function*dw(e,t,n){let r=Xo(t),o=gd(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=hd(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(aw(s,f,l))continue;let h=xg(n,f,u,o.accepts(!0));s[l?"compact":"exact"]=h.end,h.found&&(yield{index:a.index})}else cw(o,u,c,f)&&(yield{index:a.index})}r.element&&(yield*iw(r.element,n,uw(e,t,r)))}var lw=8;function uw(e,t,n){if(!t.elementValue){let r=e.minimumLiteralLength??lw;return o=>Td(o).length>=r}return r=>{let o=r.replaceAll('"',"'");n.value.lastIndex=0;let i=n.value.exec(`"${o}"`);return i===null||i[1]!==o?!1:(i[1]=r,tr(e,i))}}function fw(e,t,n){let r=t.index+t[0].length;return/^[ \t]*;/u.test(t.input.slice(r,r+64))&&!$e(Wt(t))&&e.test(n)}function mw(e,t){for(let n=t+1;n<e.length;n+=1){if(e[n]===">")return n;if(e[n]==="<")return-1}return-1}function Yo(e,t){e.raw+=t,e.literal+=t}function pw(e,t,n){let r=e[t+1];if(e[t]!=="$"||r!=="{"&&r!=="(")return-1;let o=r==="{"?e.slice(t+2,t+2+Sw(e,t+2)):"",i=n[0],s=n.length===1&&i.quote!==void 0&&i.literal.length===i.pieceStart;return n.push({close:r==="{"?"}":")",keep:o!=="",raw:`$${r}${o}`,literal:"",opensPiece:s}),t+2+o.length}var _w=/[A-Za-z_]/u,yw=/\w/u,hw=/[{(A-Za-z_]/u,Qn=/\$[A-Za-z_]\w*/y,gw=/^_*[A-Z][A-Z0-9_]*$/u,ww=/^\$[A-Za-z_]\w*$/u,Ew=/^(["'])\$[A-Za-z_]\w*\1$/u;function bw(e,t,n){Qn.lastIndex=t;let r=Qn.exec(e)?.[0];return r===void 0?-1:(n.literal===""&&gw.test(r.slice(1))?n.raw+=r:Yo(n,r),t+r.length)}function Sw(e,t){if(!_w.test(e[t]??""))return 0;let n=t+1;for(;n<e.length&&yw.test(e[n]);)n+=1;e[n]===":"&&(n+=1);let r=e[n];return r==="-"||r==="="||r==="+"?n+1-t:0}function vw(e,t){let n=e.pop(),r=e.at(-1);r.raw+=`${n.raw}${t}`,n.keep&&(r.literal+=n.literal)}var nd=/[^$<"'\\})]+/y,Tw='$`"\\\n';function Iw(e,t){return e===`
110
+ `?"":t==='"'&&!Tw.includes(e)?`\\${e}`:e}function Aw(e,t,n){let r=e[t],o=n.quote;if(o==='"'&&r==="$"&&hw.test(e[t+1]??""))return-1;let i=1,s=r;if(r==="\\"&&o!=="'"&&t+1<e.length)i=2,s=Iw(e[t+1],o);else if(o===void 0){if(r!=='"'&&r!=="'")return-1;n.quote=r,s=""}else r===o&&(n.quote=void 0,s="");return n.raw+=e.slice(t,t+i),n.keep&&(n.literal+=s),t+i}function Cw(e,t,n,r,o){let i=n.at(-1);nd.lastIndex=t;let s=nd.exec(e)?.[0];if(s!==void 0)return Yo(i,s),t+s.length;if(n.length>1){let f=Aw(e,t,i);if(f!==-1)return f}else if(r&&Rw(e[t],i))return t+1;let a=pw(e,t,n);if(a!==-1)return a;let c=n.at(-1),d=e[t],l=o&&d==="$"?bw(e,t,c):-1;if(l!==-1)return l;if(n.length>1&&d===c.close)return vw(n,d),t+1;let u=d==="<"?mw(e,t):-1;return u!==-1?(c.raw+=e.slice(t,u+1),u+1):(Yo(c,d),t+1)}function Rw(e,t){return e!=='"'&&e!=="'"?!1:t.quote===void 0?(t.quote=e,t.pieceStart=t.literal.length,!0):e!==t.quote?!1:(t.quote=void 0,!0)}function vd(e,t,n){if(n&&(ww.test(e)||t&&Ew.test(e)))return"";let r={close:"}",keep:!0,raw:"",literal:""},o=[r];for(let i=0;i<e.length;)i=Cw(e,i,o,t,n);for(let i=o.length-1;i>0;i-=1){let s=o[i],a=o[i-1];a.raw+=s.raw,t&&i===1&&s.opensPiece===!0||(a.literal+=s.raw)}return r.literal}function Td(e,t=!0){return vd(e,!1,t)}function xw(e,t=!0){return vd(e,!0,t)}function tr(e,t){let n=e.minimumLiteralLength===void 0?t[1]:wd(t);if(e.minimumLiteralLength!==void 0&&n.length<e.minimumLiteralLength||e.literalValue&&Yg.test(t[1])&&!ow(e.literalValue,n,Gg(t))||e.rejectValue?.test(n)===!0||e.rejectStatementReference&&fw(e.rejectStatementReference,t,n))return!1;if(e.minimumEntropy===void 0)return!0;let r=[...n],o=new Map;for(let s of r)o.set(s,(o.get(s)??0)+1);let i=0;for(let s of o.values()){let a=s/r.length;i-=a*Math.log2(a)}return i>=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]="e55d27db-d28f-56da-ac44-2ed6c19f8609")}catch{}})();var Ow=[{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"}],Zo=new Map(Ow.map(e=>[e.action,e])),kw=/^(?:0|[1-9]\d*)$/u,Dw=2**32-2;function Nw(e){return kw.test(e)&&Number(e)<=Dw}function kd(e){let t=[];for(let n of er){let r=Mw(n,e);r&&t.push({rule:n,match:r})}return t}function Lw(e,t){let n=t.names.get(e);return n===void 0&&(n=kd(e),t.names.set(e,n)),n}function Dd(e,t){let n=t.entries.get(e);return n===void 0&&(n=Array.isArray(e)?Object.getOwnPropertyNames(e).filter(Nw).map(r=>({name:r,value:e[Number(r)],segment:`[${r}]`,nameMatches:[]})):Object.entries(e).map(([r,o],i)=>{let s=Lw(r,t);return{name:r,value:o,segment:s.length>0?`[key ${i}]`:`.${r}`,nameMatches:s}}),t.entries.set(e,n)),n}function Id({rule:e,match:t},n,r){let o={rule:e.mutationRule,path:n};return r&&(o.property_name=!0),t.normalizations&&(o.normalizations=t.normalizations),t.normalization_incomplete&&(o.normalization_incomplete=!0),o}function Nd(e,t){for(let n=t.length-1;n>=0;n-=1)e.push(t[n])}function Mw(e,t){try{return $w(e,t)}catch(n){return Ld(n)}}function Ld(e){if(!(e instanceof RangeError))throw e;return{index:0,normalization_incomplete:!0}}function $w(e,t){let n=ud(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 Pw(e,t){let n=[],r=new WeakSet,o=[{value:e,path:"$"}];for(let i=o.pop();i!==void 0;i=o.pop()){let{value:s,path:a}=i;if(typeof s=="string")for(let c of kd(s))n.push(Id(c,a,!1));else if(typeof s=="object"&&s!==null&&!r.has(s)){r.add(s);let c=Dd(s,t);for(let d of c)for(let l of d.nameMatches)n.push(Id(l,`${a}${d.segment}`,!0));Nd(o,c.map(d=>({value:d.value,path:`${a}${d.segment}`})))}}return n}var nr=er.filter(e=>"structured"in e),Fw=nr.map(()=>({named:!1,exact:!1})),Md=/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/gu,jw=3;function Ad(e){return e.replace(Md,"_")}function zw(e){let t=[...e.matchAll(Md)].map(n=>n.index).slice(-jw).map(n=>`${Ad(e.slice(0,n))}_${e.slice(n)}`);return[...new Set([e,Ad(e),...t])]}function Uw(e){let t=zw(e);return nr.map(n=>{let r=t.map(o=>bd(n,o));return r.includes("exact")?"exact":r.includes("prefixed")?"prefixed":void 0})}var Vw=nr.map(()=>{});function Hw(e,t,n,r){let o=Dd(e,r);if(Array.isArray(e)){let i=n.map(({named:s,exact:a})=>a?"lenient":s?"compact":void 0);return o.map(s=>({value:s.value,path:`${t}${s.segment}`,contexts:n,judgments:i}))}return o.map(({name:i,value:s,segment:a})=>{let c=Uw(i);return{value:s,path:`${t}${a}`,contexts:n.map(({named:d,exact:l},u)=>({named:d||c[u]!==void 0,exact:l||c[u]==="exact"})),judgments:c.map((d,l)=>d==="exact"?"lenient":d==="prefixed"||n[l].named?"compact":void 0)}})}function qw(e,t){let n=[],r=new WeakMap,o=[{value:e,path:"$",contexts:Fw,judgments:Vw}];for(let i=o.pop();i!==void 0;i=o.pop()){let{value:s,path:a,contexts:c,judgments:d}=i;if(typeof s=="string"){d.forEach((f,_)=>{let h=nr[_];if(f===void 0)return;let g;try{g=Sd(h,s,f==="compact")}catch(y){Ld(y),n.push({rule:h.mutationRule,path:a,normalization_incomplete:!0});return}g&&n.push({rule:h.mutationRule,path:a})});continue}if(typeof s!="object"||s===null)continue;let l=c.map(({named:f,exact:_})=>_?"e":f?"n":"-").join(""),u=r.get(s)??new Set;u.has(l)||(r.set(s,u.add(l)),Nd(o,Hw(s,a,c,t)))}return n}function $d(e){let t=new Set,n={entries:new WeakMap,names:new Map};return[...Pw(e,n),...qw(e,n)].filter(r=>{let o=`${r.rule}\0${r.path}\0${r.property_name===!0}`;return t.has(o)?!1:(t.add(o),!0)})}function Bw(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=$d(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}}var Cd=Object.freeze(Object.fromEntries(er.map(e=>[e.mutationRule,e.category])));function Ww(e){return Object.hasOwn(Cd,e)?Cd[e]:void 0}function Rd(e,t){return e!==void 0&&t!==void 0&&Object.hasOwn(e,t)?e[t]:void 0}var xd=new Set(Reflect.ownKeys(Object.prototype));function Yw(e){let t=Reflect.ownKeys(e);if(t.length!==xd.size||!t.every(r=>xd.has(r)))return!1;let n=Object.getOwnPropertyDescriptor(e,"constructor")?.value;return typeof n=="function"&&Object.getOwnPropertyDescriptor(n,"prototype")?.value===e}function Gw(e){let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype?!0:Object.getPrototypeOf(t)!==null?!1:Reflect.ownKeys(t).length===0||Yw(t)}function Od(e,t){let n=Object.hasOwn(e,t)?e[t]:void 0;if(n!==void 0&&(typeof n!="object"||n===null||!Gw(n)))throw new TypeError(`Secret guard policy ${t} must be an object keyed by ${t==="rules"?"rule":"category"}.`);return n}function cC(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("Secret guard policy must be an object with a default decision.");let n=Object.hasOwn(e,"default")?e.default:void 0;if(n===void 0)throw new TypeError("Secret guard policy requires a default decision.");let r=Od(e,"categories"),o=Od(e,"rules"),i=typeof t=="object"&&t!==null?t.rule:void 0;if(typeof i!="string")throw new TypeError("Secret guard finding must have a string rule.");let s=Rd(o,i);if(s!==void 0)return s;let a=Rd(r,Ww(i));return a===void 0?n:a}function Kw(e){return Zo.has(e.trim().toLowerCase())}function Xw(){return[...Zo.keys()].sort((e,t)=>e.localeCompare(t))}function dC(e){return Zo.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 Jw=/\b([a-z][a-z0-9]*)-(\d+)(?:-[a-z0-9]+)*\b/giu,Zw=/^(?:utf|iso|sha|tls|http|covid|match)$/iu;function Qo(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Fd(e){return[...new Set(Qo(e).match(/[\p{L}\p{N}]+/gu)??[])]}function Pd(e){let t=Qo(e);return{normalized:t,tokens:Fd(t),issueCodes:[...new Set([...e.matchAll(Jw)].filter(n=>{let r=n[1],o=n.index,i=e.slice(o+n[0].length);return!Zw.test(r)&&(r===r.toUpperCase()||r.length<=2||o===0&&/^\s*(?::|—|–|\])/u.test(i))}).map(n=>n[0].toLowerCase()))]}}function Qw(e,t){return eE(Pd(e),Pd(t))}function eE(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:en(e.tokens,t.tokens),reason:"title_token_jaccard"}}import tE 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]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var jd=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){let s=o;o+=1,r[s]=await n(e[s])}});return await Promise.all(i),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]="f65cb540-c93d-5da7-b4c3-bd189b2e4967")}catch{}})();var SC="mutation_guard.stale_in_progress_hours",Hd=36e5,vC=["claim_record_unavailable","discarded_history_tail","rewritten_history","workspace_restored"],nE=new Set(["history_repair","history_redact","merge_reconcile"]);function zd(e){return e==="history_salvage"||nE.has(e)}function Ud(e){let t=e.reanchor_evidence;if(t===void 0)return!1;if(!Array.isArray(t))return!0;let n=Ar(e.patch);return t.some(r=>!ti(r)||r.patch_hash!==n)}var rE=16;function Vd(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function qd(e){return Math.max(1,Math.trunc(e))}function Bd(e,t){let n;for(let r of[e,t]){let o=Date.parse(r??"");typeof r=="string"&&Number.isFinite(o)&&(n===void 0||o>n.time)&&(n={value:r,time:o})}return n?.value}function Wd(e,t){return Math.max(0,Math.floor((t-Date.parse(e))/Hd))}var oE=864e13;function TC(e,t){let n=Date.parse(e)+t*Hd;return Math.abs(n)<=oE?new Date(n).toISOString():null}function Yd(e){let t=e.status_registry;if(t===void 0){let r=Vd(e.in_progress_status);return o=>Vd(String(o.status))===r}let n=Qt(e.in_progress_status??t.in_progress_status,t);return r=>Qt(r.status,t)===n}function Gd(e){let t=e.assignee?.trim();return t!==void 0&&t.length>0?t:void 0}function ei(e){return e.sort((t,n)=>(n.age_hours??-1)-(t.age_hours??-1)||t.id.localeCompare(n.id))}var iE="Claim active work with `pm claim <id>` or return abandoned work to open with `pm update <id> --status open`.";function sE(e,t,n,r){let o=Gd(e);if(t===void 0)return o===void 0?{unowned:{id:e.id,last_activity_at:null,age_hours:null}}:{};let i={id:e.id,last_activity_at:t,age_hours:Wd(t,r)},s=i.age_hours>=n;return o!==void 0?s?{idle:{...i,assignee:zi(o)}}:{}:s?{unowned:{...i},idle:{...i},stale:{...i}}:{unowned:{...i}}}function Kd(e,t){let n=qd(t.threshold_hours),r=(t.now??new Date).getTime(),o=Yd(t),i=[],s=[],a=[];for(let c of e){if(!o(c))continue;let d=sE(c,Bd(c.updated_at,t.last_history_activity?.(c)),n,r);d.unowned&&i.push(d.unowned),d.idle&&s.push(d.idle),d.stale&&a.push(d.stale)}return{threshold_hours:n,unowned:{count:i.length,items:ei(i)},idle:{count:s.length,items:ei(s)},stale:{threshold_hours:n,count:a.length,items:ei(a),remediation:iE}}}function aE(e,t){return Kd(e,t).stale}function Xd(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.ts=="string"&&typeof t.op=="string"&&Array.isArray(t.patch)&&t.patch.every(n=>n!==null&&typeof n=="object"&&typeof n.path=="string")}function cE(e){if(Xd(e)){if(e.op==="history_compact_baseline"){let t=ni(e);return t.kind==="recorded"?t.at??void 0:e.ts}return Zi(e)==="substantive"?e.ts:void 0}}function ti(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ni(e){let t=e.context;if(t===void 0)return{kind:"legacy"};if(!ti(t))return{kind:"malformed"};let n=t.history_compaction;if(n===void 0)return{kind:"legacy"};if(!ti(n))return{kind:"malformed"};if(!("last_activity_at"in n))return{kind:"legacy"};let r=n.last_activity_at;return r===null?{kind:"recorded",at:null}:typeof r=="string"&&Number.isFinite(Date.parse(r))?{kind:"recorded",at:r}:{kind:"malformed"}}function IC(e){return Xd(e)&&Number.isFinite(Date.parse(e.ts))&&(e.op!=="history_compact_baseline"||ni(e).kind!=="malformed")}function AC(e,t){let n=e[t];if(n===void 0||n.op==="history_compact_baseline"||zd(n.op))return"claim_record_unavailable";if(Ud(n))return"rewritten_history";for(let r of e.slice(t+1)){if(zd(r.op))return r.op==="history_salvage"?"discarded_history_tail":"rewritten_history";if(Ud(r))return"rewritten_history"}}function CC(e){let t=ni(e);return t.kind==="recorded"?t.at:void 0}function Jd(e){let t;for(let n of e){let r=cE(n),o=Date.parse(r??"");r!==void 0&&Number.isFinite(o)&&(t===void 0||o>t.time)&&(t={value:r,time:o})}return t?.value}function RC(e){return Jd(e)??null}async function dE(e,t){let n;try{n=await pt(tE.join(e,"history",`${t}.jsonl`),t)}catch{return}return Jd(n)}async function lE(e,t,n){let r=qd(n.threshold_hours),o=(n.now??new Date).getTime(),i=Yd(n),s=new Map,a=t.filter(c=>{if(!i(c))return!1;if(Gd(c)===void 0)return!0;let d=Bd(c.updated_at,void 0);return d===void 0||Wd(d,o)>=r});return await jd(a,rE,async c=>{let d=await dE(e,c.id);d!==void 0&&s.set(c.id,d)}),Kd(t,{...n,now:new Date(o),last_history_activity:c=>s.get(c.id)})}async function uE(e,t,n){return(await lE(e,t,n)).stale}(function(){try{var e=typeof window<"u"?window:typeof 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 fE=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"}),mE=/&(?:lt|gt|quot|#39|amp);/g;function pE(e){return typeof e!="string"||!e.includes("&lt;")&&!e.includes("&gt;")?e:e.replace(mE,t=>fE[t])}function _E(e){return ri(e,new WeakMap)}function ri(e,t){if(typeof e=="string")return pE(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(ri(r,t));return n}if(e!==null&&typeof e=="object"){if(!yE(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:ri(i,t),enumerable:!0,writable:!0,configurable:!0});return r}return e}function yE(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 hE(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 Zd(e){return e.split(/[\s,|]+/).map(t=>t.trim()).filter(t=>t.startsWith("--"))}function gE(e){return Zd(e)[0]??null}function wE(e,t){let n=gE(t);if(n===null)return!1;let r=o=>o.slice(2).replaceAll("-","_");return Zd(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 EE(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 oi from"node:fs/promises";import rr 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 bE(e){return"json_markdown"}function Qd(e,t){return rr.relative(e,t).replaceAll("\\","/")}function SE(e){return String(e).replaceAll(/[^a-zA-Z0-9._-]+/g,"_").slice(0,120)}async function vE(e,t,n){e!==t&&ce(await oi.readFile(t,"utf8"),{format:"json_markdown",requireSupportedFormat:!0,schema:n})}async function TE(e,t,n="item_format:migrate",r=Q,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=bE(t),l=Object.entries(r);for(let[u,f]of l){let _=rr.join(e,f),h=[];try{h=await oi.readdir(_)}catch{continue}let g=new Map;for(let w of h){let E=rr.join(_,w),I=dt(E);if(!I)continue;let C=rr.extname(w),M=w.slice(0,w.length-C.length).trim();if(M.length===0)continue;let R=g.get(M)??{};R[I]=E,g.set(M,R)}let y=[...g.keys()].sort((w,E)=>w.localeCompare(E));for(let w of y){let E=g.get(w);c+=1;let I=E[d];if(!I)continue;let C=E[t]??I,M=C===E[t]?t:d;try{let R=await oi.readFile(C,"utf8"),D=ce(R,{format:M,requireSupportedFormat:!0,schema:o,onWarning:Z=>a.push(`item_format_migration_parse_warning:${w}:${Z}`)});await vE(C,I,o);let J=ze(e,u,w,t,r),ae=ft(D,{format:t,schema:o});await A(J)!==ae&&(await T(J,ae),a.push(...await U({path:J,scope:"project",op:n})),i.add(w)),await st(I),s.add(Qd(e,I)),a.push(...await U({path:I,scope:"project",op:`${n}:remove`})),i.add(w)}catch(R){a.push(`item_format_migration_skipped:${Qd(e,C)}:${SE(R)}`)}}}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 IE=new Set(["completed","superseded"]);function AE(e){return e!==void 0&&IE.has(e)}function CE(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 RE}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 xE=/^[a-z][a-z0-9_-]{0,63}$/u,OE=new Set(["constructor","prototype"]),el="settings:section:write",kE=240;function or(e){return`sha256:${RE("sha256").update(ii(e)).digest("hex")}`}function ii(e){return Array.isArray(e)?`[${e.map(t=>ii(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ii(Object.getOwnPropertyDescriptor(e,t)?.value)}`).join(",")}}`:String(JSON.stringify(e))}function nl(e){if(!xE.test(e)||OE.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(is.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 rl(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 si(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,kE)}`,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 ol(e){return typeof Reflect.get(e,"toJSON")=="function"}function ai(e){return e.length===0?"the value":e.join(".")}function il(e,t){return Object.values(Object.getOwnPropertyDescriptors(e)).every(n=>"value"in n&&(!t||n.enumerable===!0))}function DE(e){if(Object.getPrototypeOf(e)!==Array.prototype||!il(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&&!ol(e)}function NE(e){let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&il(e,!0)&&Object.getOwnPropertySymbols(e).length===0&&!ol(e)}function LE(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return null;let n=ai(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 sl(e,t=[],n=new Set){if(typeof e!="object"||e===null)return LE(e,t);let r=ai(t);if(n.has(e))return{detail:`${r} is a circular reference`,representable:!1};if(!(Array.isArray(e)?DE(e):NE(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=sl(i,[...t,o],n);if(s!==null)return s}return n.delete(e),null}function al(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 ai(o);let i=al(r,o);if(i!==null)return i}return null}function tl(e,t,n){return si(e,t,()=>{throw new Error(n)})}function ME(e,t){let n=sl(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 tl(e,t,o)}let r=al(t);return r!==null?tl(e,t,`${r} is a reserved key that settings history cannot record`):JSON.parse(JSON.stringify(t))}function cl(e,t){return Object.hasOwn(e,t)?e[t]:void 0}async function $E(e,t,n={}){nl(t);let r=Ee(e);await Te({path:r,scope:"project"});let o=await A(r),i=o===null?void 0:cl(rl(o),t);if(i===void 0)return{section:t,source:"default",value:n.defaultValue,revision:null};let s=or(i);return{section:t,source:"stored",value:si(t,structuredClone(i),n.validate),revision:s}}async function PE(e,t,n,r={}){nl(t);let o=n===void 0?void 0:ME(t,si(t,n,r.validate)),i=Ee(e),s=await W(e);try{let a=await Nr({pmRoot:e,filePath:i,op:el,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=rl(c),l=cl(d,t),u=l===void 0?null:or(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:or(o)};return it(l,o)?{raw:c,result:f}:(o===void 0?delete d[t]:d[t]=o,{raw:`${JSON.stringify(d,null,2)}
111
+ `,result:{...f,changed:!0}})}});return a.changed&&await U({path:i,scope:"project",op:el}),a.result}finally{an(e)}}import FE from"node:readline/promises";import{stdin as jE,stdout as dl}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 zE="PM_TELEMETRY_PROMPT",ll=new Set(["0","false","no","off"]),UE=new Set(["init","completion","completion-statuses","completion-tags","completion-types"]);function VE(e){return typeof e!="string"?!1:ll.has(e.trim().toLowerCase())}function HE(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t.length===0?!1:!ll.has(t)}function qE(e,t){if(t.json===!0||t.quiet===!0||process.stdin.isTTY!==!0||process.stdout.isTTY!==!0||VE(process.env[zE])||HE(process.env.CI))return!0;let n=e.trim().toLowerCase();return n.length===0?!0:UE.has(n)}function BE(e){let t=e.trim().toLowerCase();return!(t==="n"||t==="no")}async function WE(e){let t=`pm telemetry helps improve reliability and usage diagnostics.
112
112
  It is enabled by default and can be changed anytime via:
113
113
  pm config global set telemetry-tracking --policy disabled
114
- Enable telemetry now? [${e?"Y/n":"y/N"}] `,n=OE.createInterface({input:DE,output:il});try{let r=await n.question(t);return r.trim().length===0?e:FE(r)}finally{n.close()}}async function zE(e,t){if(!(G().telemetry_disabled||PE(e,t)))try{let n=me(process.cwd()),r=await B(n);if(r.telemetry.first_run_prompt_completed||Et(r))return;let o=await jE(r.telemetry.enabled);r.telemetry.enabled=o,r.telemetry.first_run_prompt_completed=!0,await bt(n,r,"telemetry:first_run_prompt"),il.write(`Telemetry ${o?"enabled":"disabled"} for this CLI install. Update any time with pm config global set telemetry-tracking --policy ${o?"disabled":"enabled"}.
115
- `)}catch{}}import X from"node:crypto";import{spawn as HE}from"node:child_process";import{mkdirSync as ci,rmSync as qE,statSync as gl}from"node:fs";import{mkdir as di,readdir as WE,rm as hi,stat as wl}from"node:fs/promises";import{request as BE}from"node:http";import{request as YE}from"node:https";import yi from"node:os";import O from"node:path";import UE 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 al(e,t,n,r=process.env,o=Date.now()){if(!n||!Vn.has(t))return 1;if(r.PM_TELEMETRY_READ_SAMPLE_RATE!==void 0)return dc(t,!0,r);try{let i=UE.join(e,"runtime","telemetry","read-sampling.json"),s=Math.floor(o/6e4),a=VE(await A(i),s),c=Math.min(Number.MAX_SAFE_INTEGER,(a[t]??0)+1);return a[t]=c,await v(i,`${JSON.stringify({minute:s,counts:a})}
116
- `),Math.min(1,(10/c)**2)}catch{return 1}}function VE(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))Vn.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 GE=O.join("runtime","telemetry","events.jsonl"),KE=O.join("runtime","telemetry","state.json"),XE=O.join("runtime","telemetry","otel-spans.jsonl"),JE=8,cl=500,ar=1,dl=1,ZE=100,QE=36e5,eb=3e4,ll=2e4,tb=1e3,nb=25e3,gi=250,rb=864e5,cr=65536,El=6,bl=20,Sl=15,ob=8192,Tl=[25,50,100,200],ib=3600*1e3,sb=1440*60*1e3,vl=6e4,ab=6e4,cb="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",db="OTEL_EXPORTER_OTLP_ENDPOINT",lb="OTEL_SERVICE_NAME",ub="PM_TELEMETRY_OTEL_DISABLED",fb=new Set(["1","true","yes","on"]),mb="PM_TELEMETRY_INLINE_FLUSH",fe="PM_TELEMETRY_FLUSH_CHILD",pb="PM_TELEMETRY_HTTP_TIMEOUT_MS",_b=globalThis.fetch,ul=!1,li=Promise.resolve(),fl=Promise.resolve(),or=new WeakMap;var hb=new Set(["1","true","yes","on"]),yb=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]),dr=X.randomUUID(),gb=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],wb=new Set(["literal","literals","regex","regexes","replacement","replacements","setjson","set_json","update"]),Il="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",Eb=new RegExp(`\\b(${Il})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),bb=new RegExp(`(--${Il})(=|\\s+)([^\\s,;]+)`,"giu"),Sb=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,Tb=/bearer\s+[a-z0-9._=-]+/giu,vb=/\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 Yt(e,t=z().endpoint){return O.join(O.dirname(O.join(e,GE)),Ht("events.jsonl",t))}function Gt(e){return O.join(e,XE)}function Ib(e){return O.dirname(Yt(e,null))}function Al(e,t=z().endpoint){return O.join(O.dirname(O.join(e,KE)),Ht("state.json",t))}function wi(e){return O.join(e,"runtime","telemetry","flush.lock")}function Cl(e){return O.join(e,"runtime","telemetry","flush.spawn.lock")}function Ab(){return O.join(gt(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function Cb(){return se(process.env[mb])||se(process.env[fe])?!0:Mo()}async function xb(e,t=z().endpoint){let n=await A(Al(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 ir(e,t,n=z().endpoint){try{await we(async()=>{let r={...await xb(e,n),...t},o=Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0).sort((i,s)=>i[0].localeCompare(s[0])));await v(Al(e,n),`${JSON.stringify(o,null,2)}
117
- `,{createParentDirectories:!se(process.env[fe])})},e)}catch{}}function fi(e){let t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),n=t.split("_").filter(r=>r.length>0);return wb.has(t)||gb.some(r=>t===r||t.endsWith(`_${r}`)||n.includes(r))}function xl(e){return e.replaceAll(Eb,(t,n,r)=>`${n}${r}[redacted]`).replaceAll(bb,(t,n,r)=>`${n}${r}[redacted]`)}function Rl(e){return e.replaceAll(Sb,(t,n)=>`${n}[redacted_path]`)}function kl(e){let t=e>=65&&e<=90,n=e>=97&&e<=122,r=e>=48&&e<=57;return t||n||r}function Ol(e){if(!e)return!1;let t=e.charCodeAt(0);return kl(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function Dl(e){if(!e)return!1;let t=e.charCodeAt(0);return kl(t)?!0:e==="."||e==="-"}function Rb(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(!Ol(i))return!1;for(let i of r)if(!Dl(i))return!1;return!0}function kb(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&&Ol(e[o]);)o-=1;o+=1;let i=r+1;for(;i<e.length&&Dl(e[i]);)i+=1;let s=e.slice(o,i);if(Rb(s)){t+=e.slice(n,o),t+="[redacted_email]",n=i;continue}t+=e.slice(n,r+1),n=r+1}return t}function Nl(e){return kb(Zt(e)).replaceAll(Tb,"bearer [redacted_token]").replaceAll(vb,"[redacted_ip]")}function Ob(e){let t=Nl(e),n=xl(t),r=Rl(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>512?`${r.slice(0,509)}...`:r}function Db(e){let t=Nl(e),n=xl(t),r=Rl(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"?Db(e):Ob(e)}function je(e,t,n="redacted",r=0){if(t&&fi(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>=El)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,bl).map(o=>je(o,void 0,n,r+1));if(typeof e=="object"){let o=e,i={};for(let[s,a]of Object.entries(o))i[s]=je(a,s,n,r+1);return i}return String(e)}function Ll(e,t="redacted"){let n=[],r=!1;for(let o of e){let i=k(ji(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);fi(c)?n.push(`--${c}=[redacted]`):n.push(`--${c}=${k(d,t)}`);continue}if(fi(s)){n.push(`--${s}`),r=!0;continue}}n.push(i)}return n}function Nb(e){let t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function se(e){return hb.has((e??"").trim().toLowerCase())}function ml(){let e=process.env[pb]?.trim();if(!e)return ll;let t=Number(e);return Number.isFinite(t)?Math.min(nb,Math.max(tb,Math.trunc(t))):ll}async function Ml(e,t,n){let r=new URL(e);if(globalThis.fetch!==_b){let i=new AbortController,s,a=new Promise((c,d)=>{s=setTimeout(()=>{i.abort(),d(new Error("telemetry_http_timeout"))},ml())});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:"?YE:r.protocol==="http:"?BE:void 0;if(!o)throw new Error(`telemetry_http_protocol_unsupported_${r.protocol}`);return new Promise((i,s)=>{let a=ml(),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 $l(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function Ei(e){let t=e?.trim();return t&&t.length>0?t:void 0}function bi(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Pl(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?Xt(e.errorCode):"unknown"}function Fl(e){let t=Qe(e);return t.source_context_source==="env_override_rejected"&&!ul&&!e.quiet&&(ul=!0,process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${Un.join("|")}; ignoring override.
118
- `)),t}function F(e,t){return X.createHash("sha256").update(`${e}:${t}`).digest("hex")}function Si(e,t){let n=(Tr()??"").trim(),r=Xi({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?yb.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 mi(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=El)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,bl).map(n=>mi(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]=mi(n[i],t+1);return r}return String(e)}function pi(e,t){return F(e,JSON.stringify(mi(t)))}function jl(e,t){return{hashes:t.map(n=>F(e,n)),digest:F(e,t.join("\0"))}}function zl(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 Lb(){if(fb.has((process.env[ub]??"").trim().toLowerCase()))return null;let e=(process.env[cb]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}let t=(process.env[db]??"").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 pl(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 Mb(e,t){return{key:e,value:{boolValue:t}}}function _l(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function $b(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[lb]??"").trim()),a=s.length>0?s:"pm-cli",c=bi(t.exit_code,t.ok),d=Ei(t.error_code),l=Pl({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",dr),V("pm.pm_root_hash",e.pm_root_hash),V("pm.cwd_hash",e.cwd_hash),Mb("pm.ok",t.ok),_l("pm.exit_code",c),_l("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:pl(e.started_at),endTimeUnixNano:pl(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 Pb(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=>je(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=je(n[s],s,t);if(a===void 0)continue;let c=JSON.stringify(a).length;if(i+c>ob){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 Fb(e){let{captureLevel:t,context:n,pmVersion:r,sourceContext:o,pmRootHash:i,cwdHash:s,installationId:a}=e,c=Le(n.command),d=jl(a,n.args),l=F(a,`${n.command}\0${n.args.join("\0")}`),u=pi(a,n.options),f=pi(a,n.global),_=Si(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:Ll(n.args,t),command_args_hashes:d.hashes,command_args_digest:d.digest,command_invocation_digest:l,command_options:je(n.options,void 0,t),command_options_digest:u,global_options:je(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,yi.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function jb(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?zl(c,a,u,o.error):void 0,h=Si(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:Pb(o.result,t)}}function zb(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=jl(f,c),E=F(f,o),I=pi(f,d),C=zl(f,o,_,y),M=Si(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:E,attempted_args_digest:w.digest,attempted_options_digest:I,error_code:_,error_category:g,exit_code:h,error:k(y,"redacted"),error_fingerprint:C,...M}:{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,...M,attempted_command:k(o,t),attempted_command_digest:E,attempted_args:Ll(c,t),attempted_args_hashes:w.hashes,attempted_args_digest:w.digest,attempted_options:je(d,void 0,t),attempted_options_digest:I,error_code:_,error_category:g,exit_code:h,error:k(y,t),error_fingerprint:C,pm_root_hash:l,cwd_hash:u,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:F(f,yi.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function Ti(e){let t=await B(e);if(!t.telemetry.enabled||G().telemetry_disabled)return null;if(t.telemetry.installation_id.trim().length===0){if(Lr(e)||Et(t))return null;t.telemetry.installation_id=X.randomUUID(),await bt(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:Nb(t.telemetry.capture_level)}}async function sr(e,t){let n=JSON.stringify({client_schema_version:dl,event:t,attempts:0});if(n.length>cr){let r={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:n.length}}};n=JSON.stringify({client_schema_version:dl,event:r,attempts:0})}await pr(Yt(e),n)}function Ul(e){let t=[];for(let n of e.split(`
119
- `)){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 Vl(e){let t=Math.min(eb*2**Math.max(e-1,0),QE);return new Date(Date.now()+t).toISOString()}function vi(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 Hl(e){return vi(e.next_attempt_after)}function ql(e){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*rb}function Ub(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 lr(e,t){let n=ql(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>cr||Ub(i,n)||i.attempts>=Sl){o+=1;continue}r.push(i)}return{entries:r,prunedCount:o}}async function Wl(e,t,n=z().endpoint){let r=t.map(i=>JSON.stringify(i)).join(`
114
+ Enable telemetry now? [${e?"Y/n":"y/N"}] `,n=FE.createInterface({input:jE,output:dl});try{let r=await n.question(t);return r.trim().length===0?e:BE(r)}finally{n.close()}}async function YE(e,t){if(!(G().telemetry_disabled||qE(e,t)))try{let n=me(process.cwd()),r=await W(n);if(r.telemetry.first_run_prompt_completed||Et(r))return;let o=await WE(r.telemetry.enabled);r.telemetry.enabled=o,r.telemetry.first_run_prompt_completed=!0,await bt(n,r,"telemetry:first_run_prompt"),dl.write(`Telemetry ${o?"enabled":"disabled"} for this CLI install. Update any time with pm config global set telemetry-tracking --policy ${o?"disabled":"enabled"}.
115
+ `)}catch{}}import X from"node:crypto";import{spawn as XE}from"node:child_process";import{mkdirSync as ci,rmSync as JE,statSync as Sl}from"node:fs";import{mkdir as di,readdir as ZE,rm as yi,stat as vl}from"node:fs/promises";import{request as QE}from"node:http";import{request as eb}from"node:https";import hi from"node:os";import k from"node:path";import GE 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 ul(e,t,n,r=process.env,o=Date.now()){if(!n||!Vn.has(t))return 1;if(r.PM_TELEMETRY_READ_SAMPLE_RATE!==void 0)return dc(t,!0,r);try{let i=GE.join(e,"runtime","telemetry","read-sampling.json"),s=Math.floor(o/6e4),a=KE(await A(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})}
116
+ `),Math.min(1,(10/c)**2)}catch{return 1}}function KE(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))Vn.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 tb=k.join("runtime","telemetry","events.jsonl"),nb=k.join("runtime","telemetry","state.json"),rb=k.join("runtime","telemetry","otel-spans.jsonl"),ob=8,fl=500,cr=1,ml=1,ib=100,sb=36e5,ab=3e4,pl=2e4,cb=1e3,db=25e3,gi=250,lb=864e5,dr=65536,Tl=6,Il=20,Al=15,ub=8192,Cl=[25,50,100,200],fb=3600*1e3,mb=1440*60*1e3,Rl=6e4,pb=6e4,_b="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",yb="OTEL_EXPORTER_OTLP_ENDPOINT",hb="OTEL_SERVICE_NAME",gb="PM_TELEMETRY_OTEL_DISABLED",wb=new Set(["1","true","yes","on"]),Eb="PM_TELEMETRY_INLINE_FLUSH",fe="PM_TELEMETRY_FLUSH_CHILD",bb="PM_TELEMETRY_HTTP_TIMEOUT_MS",Sb=globalThis.fetch,_l=!1,li=Promise.resolve(),yl=Promise.resolve(),ir=new WeakMap;var vb=new Set(["1","true","yes","on"]),Tb=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]),lr=X.randomUUID(),Ib=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],Ab=new Set(["literal","literals","regex","regexes","replacement","replacements","setjson","set_json","update"]),xl="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",Cb=new RegExp(`\\b(${xl})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),Rb=new RegExp(`(--${xl})(=|\\s+)([^\\s,;]+)`,"giu"),xb=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,Ob=/bearer\s+[a-z0-9._=-]+/giu,kb=/\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 Yt(e,t=z().endpoint){return k.join(k.dirname(k.join(e,tb)),Ht("events.jsonl",t))}function Gt(e){return k.join(e,rb)}function Db(e){return k.dirname(Yt(e,null))}function Ol(e,t=z().endpoint){return k.join(k.dirname(k.join(e,nb)),Ht("state.json",t))}function wi(e){return k.join(e,"runtime","telemetry","flush.lock")}function kl(e){return k.join(e,"runtime","telemetry","flush.spawn.lock")}function Nb(){return k.join(gt(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function Lb(){return se(process.env[Eb])||se(process.env[fe])?!0:$o()}async function Mb(e,t=z().endpoint){let n=await A(Ol(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 sr(e,t,n=z().endpoint){try{await we(async()=>{let r={...await Mb(e,n),...t},o=Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0).sort((i,s)=>i[0].localeCompare(s[0])));await T(Ol(e,n),`${JSON.stringify(o,null,2)}
117
+ `,{createParentDirectories:!se(process.env[fe])})},e)}catch{}}function fi(e){let t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),n=t.split("_").filter(r=>r.length>0);return Ab.has(t)||Ib.some(r=>t===r||t.endsWith(`_${r}`)||n.includes(r))}function Dl(e){return e.replaceAll(Cb,(t,n,r)=>`${n}${r}[redacted]`).replaceAll(Rb,(t,n,r)=>`${n}${r}[redacted]`)}function Nl(e){return e.replaceAll(xb,(t,n)=>`${n}[redacted_path]`)}function Ll(e){let t=e>=65&&e<=90,n=e>=97&&e<=122,r=e>=48&&e<=57;return t||n||r}function Ml(e){if(!e)return!1;let t=e.charCodeAt(0);return Ll(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function $l(e){if(!e)return!1;let t=e.charCodeAt(0);return Ll(t)?!0:e==="."||e==="-"}function $b(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(!Ml(i))return!1;for(let i of r)if(!$l(i))return!1;return!0}function Pb(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&&Ml(e[o]);)o-=1;o+=1;let i=r+1;for(;i<e.length&&$l(e[i]);)i+=1;let s=e.slice(o,i);if($b(s)){t+=e.slice(n,o),t+="[redacted_email]",n=i;continue}t+=e.slice(n,r+1),n=r+1}return t}function Pl(e){return Pb(Zt(e)).replaceAll(Ob,"bearer [redacted_token]").replaceAll(kb,"[redacted_ip]")}function Fb(e){let t=Pl(e),n=Dl(t),r=Nl(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>512?`${r.slice(0,509)}...`:r}function jb(e){let t=Pl(e),n=Dl(t),r=Nl(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>2048?`${r.slice(0,2045)}...`:r}function O(e,t="redacted"){return t==="max"?jb(e):Fb(e)}function je(e,t,n="redacted",r=0){if(t&&fi(t))return"[redacted]";if(e==null)return e;if(typeof e=="string")return O(e,n);if(typeof e=="number"||typeof e=="boolean")return e;if(r>=Tl)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,Il).map(o=>je(o,void 0,n,r+1));if(typeof e=="object"){let o=e,i={};for(let[s,a]of Object.entries(o))i[s]=je(a,s,n,r+1);return i}return String(e)}function Fl(e,t="redacted"){let n=[],r=!1;for(let o of e){let i=O(ji(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);fi(c)?n.push(`--${c}=[redacted]`):n.push(`--${c}=${O(d,t)}`);continue}if(fi(s)){n.push(`--${s}`),r=!0;continue}}n.push(i)}return n}function zb(e){let t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function se(e){return vb.has((e??"").trim().toLowerCase())}function hl(){let e=process.env[bb]?.trim();if(!e)return pl;let t=Number(e);return Number.isFinite(t)?Math.min(db,Math.max(cb,Math.trunc(t))):pl}async function jl(e,t,n){let r=new URL(e);if(globalThis.fetch!==Sb){let i=new AbortController,s,a=new Promise((c,d)=>{s=setTimeout(()=>{i.abort(),d(new Error("telemetry_http_timeout"))},hl())});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:"?eb:r.protocol==="http:"?QE:void 0;if(!o)throw new Error(`telemetry_http_protocol_unsupported_${r.protocol}`);return new Promise((i,s)=>{let a=hl(),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 zl(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function Ei(e){let t=e?.trim();return t&&t.length>0?t:void 0}function bi(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Ul(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?Xt(e.errorCode):"unknown"}function Vl(e){let t=Qe(e);return t.source_context_source==="env_override_rejected"&&!_l&&!e.quiet&&(_l=!0,process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${Un.join("|")}; ignoring override.
118
+ `)),t}function F(e,t){return X.createHash("sha256").update(`${e}:${t}`).digest("hex")}function Si(e,t){let n=(Tr()??"").trim(),r=Xi({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?Tb.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 mi(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=Tl)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,Il).map(n=>mi(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]=mi(n[i],t+1);return r}return String(e)}function pi(e,t){return F(e,JSON.stringify(mi(t)))}function Hl(e,t){return{hashes:t.map(n=>F(e,n)),digest:F(e,t.join("\0"))}}function ql(e,t,n,r){let o=O(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 Ub(){if(wb.has((process.env[gb]??"").trim().toLowerCase()))return null;let e=(process.env[_b]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}let t=(process.env[yb]??"").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 gl(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 Vb(e,t){return{key:e,value:{boolValue:t}}}function wl(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function Hb(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=O((process.env[hb]??"").trim()),a=s.length>0?s:"pm-cli",c=bi(t.exit_code,t.ok),d=Ei(t.error_code),l=Ul({ok:t.ok,errorCode:d,errorCategory:t.error_category}),u=[V("pm.command",O(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",lr),V("pm.pm_root_hash",e.pm_root_hash),V("pm.cwd_hash",e.cwd_hash),Vb("pm.ok",t.ok),wl("pm.exit_code",c),wl("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",O(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.${O(e.command)}`,kind:1,startTimeUnixNano:gl(e.started_at),endTimeUnixNano:gl(n),attributes:u,status:{code:t.ok?1:2,message:t.ok?"":O(typeof t.error=="string"?t.error:"command_failed")}}]}]}]};return{endpoint:i,payload:f}}function qb(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:O(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=>je(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=je(n[s],s,t);if(a===void 0)continue;let c=JSON.stringify(a).length;if(i+c>ub){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 Bb(e){let{captureLevel:t,context:n,pmVersion:r,sourceContext:o,pmRootHash:i,cwdHash:s,installationId:a}=e,c=Le(n.command),d=Hl(a,n.args),l=F(a,`${n.command}\0${n.args.join("\0")}`),u=pi(a,n.options),f=pi(a,n.global),_=Si(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:Fl(n.args,t),command_args_hashes:d.hashes,command_args_digest:d.digest,command_invocation_digest:l,command_options:je(n.options,void 0,t),command_options_digest:u,global_options:je(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,hi.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function Wb(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:h}=e,g=o.ok===!1?ql(c,a,u,o.error):void 0,y=Si(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:h,ok:o.ok,exit_code:l,error_code:u,error_category:f,error:o.error?O(o.error,"redacted"):void 0,error_fingerprint:g,duration_ms:i,...y}:{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:h,...y,ok:o.ok,exit_code:l,error_code:u,error_category:f,error:o.error?O(o.error,t):void 0,error_fingerprint:g,duration_ms:i,started_at:s,result_summary:qb(o.result,t)}}function Yb(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:h,errorCategory:g,exitCode:y}=e,w=Hl(f,c),E=F(f,o),I=pi(f,d),C=ql(f,o,_,h),M=Si(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:E,attempted_args_digest:w.digest,attempted_options_digest:I,error_code:_,error_category:g,exit_code:y,error:O(h,"redacted"),error_fingerprint:C,...M}:{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,...M,attempted_command:O(o,t),attempted_command_digest:E,attempted_args:Fl(c,t),attempted_args_hashes:w.hashes,attempted_args_digest:w.digest,attempted_options:je(d,void 0,t),attempted_options_digest:I,error_code:_,error_category:g,exit_code:y,error:O(h,t),error_fingerprint:C,pm_root_hash:l,cwd_hash:u,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:F(f,hi.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function vi(e){let t=await W(e);if(!t.telemetry.enabled||G().telemetry_disabled)return null;if(t.telemetry.installation_id.trim().length===0){if(Mr(e)||Et(t))return null;t.telemetry.installation_id=X.randomUUID(),await bt(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:zb(t.telemetry.capture_level)}}async function ar(e,t){let n=JSON.stringify({client_schema_version:ml,event:t,attempts:0});if(n.length>dr){let r={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:n.length}}};n=JSON.stringify({client_schema_version:ml,event:r,attempts:0})}await _r(Yt(e),n)}function Bl(e){let t=[];for(let n of e.split(`
119
+ `)){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 Wl(e){let t=Math.min(ab*2**Math.max(e-1,0),sb);return new Date(Date.now()+t).toISOString()}function Ti(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 Yl(e){return Ti(e.next_attempt_after)}function Gl(e){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*lb}function Gb(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 ur(e,t){let n=Gl(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>dr||Gb(i,n)||i.attempts>=Al){o+=1;continue}r.push(i)}return{entries:r,prunedCount:o}}async function Kl(e,t,n=z().endpoint){let r=t.map(i=>JSON.stringify(i)).join(`
120
120
  `),o=r.length>0?`${r}
121
- `:"";for(let i=0;;i+=1)try{await v(Yt(e,n),o,{createParentDirectories:!se(process.env[fe])});return}catch(s){let a=Tl[i];if(a===void 0||!Bl(s))throw s;await Yl(a)}}function Bl(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function Yl(e){return new Promise(t=>{setTimeout(t,e)})}async function Vb(e,t){let n={id:X.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:P(),attempts:0},r=JSON.stringify(n);r.length>cr||await pr(Gt(e),r)}function Hb(e){let t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return X.createHash("sha256").update(t).digest("hex").slice(0,32)}function Ii(e){let t=[];for(let n of e.split(`
122
- `)){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=Hb(o)),t.push(o))}catch{}}return t}function qb(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 Ai(e,t){let n=ql(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>cr||qb(i,n)||i.attempts>=Sl){o+=1;continue}r.push(i)}if(r.length>cl){let i=r.length-cl;return o+=i,{entries:r.slice(i),prunedCount:o}}return{entries:r,prunedCount:o}}async function Wb(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
121
+ `:"";for(let i=0;;i+=1)try{await T(Yt(e,n),o,{createParentDirectories:!se(process.env[fe])});return}catch(s){let a=Cl[i];if(a===void 0||!Xl(s))throw s;await Jl(a)}}function Xl(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function Jl(e){return new Promise(t=>{setTimeout(t,e)})}async function Kb(e,t){let n={id:X.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:P(),attempts:0},r=JSON.stringify(n);r.length>dr||await _r(Gt(e),r)}function Xb(e){let t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return X.createHash("sha256").update(t).digest("hex").slice(0,32)}function Ii(e){let t=[];for(let n of e.split(`
122
+ `)){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=Xb(o)),t.push(o))}catch{}}return t}function Jb(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 Ai(e,t){let n=Gl(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>dr||Jb(i,n)||i.attempts>=Al){o+=1;continue}r.push(i)}if(r.length>fl){let i=r.length-fl;return o+=i,{entries:r.slice(i),prunedCount:o}}return{entries:r,prunedCount:o}}async function Zb(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
123
123
  `),r=n.length>0?`${n}
124
- `:"";for(let o=0;;o+=1)try{await v(Gt(e),r,{createParentDirectories:!se(process.env[fe])});return}catch(i){let s=Tl[o];if(s===void 0||!Bl(i))throw i;await Yl(s)}}async function hl(e,t,n,r){return we(async()=>{let o=await A(Gt(e)),i=o===null?[]:Ii(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}=Ai(s,t);return await Wb(e,a),a.length},e)}async function Bb(e,t){let n=await A(Gt(e));if(n===null||n.trim().length===0){await ir(e,{pending_otel_spans:0},null);return}let r=Ii(n),{entries:o,prunedCount:i}=Ai(r,t),s=o.filter(y=>vi(y.next_attempt_after)).slice(0,JE);if(s.length===0){let y=i>0?await hl(e,t,new Set,new Map):o.length;await ir(e,{pending_otel_spans:y},null);return}let a=P(),c=new Set,d=new Map,l=0,u;await Promise.all(s.map(async y=>{try{let g=await Ml(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(qn(g.message),"redacted"):"local_otel_export_failed";let h=y.attempts+1;d.set(y.id,{attempts:h,next_attempt_after:Vl(h)})}}));let f=await hl(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 ir(e,_,null)}async function Gl(e,t,n){try{await Xb(e,t,n)}catch{}try{await Bb(e,n)}catch{}}async function Yb(e,t=ib,n=z().endpoint){try{let r=Ib(e),o=await WE(r,{withFileTypes:!0}),i=Date.now(),s=new Set([Ht("events.jsonl",n),Ht("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-sb: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 wl(l)).mtimeMs<d&&await hi(l,{force:!0})}))}catch{}}async function we(e,t=me(process.cwd()),n=5e3){let r=fl.catch(()=>{}).then(()=>rs(async()=>{let o=await Te(t,"telemetry-queue",60,"telemetry",!1,!1,n,{createParentDirectories:!se(process.env[fe])});try{return an(t),await e()}finally{await o()}}));return fl=r.catch(()=>{}),r}async function ur(e,t=z().endpoint){let n=await A(Yt(e,t));return n===null||n.trim().length===0?[]:Ul(n)}async function ui(e,t,n,r=z().endpoint){return we(async()=>{let o=await ur(e,r),{entries:i}=lr(o,n),s=i.filter(a=>!t.has(a.event.event_id));return await Wl(e,s,r),s},e)}async function Gb(e,t,n,r,o=z().endpoint){return we(async()=>{let i=await ur(e,o),{entries:s}=lr(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:Vl(d)}});return await Wl(e,a,o),a},e)}function Kb(e,t){return t===null?e:Hn(e)}async function Xb(e,t,n){let r=z().endpoint;await Yb(e,void 0,r);let o=(r??t).trim(),i=Kb(o,r),s=h=>ir(e,h,r);if(o.length===0)return;let a=await A(Yt(e,r));if(a===null||a.trim().length===0){await s({endpoint:i,queue_entries:0});return}let c=Ul(a);if(c.length===0){await s({endpoint:i,queue_entries:0});return}let{entries:d,prunedCount:l}=lr(c,n);if(d.length===0){let h=await ui(e,new Set,n,r);await s({endpoint:i,queue_entries:h.length});return}let u=d.filter(h=>Hl(h)).slice(0,ZE);if(u.length===0){let h=l>0?await ui(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)),_=P(),y={"content-type":"application/json"},g=process.env.PM_TELEMETRY_INGEST_KEY?.trim();g&&(y["x-pm-telemetry-key"]=g);try{let h=await Ml(o,y,JSON.stringify({schema_version:ar,events:u.map(w=>w.event)}));if(h<200||h>=300)throw new Error(`telemetry_flush_http_${h}`)}catch(h){let w=await Gb(e,f,_,n,r),E=h instanceof Error?k(qn(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:E});return}try{let h=await ui(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(qn(h.message),"redacted"):"telemetry_flush_failed",E=await ur(e,r).catch(()=>d);await s({endpoint:i,queue_entries:E.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:w})}}async function Jb(e){let t=wi(e);se(process.env[fe])||await di(O.dirname(t),{recursive:!0});try{return await di(t),!0}catch(n){if(typeof n!="object"||n===null||!("code"in n)||n.code!=="EEXIST")throw n}try{let n=await wl(t);return Date.now()-n.mtimeMs<vl?!1:(await hi(t,{recursive:!0,force:!0}),await di(t),!0)}catch{return!1}}function Zb(e,t){try{return Date.now()-gl(e).mtimeMs<t}catch{return!1}}function Kl(e){try{qE(e,{recursive:!0,force:!0})}catch{}}function Qb(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function e0(e){try{return ci(e),!0}catch(t){if(Qb(t)==="EEXIST"||!$(t))return!1}try{return ci(O.dirname(e),{recursive:!0}),ci(e),!0}catch{return!1}}function t0(e){if(Zb(wi(e),vl))return!1;let t=Cl(e);try{if(Date.now()-gl(t).mtimeMs<ab)return!1;Kl(t)}catch(n){if(!$(n))return!1}return e0(t)}function _i(e){Kl(Cl(e))}async function n0(e,t,n){let r=await Jb(e);if(_i(e),!r)return!1;try{await Gl(e,t,n)}finally{try{await hi(wi(e),{recursive:!0,force:!0})}catch{}}return!0}async function yl(e,t){let n=new Set;try{let{entries:r}=lr(await ur(e),t);for(let o of r.filter(Hl))n.add(`event:${o.event.event_id}`)}catch{}try{let r=await A(Gt(e));if(r!==null)for(let o of Ai(Ii(r),t).entries)vi(o.next_attempt_after)&&n.add(`span:${o.id}`)}catch{}return n}function Ci(e,t,n){if(!Lr(e)){if(Cb())return li=li.then(()=>Gl(e,t,n)),li;try{if(!t0(e))return;let r=HE(process.execPath,[Ab()],{detached:!0,stdio:"ignore",cwd:yi.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[fe]:"1"}});r.on("error",()=>{_i(e)}),r.unref()}catch{_i(e)}}}async function xx(e=me(process.cwd())){if(!G().telemetry_disabled)try{await Nr(e,async()=>{let t=se(process.env[fe]),n=!0;for(;n;){if(!(await B(e)).telemetry.enabled)return;let r=await we(()=>Ti(e),e);if(!r)return;let o=t?await yl(e,r.retentionDays):new Set;if(!await n0(e,r.endpoint,r.retentionDays)||!t)return;let i=await yl(e,r.retentionDays);n=i.size>0&&(i.size!==o.size||[...i].some(s=>!o.has(s)))}},()=>se(process.env[fe]))}catch{}}async function r0(e){if(G().telemetry_disabled||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=me(process.cwd());if(!(await B(t)).telemetry.enabled)return null;let n=e.global.noExtensions===!0||os(e.command),r=await we(async()=>{let o=await Ti(t);if(!o)return null;let{installationId:i,endpoint:s,retentionDays:a,captureLevel:c}=o,d=$l(e.pm_version),l=Fl(e.global),u=F(i,e.pm_root),f=F(i,process.cwd()),_=Lb(),y=P(),g={schema_version:ar,event_id:X.randomUUID(),event_type:"command_start",occurred_at:y,installation_id:i,session_id:dr,command:e.command,payload:Fb({captureLevel:c,context:e,pmVersion:d,sourceContext:l,pmRootHash:u,cwdHash:f,installationId:i})},h=await al(t,e.command,n);h===1&&await sr(t,g);let w=Le(e.command),E={...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:_?X.randomBytes(16).toString("hex"):void 0,otel_span_id:_?X.randomBytes(8).toString("hex"):void 0};return h<1&&or.set(E,g),E},t,gi);return r&&r.sample_rate===void 0&&Ci(t,r.endpoint,r.retention_days),r}catch{return null}}async function o0(e,t){if(!(!e||G().telemetry_disabled))try{if(!await we(async()=>{let n=await B(e.global_pm_root);if(G().telemetry_disabled||!n.telemetry.enabled||n.telemetry.installation_id!==e.installation_id)return or.delete(e),!1;let r=or.get(e),o=t.ok?e.sample_rate??1:1;if(r){if(or.delete(e),X.randomBytes(6).readUIntBE(0,6)/281474976710656>=o)return!1;r.payload.sample_rate=o,await sr(e.global_pm_root,r)}let i=P(),s=Math.max(0,Date.now()-e.started_at_ms),a=Ei(Vo({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),c=Pl({ok:t.ok,errorCode:a,errorCategory:t.error_category}),d=bi(t.exit_code,t.ok),l=t.command_resolution??tt({ok:t.ok,errorCode:a,errorCategory:c}),u=t.resolution_stage??"execute",f={schema_version:ar,event_id:X.randomUUID(),event_type:"command_finish",occurred_at:i,installation_id:e.installation_id,session_id:dr,command:e.command,payload:{...r?{sample_rate:o}:{},...jb({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 sr(e.global_pm_root,f);let _=$b(e,{...t,exit_code:d,error_code:a,error_category:c},i,s,o);return _&&await Vb(e.global_pm_root,_),!0},e.global_pm_root,gi))return;await Ci(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function i0(e){if(!G().telemetry_disabled)try{let t=me(process.cwd());if(!(await B(t)).telemetry.enabled)return;let n=await we(async()=>{let r=await Ti(t);if(!r)return null;let{installationId:o,captureLevel:i}=r,s=$l(e.pm_version),a=Fl(e.global),c=F(o,e.pm_root),d=F(o,process.cwd()),l=P(),u=Ei(Vo({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),f=e.error_category??Xt(u),_=bi(e.exit_code,!1),y=e.command.trim().length>0?e.command:"<unknown>",g=Le(y),h=e.command_resolution??tt({ok:!1,errorCode:u,errorCategory:f}),w=e.resolution_stage??"unknown",E={schema_version:ar,event_id:X.randomUUID(),event_type:"command_error",occurred_at:l,installation_id:o,session_id:dr,command:k(y,"redacted"),payload:zb({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 sr(t,E),r},t,gi);n&&await Ci(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]="52348de5-f05f-56d0-8e0e-bd7f25b8e6a6")}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 eD(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function tD(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}export{tu as a,Pr as b,ls as c,nu as d,l0 as e,cs as f,ln as g,ps as h,_s as i,ru as j,ou as k,iu as l,su as m,_0 as n,Ur as o,mu as p,h0 as q,pu as r,y0 as s,vt as t,hu as u,It as v,g0 as w,yu as x,un as y,w0 as z,qe as A,wu as B,Eu as C,I0 as D,Hr as E,A0 as F,C0 as G,At as H,x0 as I,Ss as J,ku as K,H0 as L,Du as M,Lu as N,$u as O,Pu as P,G0 as Q,ju as R,fn as S,Ct as T,qu as U,Gu as V,eS as W,ef as X,nS as Y,tf as Z,nf as _,rS as $,Wr as aa,Ns as ba,cf as ca,Br as da,df as ea,pn as fa,Ms as ga,yf as ha,Ps as ia,We as ja,le as ka,Sf as la,MS as ma,vf as na,js as oa,If as pa,Af as qa,xf as ra,Rf as sa,kf as ta,BS as ua,Nf as va,ZS as wa,Pf as xa,jf as ya,zf as za,Uf as Aa,Vf as Ba,Kr as Ca,Wf as Da,aT as Ea,cT as Fa,dT as Ga,lT as Ha,uT as Ia,fT as Ja,mT as Ka,Kf as La,Xf as Ma,Jf as Na,Zf as Oa,Qf as Pa,em as Qa,Be as Ra,ra as Sa,Rm as Ta,LT as Ua,xt as Va,Fm as Wa,la as Xa,Qr as Ya,ua as Za,HT as _a,zm as $a,Vm as ab,Hm as bb,qm as cb,Wm as db,eo as eb,av as fb,Wv as gb,_v as hb,hv as ib,yv as jb,va as kb,cp as lb,uo as mb,kv as nb,fo as ob,$t as pb,Ke as qb,Pt as rb,Yp as sb,$a as tb,Gp as ub,vI as vb,_o as wb,Pa as xb,n_ as yb,II as zb,r_ as Ab,o_ as Bb,OI as Cb,Dn as Db,Wa as Eb,go as Fb,y_ as Gb,g_ as Hb,LI as Ib,Ba as Jb,Xe as Kb,wo as Lb,bo as Mb,Pn as Nb,BI as Ob,Ro as Pb,jn as Qb,Qa as Rb,zn as Sb,ko as Tb,Oo as Ub,Do as Vb,No as Wb,ic as Xb,sc as Yb,tc as Zb,ph as _b,Qe as $b,Ht as ac,yh as bc,Hn as cc,pA as dc,G as ec,De as fc,vh as gc,yc as hc,gc as ic,wc as jc,Ch as kc,bA as lc,Oh as mc,SA as nc,TA as oc,qt as pc,jc as qc,yy as rc,Wt as sc,$A as tc,PA as uc,gy as vc,wy as wc,FA as xc,jA as yc,tt as zc,ky as Ac,Oy as Bc,Dy as Cc,Ny as Dc,Py as Ec,Fy as Fc,zy as Gc,Aw as Hc,Dd as Ic,Uw as Jc,Vw as Kc,Hw as Lc,tC as Mc,Qo as Nc,Ld as Oc,Nd as Pc,Bw as Qc,Yw as Rc,Md as Sc,pC as Tc,_C as Uc,zd as Vc,Ud as Wc,Vd as Xc,hC as Yc,Wd as Zc,eE as _c,Bd as $c,yC as ad,gC as bd,wC as cd,Yd as dd,EC as ed,nE as fd,rE as gd,oE as hd,cE as id,lE as jd,fE as kd,mE as ld,yE as md,wE as nd,EE as od,rr as pd,RE as qd,kE as rd,zE as sd,ar as td,Sl as ud,we as vd,xx as wd,r0 as xd,o0 as yd,i0 as zd,eD as Ad,tD as Bd};
125
- //# sourceMappingURL=chunk-2VH6COJE.js.map
124
+ `:"";for(let o=0;;o+=1)try{await T(Gt(e),r,{createParentDirectories:!se(process.env[fe])});return}catch(i){let s=Cl[o];if(s===void 0||!Xl(i))throw i;await Jl(s)}}async function El(e,t,n,r){return we(async()=>{let o=await A(Gt(e)),i=o===null?[]:Ii(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}=Ai(s,t);return await Zb(e,a),a.length},e)}async function Qb(e,t){let n=await A(Gt(e));if(n===null||n.trim().length===0){await sr(e,{pending_otel_spans:0},null);return}let r=Ii(n),{entries:o,prunedCount:i}=Ai(r,t),s=o.filter(h=>Ti(h.next_attempt_after)).slice(0,ob);if(s.length===0){let h=i>0?await El(e,t,new Set,new Map):o.length;await sr(e,{pending_otel_spans:h},null);return}let a=P(),c=new Set,d=new Map,l=0,u;await Promise.all(s.map(async h=>{try{let g=await jl(h.endpoint,{"content-type":"application/json"},JSON.stringify(h.payload));if(g<200||g>=300)throw new Error(`local_otel_export_http_${g}`);c.add(h.id),l+=1}catch(g){u=g instanceof Error?O(qn(g.message),"redacted"):"local_otel_export_failed";let y=h.attempts+1;d.set(h.id,{attempts:y,next_attempt_after:Wl(y)})}}));let f=await El(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 sr(e,_,null)}async function Zl(e,t,n){try{await r0(e,t,n)}catch{}try{await Qb(e,n)}catch{}}async function e0(e,t=fb,n=z().endpoint){try{let r=Db(e),o=await ZE(r,{withFileTypes:!0}),i=Date.now(),s=new Set([Ht("events.jsonl",n),Ht("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-mb: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=k.join(r,c.name);(await vl(l)).mtimeMs<d&&await yi(l,{force:!0})}))}catch{}}async function we(e,t=me(process.cwd()),n=5e3){let r=yl.catch(()=>{}).then(()=>rs(async()=>{let o=await ve(t,"telemetry-queue",60,"telemetry",!1,!1,n,{createParentDirectories:!se(process.env[fe])});try{return an(t),await e()}finally{await o()}}));return yl=r.catch(()=>{}),r}async function fr(e,t=z().endpoint){let n=await A(Yt(e,t));return n===null||n.trim().length===0?[]:Bl(n)}async function ui(e,t,n,r=z().endpoint){return we(async()=>{let o=await fr(e,r),{entries:i}=ur(o,n),s=i.filter(a=>!t.has(a.event.event_id));return await Kl(e,s,r),s},e)}async function t0(e,t,n,r,o=z().endpoint){return we(async()=>{let i=await fr(e,o),{entries:s}=ur(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:Wl(d)}});return await Kl(e,a,o),a},e)}function n0(e,t){return t===null?e:Hn(e)}async function r0(e,t,n){let r=z().endpoint;await e0(e,void 0,r);let o=(r??t).trim(),i=n0(o,r),s=y=>sr(e,y,r);if(o.length===0)return;let a=await A(Yt(e,r));if(a===null||a.trim().length===0){await s({endpoint:i,queue_entries:0});return}let c=Bl(a);if(c.length===0){await s({endpoint:i,queue_entries:0});return}let{entries:d,prunedCount:l}=ur(c,n);if(d.length===0){let y=await ui(e,new Set,n,r);await s({endpoint:i,queue_entries:y.length});return}let u=d.filter(y=>Yl(y)).slice(0,ib);if(u.length===0){let y=l>0?await ui(e,new Set,n,r):d;await s({endpoint:i,queue_entries:y.length});return}let f=new Set(u.map(y=>y.event.event_id)),_=P(),h={"content-type":"application/json"},g=process.env.PM_TELEMETRY_INGEST_KEY?.trim();g&&(h["x-pm-telemetry-key"]=g);try{let y=await jl(o,h,JSON.stringify({schema_version:cr,events:u.map(w=>w.event)}));if(y<200||y>=300)throw new Error(`telemetry_flush_http_${y}`)}catch(y){let w=await t0(e,f,_,n,r),E=y instanceof Error?O(qn(y.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:E});return}try{let y=await ui(e,f,n,r);await s({endpoint:i,queue_entries:y.length,last_attempted_flush_at:_,last_successful_flush_at:_,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(y){let w=y instanceof Error?O(qn(y.message),"redacted"):"telemetry_flush_failed",E=await fr(e,r).catch(()=>d);await s({endpoint:i,queue_entries:E.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:w})}}async function o0(e){let t=wi(e);se(process.env[fe])||await di(k.dirname(t),{recursive:!0});try{return await di(t),!0}catch(n){if(typeof n!="object"||n===null||!("code"in n)||n.code!=="EEXIST")throw n}try{let n=await vl(t);return Date.now()-n.mtimeMs<Rl?!1:(await yi(t,{recursive:!0,force:!0}),await di(t),!0)}catch{return!1}}function i0(e,t){try{return Date.now()-Sl(e).mtimeMs<t}catch{return!1}}function Ql(e){try{JE(e,{recursive:!0,force:!0})}catch{}}function s0(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function a0(e){try{return ci(e),!0}catch(t){if(s0(t)==="EEXIST"||!$(t))return!1}try{return ci(k.dirname(e),{recursive:!0}),ci(e),!0}catch{return!1}}function c0(e){if(i0(wi(e),Rl))return!1;let t=kl(e);try{if(Date.now()-Sl(t).mtimeMs<pb)return!1;Ql(t)}catch(n){if(!$(n))return!1}return a0(t)}function _i(e){Ql(kl(e))}async function d0(e,t,n){let r=await o0(e);if(_i(e),!r)return!1;try{await Zl(e,t,n)}finally{try{await yi(wi(e),{recursive:!0,force:!0})}catch{}}return!0}async function bl(e,t){let n=new Set;try{let{entries:r}=ur(await fr(e),t);for(let o of r.filter(Yl))n.add(`event:${o.event.event_id}`)}catch{}try{let r=await A(Gt(e));if(r!==null)for(let o of Ai(Ii(r),t).entries)Ti(o.next_attempt_after)&&n.add(`span:${o.id}`)}catch{}return n}function Ci(e,t,n){if(!Mr(e)){if(Lb())return li=li.then(()=>Zl(e,t,n)),li;try{if(!c0(e))return;let r=XE(process.execPath,[Nb()],{detached:!0,stdio:"ignore",cwd:hi.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[fe]:"1"}});r.on("error",()=>{_i(e)}),r.unref()}catch{_i(e)}}}async function $R(e=me(process.cwd())){if(!G().telemetry_disabled)try{await Lr(e,async()=>{let t=se(process.env[fe]),n=!0;for(;n;){if(!(await W(e)).telemetry.enabled)return;let r=await we(()=>vi(e),e);if(!r)return;let o=t?await bl(e,r.retentionDays):new Set;if(!await d0(e,r.endpoint,r.retentionDays)||!t)return;let i=await bl(e,r.retentionDays);n=i.size>0&&(i.size!==o.size||[...i].some(s=>!o.has(s)))}},()=>se(process.env[fe]))}catch{}}async function l0(e){if(G().telemetry_disabled||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=me(process.cwd());if(!(await W(t)).telemetry.enabled)return null;let n=e.global.noExtensions===!0||os(e.command),r=await we(async()=>{let o=await vi(t);if(!o)return null;let{installationId:i,endpoint:s,retentionDays:a,captureLevel:c}=o,d=zl(e.pm_version),l=Vl(e.global),u=F(i,e.pm_root),f=F(i,process.cwd()),_=Ub(),h=P(),g={schema_version:cr,event_id:X.randomUUID(),event_type:"command_start",occurred_at:h,installation_id:i,session_id:lr,command:e.command,payload:Bb({captureLevel:c,context:e,pmVersion:d,sourceContext:l,pmRootHash:u,cwdHash:f,installationId:i})},y=await ul(t,e.command,n);y===1&&await ar(t,g);let w=Le(e.command),E={...y<1?{sample_rate:y}:{},started_at:h,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:_?X.randomBytes(16).toString("hex"):void 0,otel_span_id:_?X.randomBytes(8).toString("hex"):void 0};return y<1&&ir.set(E,g),E},t,gi);return r&&r.sample_rate===void 0&&Ci(t,r.endpoint,r.retention_days),r}catch{return null}}async function u0(e,t){if(!(!e||G().telemetry_disabled))try{if(!await we(async()=>{let n=await W(e.global_pm_root);if(G().telemetry_disabled||!n.telemetry.enabled||n.telemetry.installation_id!==e.installation_id)return ir.delete(e),!1;let r=ir.get(e),o=t.ok?e.sample_rate??1:1;if(r){if(ir.delete(e),X.randomBytes(6).readUIntBE(0,6)/281474976710656>=o)return!1;r.payload.sample_rate=o,await ar(e.global_pm_root,r)}let i=P(),s=Math.max(0,Date.now()-e.started_at_ms),a=Ei(Ho({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),c=Ul({ok:t.ok,errorCode:a,errorCategory:t.error_category}),d=bi(t.exit_code,t.ok),l=t.command_resolution??tt({ok:t.ok,errorCode:a,errorCategory:c}),u=t.resolution_stage??"execute",f={schema_version:cr,event_id:X.randomUUID(),event_type:"command_finish",occurred_at:i,installation_id:e.installation_id,session_id:lr,command:e.command,payload:{...r?{sample_rate:o}:{},...Wb({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 ar(e.global_pm_root,f);let _=Hb(e,{...t,exit_code:d,error_code:a,error_category:c},i,s,o);return _&&await Kb(e.global_pm_root,_),!0},e.global_pm_root,gi))return;await Ci(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function f0(e){if(!G().telemetry_disabled)try{let t=me(process.cwd());if(!(await W(t)).telemetry.enabled)return;let n=await we(async()=>{let r=await vi(t);if(!r)return null;let{installationId:o,captureLevel:i}=r,s=zl(e.pm_version),a=Vl(e.global),c=F(o,e.pm_root),d=F(o,process.cwd()),l=P(),u=Ei(Ho({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),f=e.error_category??Xt(u),_=bi(e.exit_code,!1),h=e.command.trim().length>0?e.command:"<unknown>",g=Le(h),y=e.command_resolution??tt({ok:!1,errorCode:u,errorCategory:f}),w=e.resolution_stage??"unknown",E={schema_version:cr,event_id:X.randomUUID(),event_type:"command_error",occurred_at:l,installation_id:o,session_id:lr,command:O(h,"redacted"),payload:Yb({captureLevel:i,pmVersion:s,sourceContext:a,command:h,commandTaxonomy:g,commandResolution:y,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 ar(t,E),r},t,gi);n&&await Ci(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]="52348de5-f05f-56d0-8e0e-bd7f25b8e6a6")}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 cD(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function dD(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}export{iu as a,Fr as b,ls as c,su as d,h0 as e,cs as f,ln as g,ps as h,_s as i,au as j,cu as k,du as l,lu as m,S0 as n,Vr as o,hu as p,v0 as q,gu as r,T0 as s,Tt as t,Eu as u,It as v,I0 as w,bu as x,un as y,A0 as z,qe as A,vu as B,Tu as C,D0 as D,qr as E,N0 as F,L0 as G,At as H,M0 as I,Ss as J,Lu as K,X0 as L,$u as M,Fu as N,zu as O,Uu as P,tS as Q,Hu as R,fn as S,Ct as T,Gu as U,Zu as V,aS as W,of as X,dS as Y,sf as Z,af as _,lS as $,Wr as aa,Ns as ba,ff as ca,Yr as da,mf as ea,pn as fa,Ms as ga,bf as ha,Ps as ia,Be as ja,le as ka,Af as la,VS as ma,Rf as na,js as oa,xf as pa,Of as qa,Df as ra,Nf as sa,Lf as ta,QS as ua,Pf as va,iv as wa,Uf as xa,Hf as ya,qf as za,Bf as Aa,Wf as Ba,Xr as Ca,Kf as Da,pv as Ea,_v as Fa,yv as Ga,hv as Ha,gv as Ia,wv as Ja,Ev as Ka,Qf as La,em as Ma,tm as Na,nm as Oa,rm as Pa,om as Qa,We as Ra,ra as Sa,Nm as Ta,Uv as Ua,Rt as Va,Vm as Wa,la as Xa,eo as Ya,ua as Za,Xv as _a,qm as $a,Wm as ab,Ym as bb,Gm as cb,Km as db,to as eb,pT as fb,ZT as gb,ST as hb,vT as ib,TT as jb,Ta as kb,fp as lb,fo as mb,PT as nb,mo as ob,$t as pb,Ke as qb,Pt as rb,Jp as sb,$a as tb,Zp as ub,kI as vb,yo as wb,Pa as xb,s_ as yb,DI as zb,a_ as Ab,c_ as Bb,FI as Cb,Dn as Db,Ba as Eb,wo as Fb,b_ as Gb,S_ as Hb,UI as Ib,Wa as Jb,Xe as Kb,Eo as Lb,So as Mb,Pn as Nb,QI as Ob,Oo as Pb,jn as Qb,Qa as Rb,zn as Sb,ko as Tb,Do as Ub,No as Vb,Lo as Wb,ic as Xb,sc as Yb,tc as Zb,gy as _b,Qe as $b,Ht as ac,by as bc,Hn as cc,bA as dc,G as ec,De as fc,Ry as gc,hc,gc as ic,wc as jc,ky as kc,RA as lc,My as mc,xA as nc,OA as oc,qt as pc,jc as qc,bh as rc,Bt as sc,HA as tc,qA as uc,Sh as vc,vh as wc,BA as xc,WA as yc,tt as zc,Lh as Ac,Mh as Bc,$h as Cc,Ph as Dc,Uh as Ec,Vh as Fc,qh as Gc,Ow as Hc,$d as Ic,Bw as Jc,Cd as Kc,Ww as Lc,cC as Mc,Kw as Nc,Xw as Oc,dC as Pc,Qo as Qc,Fd as Rc,Pd as Sc,Qw as Tc,eE as Uc,jd as Vc,SC as Wc,vC as Xc,qd as Yc,Bd as Zc,Wd as _c,TC as $c,Kd as ad,aE as bd,Xd as cd,IC as dd,AC as ed,CC as fd,Jd as gd,RC as hd,dE as id,lE as jd,uE as kd,_E as ld,hE as md,wE as nd,EE as od,TE as pd,AE as qd,CE as rd,or as sd,$E as td,PE as ud,YE as vd,cr as wd,Al as xd,we as yd,$R as zd,l0 as Ad,u0 as Bd,f0 as Cd,cD as Dd,dD as Ed};
125
+ //# sourceMappingURL=chunk-723PMYNX.js.map