@unbrained/pm-cli 2026.11.15 → 2026.11.16
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/help-content.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-TESRFVGF.js → chunk-2D26HRXB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-VWKLTHYQ.js → chunk-2WNORBVN.js} +36 -25
- package/dist/cli-bundle/chunks/{chunk-J6L3Q5J4.js → chunk-4I7YG3VZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QZNDEZYI.js → chunk-4WIVCOA7.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-A3WCP4TU.js +6 -0
- package/dist/cli-bundle/chunks/chunk-AB5S6TWE.js +124 -0
- package/dist/cli-bundle/chunks/{chunk-KLWGIEDC.js → chunk-BV7J3LRH.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-GCSKHCYK.js → chunk-DZWRNL6R.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KSLPRST2.js → chunk-E4BQRZF2.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-ERD2RYWM.js +31 -0
- package/dist/cli-bundle/chunks/chunk-F7P42FL5.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-E4B2HWH7.js → chunk-FZ4XWWLO.js} +23 -23
- package/dist/cli-bundle/chunks/{chunk-7AODVNHX.js → chunk-I3T2FVUA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-PMIGRSNZ.js → chunk-IGEBFNWE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YLPZE2TK.js → chunk-IYICNCK2.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-J257NZRD.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-Q6GBRK27.js → chunk-JD3XWF66.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FSE624WQ.js → chunk-JLHD7OQ2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DBUBX4DL.js → chunk-KGOGLKL2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZWUS65LN.js → chunk-LC4DJVXR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LC6DL446.js → chunk-NHNM3GIP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZVDXGAYV.js → chunk-NYN5OR2T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6UTBX62V.js → chunk-OFZQEQ6X.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GAFALSR2.js → chunk-QGL5IAP4.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-HMVZSXB4.js → chunk-R24NZ2TB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-S5UXBECQ.js → chunk-VJLZHOTP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YJNY5MKP.js → chunk-VO2HSB5F.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-42Y2CSEQ.js → indexed-receipt-blobs-HNLN6UXH.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-JCEDTAVX.js → item-revision-PSOL5I4H.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-55QTCU2M.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-IQHBRFAJ.js → mutation-actor-BDBBH3ZS.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-DF6BFGG6.js → mutation-admission-WUN7JYVJ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-DNKPQB76.js → register-list-query-AESCVO6H.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-WVTDFLEF.js → register-mutation-SKCEP5QU.js} +2 -2
- package/dist/cli-bundle/chunks/register-operations-ZT4OYCF3.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-2RTG3LII.js → register-setup-JVWNS2TY.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-W5ULPKIE.js → settlement-hook-MVVVUIVZ.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-YFNK7U26.js → stage-RMU3JAWM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YZUBG4W2.js → chunk-3WVMEA2A.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-CZZKAGHE.js → chunk-5UVJOAUP.js} +6 -6
- package/dist/cli-bundle/focused-chunks/{chunk-EALGFJRP.js → chunk-5WQ3LNUK.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-6E4X7MQA.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JE3MFEQZ.js → chunk-7SEPCQV2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XQZKGTZV.js → chunk-7XHE335U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-52H6AELE.js → chunk-BEHIMEV2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JXA77YIV.js → chunk-CZFZCSOX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-W2KIQ7RF.js → chunk-DFBHW7HP.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-WGYR3X6O.js → chunk-DZMP3VYQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-HHMMIHZP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LSWUTTE6.js → chunk-HPC2M6JD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2UQFFVQK.js → chunk-HR5FEUUL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-S6GTALM4.js → chunk-J7ESCE7M.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-KRNF3WTC.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DXMQ32EH.js → chunk-KWZLY35A.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-Z6HCQYSW.js → chunk-M4IA4LC6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YTNUUEY6.js → chunk-NASE6JC2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ONM2R32I.js +65 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QXOFSZR6.js → chunk-PDXSMSO5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BSY6FZ3Y.js → chunk-PEL4SQXV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-DRBXOAGY.js → chunk-QJ647CQE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SFATIM77.js +12 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7GCAZJT4.js → chunk-UBBTBNUY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UPUIDGNJ.js → chunk-ZCN35TCK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZSQ2FT22.js +44 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-LSBWMXKS.js → indexed-receipt-blobs-ADMQXF3N.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-revision-YO7YGQYE.js → item-revision-GNKYO6GZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-7A3Q4CAJ.js → item-transaction-AUUQHR5Z.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-UQHBNHOF.js → mutation-actor-OBRD7HFZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-G565NLPE.js → mutation-admission-6TX3EOJX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-UXN76GMA.js → settlement-hook-5U2M75BY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-F3YJGNRK.js → stage-LERF2YJU.js} +2 -2
- package/dist/cli-bundle/main.js +6 -6
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/shared/errors.d.ts +22 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/item-store.d.ts +15 -4
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/telemetry/policy.d.ts +21 -2
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/completion/bash.js +1 -1
- package/dist/sdk/completion/fish.js +2 -1
- package/dist/sdk/completion/zsh.js +12 -2
- package/dist/sdk/flag-invocation-contracts.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/governance/in-progress-work-health.d.ts +49 -0
- package/dist/sdk/governance/in-progress-work-health.js +2 -0
- package/dist/sdk/governance/stale-work.d.ts +143 -2
- package/dist/sdk/governance/stale-work.js +1 -1
- package/dist/sdk/governance.d.ts +1 -1
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/claim.d.ts +46 -3
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/ownership-source.d.ts +32 -0
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.d.ts +5 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/next.d.ts +19 -3
- package/dist/sdk/query/next.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/docs/AGENT_GUIDE.md +2 -0
- package/docs/COMMANDS.md +22 -0
- package/docs/CONFIGURATION.md +20 -7
- package/docs/LIFECYCLE_COMMANDS.md +8 -1
- package/docs/MUTATION_INTEGRITY.md +79 -1
- package/docs/SDK.md +28 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
- package/marketplace.json +1 -1
- package/node_modules/commander/Readme.md +6 -32
- package/node_modules/commander/index.js +1 -1
- package/node_modules/commander/lib/command.js +22 -9
- package/node_modules/commander/lib/help.js +6 -2
- package/node_modules/commander/lib/option.js +1 -1
- package/node_modules/commander/package.json +2 -1
- package/node_modules/commander/typings/index.d.ts +6 -3
- package/node_modules/semver/classes/range.js +2 -2
- package/node_modules/semver/internal/constants.js +30 -0
- package/node_modules/semver/internal/trim-comparator-whitespace.js +438 -0
- package/node_modules/semver/package.json +1 -1
- package/package.json +3 -3
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-ASGAELBQ.js +0 -9
- package/dist/cli-bundle/chunks/chunk-E74OMFBZ.js +0 -6
- package/dist/cli-bundle/chunks/chunk-FYOIH56R.js +0 -20
- package/dist/cli-bundle/chunks/chunk-IXV5UM4U.js +0 -31
- package/dist/cli-bundle/chunks/chunk-NAX554KY.js +0 -124
- package/dist/cli-bundle/chunks/item-transaction-BSMGKZ4S.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-NR5MTT5T.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-63FM3TIG.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-FK2X6MJY.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-JRRHN2PZ.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-LQZ5F6LE.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-RMCODWHZ.js +0 -65
- package/dist/cli-bundle/focused-chunks/chunk-WVYXR3YX.js +0 -2
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
import{Aa as Hi,Gd as Sr,Hd as vr,I as wr,J as ji,Ld as Bi,Od as rn,P as br,Pd as Tr,Q as zi,Qd as Ir,Rd as Wi,Td as yt,U as Er,Wd as ze,Xd as Y,Yd as gt,a as Ti,aa as Ui,b as Ii,be as Yi,e as Ci,he as on,ia as ce,id as en,j as Oi,ja as mt,ka as je,md as tn,nd as nn,od as pt,pd as qi,q as ut,ta as Vi,va as ft,wd as _t,yd as ht}from"./chunk-KLWGIEDC.js";import{Aa as lr,Ab as Fe,Ba as ur,Bb as S,Ca as xi,Ce as U,Da as mr,Db as Di,Ea as it,Fe as Zt,Gd as Ee,Ge as Se,Hd as _r,He as gr,Ja as Gt,Jb as Ni,Lc as Li,Na as fr,Nb as Mi,Oa as me,Ob as $,Oe as Qt,Pa as we,Qa as $e,Ra as st,Sa as te,Vc as Xt,Y as ot,Zb as be,_d as Pi,ae as hr,b as nt,c as gi,e as wi,fb as q,ge as yr,hb as Ri,he as dt,i as bi,ie as $i,kc as ct,lc as pr,m as Ei,n as Si,nb as ki,qb as Kt,re as fe,u as vi,ve as Fi,xb as E,ye as Jt,zb as at,ze as lt}from"./chunk-KSLPRST2.js";import{A as f,B as Yt,C as p,D as Ai,E as j,G as P,H as C,K as T,L as dr,M as rt,m as ar,u as ee,z as cr}from"./chunk-LC6DL446.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 el=new Set(["rename-type","rename-field","remap-status",...wi]);function tl(e,t){if(t&&!el.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.`,f.USAGE,{code:"invalid_argument_value",examples:["pm schema rename-type Spike --to Experiment --dry-run"]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8dd367eb-617e-5645-8f8a-57862f8385f7")}catch{}})();var sn=new WeakSet,Cr=new WeakMap,Ki=new WeakSet;function Ar(e){return Ki.add(e),e}function xr(e){return Ki.has(e)}function wt(e){sn.add(e);for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let r=[...n];Reflect.set(e,t,r),sn.add(r)}return e}function Xi(e,t){return sn.has(e)||t!==void 0&&Cr.get(e)?.has(t)===!0}function nl(e,t){let n=new Set(t);Cr.set(e,n);for(let r of n){let o=Reflect.get(e,r);if(!Array.isArray(o))continue;let i=[...o];Reflect.set(e,r,i),sn.add(i)}return e}function Ji(e,t){if(xr(e)&&Ar(t),Xi(e))return wt(t);let n=Cr.get(e);return n?nl(t,n):t}function Yw(e){return Xi(e)?"sdk":"cli"}function Gi(e,t){return e==="cli"?`--${t}`:t.replace(/-([a-z])/gu,(n,r)=>r.toUpperCase())}function bt(e){return`Pass unset: ["${e}"] to clear it`}function an(e,t,n=""){return e==="cli"?`--${t} must not be empty${n}`:`${Gi("sdk",t)} must not be empty. ${bt(t)}, or omit ${Gi("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="-",Qi=/^[A-Za-z0-9_.-]+$/u,Rr=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function es(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 ts(e){let t=e.trim();if(t==="")return[];let n=(al(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 ns(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let n of e)if(typeof n=="string")for(let r of ts(n))t.push(r);return Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r))}function rs(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function rl(e){return typeof e!="string"?[]:e.split(";").map(t=>t.trim()).filter(Boolean)}function ol(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',f.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 il(e,t){let n=rs(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 ns(t))r.add(o);return Array.from(r).sort((o,i)=>o.localeCompare(i))}function sl(e,t){let n=Array.from(new Set(rs(e))).sort((o,i)=>o.localeCompare(i));if(!t||t.length===0)return n;let r=new Set(ns(t));return r.size===0?n:n.filter(o=>!r.has(o))}function al(e){if(!e.startsWith("["))return null;let t;try{t=JSON.parse(e)}catch{return null}return t.map(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):"").filter(n=>n.length>0)}function kr(e){return e.replace(/\r\n/g,`
|
|
3
|
-
`)}function os(e){let t=kr(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
|
|
4
|
-
`);return n.length<2||n.at(-1)?.trim()!=="```"?e:n.slice(1,-1).join(`
|
|
5
|
-
`)}function is(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 cl(e){return is(e).map(t=>t.text)}function Zw(e){return is(e.trim()).map(({text:t,raw:n})=>{let r=ss(t),o=t.slice(0,Math.max(r,0)).trim();return Qi.test(o)?{text:t,raw:n,key:o,value:Or(t.slice(r+1).trim())}:{text:t,raw:n}})}function Or(e){let t=e.trim();if(t.startsWith('"')&&t.endsWith('"')){try{let n=JSON.parse(t);if(typeof n=="string")return n}catch{}return t.slice(1,-1).replace(/\\"/g,'"')}return e}function ss(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 dl(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 Zi(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=dl(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 as(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.`,f.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 ll(e,t){let n=os(e).trim();if(n.length===0||!n.includes(`
|
|
6
|
-
`)&&!n.startsWith("-")&&!n.startsWith("*")&&!n.startsWith("+"))return null;let r={},o,i=kr(n).split(`
|
|
7
|
-
`).map(s=>s.trim()).filter(s=>s.length>0);for(let s of i){let a=s.match(/^(?:[-*+]\s+)?([a-zA-Z0-9_.-]+)\s*(=|:)\s*(.*)$/);if(a){let c=a[1].trim();as(r,c,e,t),r[c]=Or(a[3].trim()),o=c;continue}if(o&&Rr.has(o.toLowerCase())){r[o]=`${r[o]}
|
|
8
|
-
${s}`;continue}return null}return r}function Dr(e,t){let n=os(e).trim();if(!n)throw new p(`${t} cannot be empty`,f.USAGE);let r=ll(n,t);if(r)return r;let o={},i,s=cl(n);for(let a of s){let c=ss(a),d=a.slice(0,Math.max(c,0)).trim();if(d!==""&&i!==void 0&&Rr.has(i.toLowerCase())&&!Qi.test(d)){o[i]=`${o[i]},${a}`;continue}if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new p(Zi(e,t),f.USAGE);let u=Or(a.slice(c+1).trim());as(o,l,e,t),o[l]=u,i=l;continue}if(i&&Rr.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new p(Zi(e,t),f.USAGE)}return o}var ul=/^[A-Za-z]:[\\/]/,ml=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function fl(e){let t=e.trim();return ul.test(t)?!1:ml.test(t)}function Qw(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.`,f.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 pl(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(", ")}.`,f.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.`,f.USAGE);e[s]=e[i],delete e[i]}}}async function _l(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).`,f.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((t,n)=>{let r="";process.stdin.on("data",o=>{r+=o}),process.stdin.on("end",()=>{t(kr(r))}),process.stdin.on("error",o=>{n(o)})})}var ve=Symbol("all-mutation-stdin-fields"),G=new WeakMap;function eb(e){return xr(e)?e:wt(Et({...e}))}function Et(e){return G.set(e,ve),e}function hl(e,t){let n=G.get(e);return n===ve||G.set(e,new Set([...n??[],...t])),e}function St(e,t){Ji(e,t);let n=G.get(e);return n===void 0||G.set(t,n===ve?n:new Set(n)),t}function tb(e,t){let n=G.get(e),r=G.get(t);return n===void 0||r===ve?t:n===ve?(G.set(t,n),t):(G.set(t,new Set([...r??[],...n])),t)}function yl(e){return G.get(e)!==ve}function cn(e,t){let n=G.get(e);return n!==ve&&!n?.has(t)}function gl(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`,f.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}.`,f.USAGE);t=n.optionName}}}async function nb(e,t,n){let r=e,o=[...t,...n];gl(o.map(([a,c])=>({value:r[a],optionName:c,resolveToken:cn(e,a)})));let i=Ue(),s={...r};for(let[a,c]of t)s[a]=await i.resolveValue(r[a],c,cn(e,a));for(let[a,c]of n)s[a]=await i.resolveList(r[a],c,cn(e,a));return Et(St(e,s))}function Ue(){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}.`,f.USAGE);return t=r,e||(e=_l(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`,f.USAGE);let a=await n(o),c=[...r];return c[s[0]]=a,c}}}function wl(e,t){let n=Number(e);if(!Number.isFinite(n))throw new p(`Invalid ${t} value "${e}"`,f.USAGE);return n}function bl(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.`,f.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 cb(e){try{return e()}catch(t){throw!(t instanceof p)||t.exitCode!==f.USAGE?t:new p(`${t.message} No changes were made.`,f.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 El(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 Sl(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=El(e,n);if(o===void 0)return;n=o;continue}if("<>()`".includes(r))return;n+=1}return n===e.length?n:void 0}function Nr(e,t){let n=t;for(;n<e.length;){if(/\s/u.test(e[n])){n+=1;continue}if(e[n]!=="#")return n;let r=e.indexOf(`
|
|
9
|
-
`,n);if(r<0)return e.length;n=r+1}return n}function vl(e,t){let n=Nr(e,t),r=e[n];return r===void 0||!";&|".includes(r)?n:(n+=1,r!==";"&&e[n]===r&&(n+=1),Nr(e,n))}function Tl(e){let t=e.trim(),n=Nr(t,0);if(t.length===0)return!1;for(;n<t.length;){if(!/[A-Za-z_]/u.test(t[n]))return!1;let r=n+1;for(;r<t.length&&/[A-Za-z0-9_]/u.test(t[r]);)r+=1;if(t[r]!=="=")return!1;let o=Sl(t,r+1);if(o===void 0)return!1;n=vl(t,o)}return!0}function Mr(e){if(!(e===void 0||!Tl(e)))throw new p("Linked-test command contains only variable assignments or comments and has no executable command.",f.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 db(e){if(Mr(e.command),!(e.pm_context_mode!=="none"||e.workspace_context_mode==="isolated"||e.workspace_context_mode==="snapshot"))throw new p("pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.",f.USAGE,{code:"linked_test_context_invalid",required:"Set workspace_context_mode to isolated or snapshot when pm_context_mode is none.",examples:[q(["test","<id>","--add-json",JSON.stringify({command:e.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}function lb(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}var vt=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note","phase"],Il=new Set(vt);function ub(e){return es(e,vt)}function cs(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(!Il.has(s)){r.push(o);continue}if(Object.hasOwn(n,s))throw new p(`${t} provides key "${o}" more than once after case normalization`,f.USAGE);n[s]=i}if(r.length>0)throw new p(`${t} does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${vt.join(", ")}.`,f.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`,f.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 ds(e){if(!e?.trim())return!1;try{return Mr(e.trim()),!0}catch{return!1}}function Cl(e){try{let{command:t,...n}=cs(Dr(e,"--add"),"--add");return ds(t)?["--add",e]:["command=<actual command>",...Object.entries(n).map(([r,o])=>`${r}=${JSON.stringify(o)}`)].join(",")}catch{return}}function Al(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Ii.has(n)&&n!=="--all")continue;let r=n.split("=",1)[0];if(!Ti.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 xl(e,t){let n=Ci(t);if(n===void 0)return;let r=vi(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("-"))&&Al(t.slice(o+2)))return{idIndex:o,value:s}}function Rl(e,t){let n=/^[A-Za-z_][A-Za-z0-9_]*=/u.exec(t)?.[0];if(e==="test")return n?["command=","cmd="].includes(n)?Cl(t):vt.includes(n.slice(0,-1))?`command=<actual command>,${t}`:void 0:ds(t)?["--add-json",JSON.stringify({command:t})]:"command=<actual command>";if(!(n&&n!=="path="))return["--add",n?t:`path=${JSON.stringify(t)}`]}function kl(e,t){if(e===void 0||!["files","docs","test"].includes(e))return;let n=xl(e,t);if(!n)return;let{idIndex:r,value:o}=n,i=t[r],s=Rl(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 Ol}from"node:fs/promises";import ls 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 Cb(e){if(e!==void 0){if(typeof e!="string")throw new p("--rollback requires a non-empty checkpoint ID string",f.USAGE);return us(e)}}function us(e){let t=e.trim();if(!t)throw new p("--rollback requires a non-empty checkpoint ID",f.USAGE);if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new p("--rollback checkpoint ID must match [a-zA-Z0-9._-]+",f.USAGE);return t}function Dl(e,t){let n=t.replace(/[-:.TZ]/g,"").slice(0,14),r=Math.random().toString(36).slice(2,8);return`${e}-${n}-${r}`}function Nl(e,t){return ls.join(e,"checkpoints",t)}function ms(e,t,n){return ls.join(Nl(e,t),`${n}.json`)}async function Ml(e,t,n,r){let o=ms(e,t,n),i=`${JSON.stringify(r,null,2)}
|
|
10
|
-
`;if(!await Oi(o,i)&&await C(o)!==i)throw new p(`Checkpoint ${n} already exists with different contents; use a new checkpoint ID.`,f.CONFLICT);return o}function Ll(e,t){if(!Array.isArray(e.items))throw new p(`Checkpoint ${t} is missing items`,f.GENERIC_FAILURE);return e.items.map(n=>{if(!n||typeof n!="object")throw new p(`Checkpoint ${t} contains an invalid item entry`,f.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`,f.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`,f.GENERIC_FAILURE);return{id:r.id.trim(),target_updated_at:r.target_updated_at.trim()}})}async function Pl(e,t,n,r){let o=us(n),i=ms(e,t,o);if(!await j(i))throw new p(`Checkpoint ${o} not found`,f.NOT_FOUND);let s=await Ol(i,"utf8"),a;try{a=JSON.parse(s)}catch(l){throw new p(`Checkpoint ${o} contains invalid JSON: ${S(l)}`,f.GENERIC_FAILURE)}if(!a||typeof a!="object")throw new p(`Checkpoint ${o} is invalid`,f.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.`,f.GENERIC_FAILURE);let d=Ll(c,o);return{record:c,items:d,path:i,id:typeof c.id=="string"?c.id:o,created_at:typeof c.created_at=="string"?c.created_at:$(),author:typeof c.author=="string"?c.author:"unknown"}}async function $l(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 Ob=[{code:"unknown_lifecycle_action"}];function Fl(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Math.floor(n.length/3);return t.map(o=>({candidate:o,distance:be(n,o.toLowerCase(),r)??Number.POSITIVE_INFINITY})).filter(({distance:o})=>Number.isFinite(o)).sort((o,i)=>o.distance!==i.distance?o.distance-i.distance:o.candidate.localeCompare(i.candidate))[0]?.candidate}function fs(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function jl(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(m=>m.trim()))].filter(Boolean).sort((m,_)=>m.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:Fl(r,o),l=fs([...i,r,...s]),u=e.retry_command??(d?fs([...i,d,...s]):void 0);return new p(`Unknown ${a} ${c} "${r}". Allowed: ${o.join(", ")}${e.message_suffix??""}`,e.exit_code??f.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:r,examples:[...u?[u]:[],...e.examples??[],`pm ${t} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:l,allowed_values:o,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4e02447f-3fb0-5f7c-9512-be2b348fd082")}catch{}})();var Te=new Set(ar),dn=Object.freeze({get size(){return Te.size},has(e){return Te.has(e)},entries(){return Te.entries()},keys(){return Te.keys()},values(){return Te.values()},forEach(e,t){Te.forEach(n=>e.call(t,n,n,dn))},[Symbol.iterator](){return Te.values()}});function ps(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function _s(e){return typeof e!="string"?null:Li(e)}function zl(e){try{return structuredClone(e)}catch{return e}}function Ul(e){let t=e.trim(),n=t.indexOf("=");if(n<=0)throw new p(`--field entries must use name=value syntax, received: ${e}`,f.USAGE);let r=t.slice(0,n).trim(),o=t.slice(n+1);return{key:r,value:o}}function Vl(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}`,f.USAGE)}function Hl(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`,f.USAGE);let o=Number(r);if(!Number.isFinite(o))throw new p(`--field ${e}=... must be a number`,f.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`,f.USAGE)}return t==="string_array"?n.split(/[\n,|]/u).map(r=>r.trim()).filter(r=>r.length>0):Vl(n,e,t)}function Lr(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=ps(r.name),i=_s(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}`,f.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 hs(e){if(dn.has(e))throw new p(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...dn].sort((t,n)=>t.localeCompare(n)).join(", ")}.`,f.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function Tt(e){return[...Lr(e).keys()].sort((t,n)=>t.localeCompare(n))}function ql(e,t,n,r){if(!e||e.length===0)return{};let o=Lr(t),i={};for(let s of e){let{key:a,value:c}=Ul(s),d=o.get(a);if(!d)throw Bl(a,o,n,r);hs(d.name),i[d.name]=Hl(d.name,d.type,c)}return i}function Bl(e,t,n,r){if(dn.has(e)){let s=n?.(e)??{recovery:{provided_fields:[e]},nextSteps:["Core metadata has no generic --field mutation path. Use the owning lifecycle, evidence, or importer API; inspect pm update <id> --help for declared mutation flags."]};return new p(`--field ${e} is a core item field, not an extension field`,f.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}`,f.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`,f.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 Wl(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 Yl(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function Gl(e,t,n={}){if(t){Lr(t);for(let r of t.item_fields)for(let o of r.fields){let i=ps(o.name);if(!i)continue;hs(i),!(i in e)&&!n.skipDefaultFields?.has(i)&&Object.prototype.hasOwnProperty.call(o,"default")&&(e[i]=zl(o.default));let s=e[i];if(s===void 0)continue;let a=_s(o.type);if(a&&!Wl(s,a))throw new TypeError(`Item field "${i}" must be of type ${a}`);let c=Array.isArray(o.values)?o.values:void 0;if(!Yl(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 ys=new Set(["item_format"]),gs=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"]),Kl=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"]),Xl=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock","test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),Jl={off:"disabled",on:"enabled",true:"enabled",false:"disabled",enabled:"enabled",disabled:"disabled"};function Zl(e){let t=e.trim().toLowerCase().replaceAll("-","_");if(ys.has(t)||gs.has(t)||Kl.has(t)||t==="context")return t}function Ql(e){let t=e.trim().toLowerCase();return Jl[t]??e}function $b(e,t){let n=Zl(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."}:ys.has(n)?{routable:!0,flag:"format",value:t}:gs.has(n)?{routable:!0,flag:"criterion",values:[t]}:{routable:!0,flag:"policy",value:Xl.has(n)?Ql(t):t}}function eu(e){return e==="telemetry.enabled"||/^telemetry[-_]tracking$/u.test(e??"")?"global":"project"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cb883ffc-c431-5bf9-a973-931a8a0a940c")}catch{}})();function pe(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function jb(e,t){let n=pe(t);return!e||!n?null:[...e.assurance_providers??[]].reverse().find(r=>pe(r.definition.id)===n)??null}function tu(e,t){let n=pe(t);return!e||!n?null:[...e.search_providers].reverse().find(r=>(pe(r.runtime_definition?.name)??pe(r.definition?.name))===n)??null}function nu(e,t){let n=pe(t);return!e||!n?null:[...e.vector_store_adapters].reverse().find(r=>(pe(r.runtime_definition?.name)??pe(r.definition?.name))===n)??null}function zb(e){return e.runtime_definition??e.definition}import{readFile as ru}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 ou=e=>ru(e,"utf8"),iu=async e=>await Ue().resolveValue("-",e);function Pr(e){return[...new Set(e.split(/[,\r\n]+/).map(t=>t.trim()).filter(t=>t.length>0))]}function su(e){let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(typeof r=="number"&&Number.isFinite(r))t.push(String(r));else return"";let n=Pr(t.join(`
|
|
11
|
-
`));return n.length>0?n.join(","):""}function ws(e){if(e===void 0)return;if(typeof e=="number")return Number.isFinite(e)?String(e):"";if(Array.isArray(e))return su(e);if(typeof e!="string")return"";let t=Pr(e);return t.length>0?t.join(","):""}async function au(e,t="--ids",n={}){if(e===void 0)return;let r=e.trim(),o=e;try{if(r==="-")o=await(n.readStdin??iu)(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.`,f.USAGE,{code:"bulk_ids_input_missing_path",required:`Pass ${t} @<path>, ${t} -, or inline IDs.`});o=await(n.readFile??ou)(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}`,f.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=ws(o);if(i!=="")return i;throw new p(`${t} requires at least one non-empty item ID.`,f.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 bs(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function $r(e){if(e==="/body"||e.startsWith("/body/"))return"body";if(e==="/metadata"||e.startsWith("/metadata/")||e==="/front_matter"||e.startsWith("/front_matter/")){let n=e.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return n?bs(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?bs(t):"root"}function ln(e,t){return t==="body"?e.body:t==="metadata"?e.metadata:t==="root"?e:e.metadata[t]}function cu(e,t){let n=t?.windowStartIndex??0,r=t?.field;if(e.length===0||n>=e.length)return[];let o=qi(),i=[];for(let s=0;s<e.length;s+=1){let a=e[s],c=o,d=_t(o,a.patch),l;d.ok?(l=d.document,o=l):l=c;let u=new Set;for(let _ of a.patch)u.add($r(_.path)),_.from!==void 0&&u.add($r(_.from));let m=[...u].sort((_,y)=>_.localeCompare(y));if(s>=n)if(r!==void 0){if(!u.has(r))continue;let _={field:r,before:ln(c,r),after:ln(l,r)};i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:[r],changes:[_]})}else{let _=m.map(y=>({field:y,before:ln(c,y),after:ln(l,y)}));i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:m,changes:_})}}return i}import du from"node:fs/promises";import lu 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 uu(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function mu(e,t){return new p(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,f.NOT_FOUND)}async function fu(e,t){return await Ai(lu.dirname(e)),await(await du.open(e,"a")).close(),U({path:e,scope:"project",op:`${t}:history:auto_create`})}async function un(e){return Es({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function Es(e){let t=uu(e.itemIds),n=[],r=[];for(let o of t){let i=te(e.pmRoot,o);if(!await j(i)){if(e.settings.history.missing_stream==="strict_error")throw mu(o,e.commandLabel);r.push(...await fu(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}import{readFile as pu}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 _u=e=>pu(e,"utf8");async function hu(e,t,n=_u){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.",f.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.",f.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 Ue().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.`,f.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 yu from"node:crypto";import mn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function vs(e){let t=[],n=!1;for(let r of(e??"").toLowerCase()){let o=r.charCodeAt(0),i=o>=48&&o<=57,s=o>=97&&o<=122;if(!i&&!s){n=t.length>0;continue}n&&(t.push("-"),n=!1),t.push(r)}return t.length===0?"pm-":`${t.join("")}-`}function Ve(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function le(e,t){let n=vs(t),r=Ve(e);return r.startsWith(n)?r:`${n}${r}`}function gu(e){let t=Mi(e);if(t!==void 0)return t;let n="";for(let r=0;r<e;r+=1)n+=yu.randomInt(0,36).toString(36);return n}async function wu(e,t,n){let r=[...new Set(Object.values(n))].flatMap(o=>[mn.join(e,o,`${t}.md`),mn.join(e,o,`${t}.toon`)]);return r.push(mn.join(e,"history",`${t}.jsonl`)),(await Promise.all(r.map(o=>j(o)))).some(Boolean)}var Ss=4,Ts=12;function bu(e){return typeof e!="number"||!Number.isFinite(e)?Ss:Math.min(Ts,Math.max(Ss,Math.trunc(e)))}async function Eu(e,t,n={}){let r=bu(n.tokenLength),o=Math.min(r+6,Ts),i=0;for(;r<=o;){for(let s=0;s<32;s+=1){let a=`${vs(t)}${gu(r)}`;if(!await(n.probeExisting===!1?j(mn.join(e,"history",`${a}.jsonl`)):wu(e,a,n.typeToFolder??ee)))return a;i+=1}r+=1}throw new Error(`Unable to generate unique id after ${i} attempts`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0394e0c1-ff68-5553-b022-1e8b6fff04f0")}catch{}})();var Su=new Set(["none","null","undefined"]);function gE(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)",f.USAGE)}function vu(e,t="cli"){let n=t==="sdk";if(typeof e!="string")throw new p(n?`parent must be a string. ${bt("parent")}.`:"--parent must be a string. Use --unset parent to clear this field.",f.USAGE);let r=e.trim();if(r.length===0)throw new p(an(t,"parent",". Use --parent none to unset."),f.USAGE);if(Is(r))throw new p(n?`parent must not be the placeholder "${r}". ${bt("parent")}, or omit parent.`:`--parent must not use placeholder token "${r}". Use --unset parent to clear this field.`,f.USAGE);return r}function Is(e){return Su.has(e.trim().toLowerCase())}function Tu(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"}.`,f.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${e}`]}}function Iu(e,t,n,r="cli"){let o=le(e,n),i=le(t,n);if(o!==i)return;let s=t!==i||e!==o?` (normalized from parent "${t}" and item "${e}")`:"";throw new p(`Parent item "${i}" cannot be the same as item "${o}"${s}. ${r==="sdk"?`${bt("parent")}.`:"Use --unset parent to clear this field."}`,f.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a59d5b7f-9764-53c5-a014-1119868be8ea")}catch{}})();var Fr={critical:0,high:1,medium:2,low:3,minimal:4},Cs=Object.keys(Fr),Cu=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${Cs.join(", ")}), case-insensitive`;function fn(e){return new p(`Invalid priority "${e}". Accepted values: ${Cu}.`,f.USAGE,{code:"invalid_argument_value",field:"priority",value:e,allowed:["0","1","2","3","4",...Cs]})}function Au(e){if(typeof e=="number"){if(Number.isInteger(e)&&e>=0&&e<=4)return e;throw fn(String(e))}if(typeof e!="string")throw fn(String(e));let t=e.trim();if(t.length===0)throw fn(e);let n=t.toLowerCase();if(Object.prototype.hasOwnProperty.call(Fr,n))return Fr[n];if(/^[0-4]$/.test(t))return Number(t);throw fn(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e363ee89-b438-5c8e-bb06-f4d05cc814cc")}catch{}})();function xu(e){let t={...e};for(let[n,r]of Object.entries(t))Array.isArray(r)&&Reflect.set(t,n,[...r]);return Ar(St(e,t))}function Ru(e){return wt(Et(St(e,{...e})))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6012e77b-7cdd-5496-a668-c9240a811b1a")}catch{}})();var ku=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,Ou=64;function RE(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)",f.USAGE)}function Du(e,t,n,r="cli"){let o=t.trim();if(o.length===0)throw new p(an(r,e,`. Use --${e} none to unset.`),f.USAGE);if(o.length<=Ou&&ku.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}`,f.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 As={open:"open_status",closed:"close_status",canceled:"canceled_status",cancelled:"canceled_status"},xs="all";function LE(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]===xs}function Nu(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=As[n];return r?t[r]:Er(e,t)}function Mu(e){let t=new Set(Object.keys(As));for(let n of e.definitions){t.add(n.id);for(let r of n.aliases)t.add(r)}return[...t]}function Lu(e,t){let n=e.trim().toLowerCase(),r,o=Number.POSITIVE_INFINITY;for(let i of Mu(t)){let s=be(n,i.toLowerCase(),2);s!==null&&s<o&&(r=i,o=s)}return r}function Pu(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()===xs).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.`,f.USAGE)}let s=[];for(let a of i){let c=Nu(a,t);if(c===void 0){if(r){let d=Lu(a,t);throw new p(`Invalid ${o} value "${a}". Use open|closed|canceled or a configured status id${d?`. Did you mean "${d}"?`:"."}`,f.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 $u={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 Fu(e){if(e!==void 0)return $u[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 ks(e){let t=[],n=new Set;for(let r of e)for(let o of Object.keys(r))n.has(o)||(n.add(o),t.push(o));return t}function jr(e){return e==null?"":Array.isArray(e)?e.map(t=>jr(t)).join(";"):typeof e=="object"?JSON.stringify(e):String(e)}function Rs(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function ju(e){if(e.length===0)return"";let t=ks(e),n=[t.map(r=>Rs(r)).join(",")];for(let r of e)n.push(t.map(o=>Rs(jr(r[o]))).join(","));return n.join(`
|
|
12
|
-
`)}function zu(e){if(e.length===0)return"";let t=ks(e),n=e.map(s=>t.map(a=>jr(s[a]))),r=t.map((s,a)=>Math.max(s.length,...n.map(c=>c[a].length))),o=(s,a)=>s.padEnd(r[a]),i=[t.map((s,a)=>o(s,a)).join(" | ")];i.push(r.map(s=>"-".repeat(s)).join("-+-"));for(let s of n)i.push(s.map((a,c)=>o(a,c)).join(" | "));return i.join(`
|
|
13
|
-
`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b84fee06-5bbd-57f9-9643-f283d6c87afa")}catch{}})();function Uu(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`,f.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 Vu=new Map(ot.map(e=>[e.toLowerCase(),e])),Hu=/^[A-Za-z][A-Za-z0-9_-]*$/;function Os(e,t){if(!Hu.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 zr(e){return Vu.get(e.trim().toLowerCase())}function Ms(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function qu(e){return e.replace(/[\\"`$]/g,t=>`\\${t}`)}function Ls(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 qE(e){let t=(e.name??"").trim();if(t.length===0)throw new Error("Type name must not be empty.");Os(t,"Type name");let n=zr(t);if(n)throw new Error(`Cannot redefine built-in item type "${n}". Built-in types are reserved: ${ot.join(", ")}.`);let r=e.description?.trim(),o=e.defaultStatus?.trim(),i=e.folder?.trim(),s=i&&i.length>0?mr(i):void 0,a=Ls(e.aliases??[]);for(let c of a){Os(c,"Alias");let d=zr(c);if(d)throw new Error(`Alias "${c}" collides with built-in item type "${d}". Built-in types are reserved: ${ot.join(", ")}.`)}return{name:t,description:r&&r.length>0?r:void 0,defaultStatus:o&&o.length>0?o:void 0,folder:s,aliases:a}}function BE(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 Ms(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 Ds(e,t){return typeof t=="string"&&t.trim().length>0?mr(t).toLowerCase():xi(e).toLowerCase()}function WE(e,t,n){let r=e.name.toLowerCase(),o=Ds(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||Ds(c,a.folder)===o&&i(c)}let s=n?.get(o);s!==void 0&&s.toLowerCase()!==r&&i(s)}function YE(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:Bu(t)}}function Bu(e){let t=Wu(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 Wu(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 GE(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=Ls([...Ms(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,Ns(a,"description",t.description),Ns(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 KE(e,t){let n=(t??"").trim();if(n.length===0)throw new Error("Type name must not be empty.");let r=zr(n);if(r)throw new Error(`Cannot remove built-in item type "${r}". Built-in types are reserved: ${ot.join(", ")}.`);let o=n.toLowerCase(),i=e.definitions.slice(),s=i.findIndex(c=>typeof c.name=="string"&&c.name.trim().toLowerCase()===o);if(s<0)return{file:{definitions:i},removed:!1};let[a]=i.splice(s,1);return{file:{definitions:i},removed:!0,definition:a}}function Ns(e,t,n){let r=e;n!==void 0&&(r[t]=n)}function XE(e){return`${JSON.stringify({definitions:e.definitions},null,2)}
|
|
14
|
-
`}function Yu(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 "${qu(n)}" (writes ${r}).`}function Gu(e,t,n){return`Invalid type value "${e}". Allowed: ${t.join(", ")}. ${Yu(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 Ps(e,t){return nt(e,t)}function Ku(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]=ji(o,i))}return r}function Xu(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(!Ps(o,r[r.length-1]))return!1;continue}if(!Ps(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 $s(e){return typeof e=="string"?e.trim().toLowerCase():""}function pn(e,t){let n=ut(e);return n.length===0?"":t?.alias_to_id?.get(n)??n}function Ju(e){let t=Array.isArray(e?.type_workflows)?e.type_workflows:[],n=new Map;for(let r of t){let o=$s(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 Zu(e){let t=$s(e.typeName),n=e.typeWorkflows.find(i=>i.type===t);if(!n)return{allowed:!0,hasRule:!1,allowedTransitions:[]};let r=pn(e.fromStatus,e.statusRegistry),o=pn(e.toStatus,e.statusRegistry);return r.length>0&&r===o?{allowed:!0,hasRule:!0,allowedTransitions:n.allowed_transitions}:{allowed:n.allowed_transitions.some(i=>{let s=pn(i[0],e.statusRegistry),a=pn(i[1],e.statusRegistry);return s===r&&a===o}),hasRule:!0,allowedTransitions:n.allowed_transitions}}function Qu(e){return e.length===0?"(no transitions allowed)":e.map(t=>`${t[0]} -> ${t[1]}`).join(", ")}import{spawnSync as js}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 em="PM_DISABLE_OLLAMA_AUTO_DEFAULTS",tm="PM_OLLAMA_MODEL",nm="http://localhost:11434",rm="qwen3-embedding:0.6b",om=".agents/pm/search/lancedb/",im=1500,sm=2500,am=/qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i,cm=/embed|embedding/i,ne=E;function dm(){let e=ne(process.env[em]);if(!e)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}function Fs(e){return e.some(t=>ne(t)!==null)}function lm(e){let t=ne(e);return!!(t&&t.toLowerCase()!=="ollama")}function um(e){let t=ne(e);return!!(t&&t.toLowerCase()!=="lancedb")}function mm(e){return lm(e.search?.provider)||um(e.vector_store?.adapter)||Fs([e.providers?.openai?.base_url,e.providers?.openai?.model,e.providers?.openai?.api_key])?!0:Fs([e.vector_store?.qdrant?.url,e.vector_store?.qdrant?.api_key])}function fm(){let e=js("ollama",["--version"],{encoding:"utf8",timeout:im});return e.error?!1:e.status===0}function pm(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=>am.test(r))||(n.find(r=>cm.test(r))??null)}function _m(e){let t=ne(e.providers?.ollama?.model);if(t)return t;let n=ne(process.env[tm]);if(n)return n;let r=js("ollama",["list"],{encoding:"utf8",timeout:sm});if(!r.error&&r.status===0){let o=pm(typeof r.stdout=="string"?r.stdout:"");if(o)return o}return null}function hm(e){return{baseUrl:ne(e.providers?.ollama?.base_url)===null,model:ne(e.providers?.ollama?.model)===null,lancedbPath:ne(e.vector_store?.lancedb?.path)===null,embeddingModel:ne(e.search?.embedding_model)===null}}function ym(e){return e.baseUrl||e.model||e.lancedbPath||e.embeddingModel}function gm(e,t,n){if(!t.baseUrl&&!t.model)return;let r=e.providers??={},o=r.ollama??={};t.baseUrl&&(o.base_url=nm),t.model&&(o.model=n)}function wm(e,t){if(!t.lancedbPath)return;let n=e.vector_store??={},r=n.lancedb??={};r.path=om}function bm(e,t,n){if(!t.embeddingModel)return;let r=e.search??={};r.embedding_model=n}function He(e){let t={settings:e,auto_ollama_defaults_applied:!1};if(dm()||mm(e))return t;let n=hm(e);if(!ym(n)||n.model&&!fm())return t;let r=structuredClone(e),o=_m(r);return o?(gm(r,n,o),wm(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 ${rm} or configure providers.ollama.model explicitly (and search.embedding_model if you need an override).`}}import{spawn as Em}from"node:child_process";import{mkdirSync as zs,rmSync as Vs,statSync as Sm}from"node:fs";import _n from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9ecff496-8afa-5cfc-9178-2be8bd403978")}catch{}})();var Hs="reindex",vm="search/pending-refresh.json",Tm="search/pending-refresh.gate.lock",Im=3e4,Cm="PM_SEARCH_REFRESH_INLINE",qs="PM_SEARCH_REFRESH_CHILD",Am=3e4;function Us(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function xm(){if(Us(process.env[Cm])||Us(process.env[qs]))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 Bs(e){return _n.join(e,vm)}function Ws(e){return _n.join(e,Tm)}function Rm(e){let t=Ws(e);try{if(Date.now()-Sm(t).mtimeMs<Im)return!1;Vs(t,{recursive:!0,force:!0})}catch{}try{return zs(_n.dirname(t),{recursive:!0}),zs(t),!0}catch{return!1}}function km(e){try{Vs(Ws(e),{recursive:!0,force:!0})}catch{}}async function Ys(e,t,n){for(let r=0;r<50;r+=1){if(Rm(e))try{return await t()}finally{km(e)}await Om(20)}return n}function Om(e){return new Promise(t=>{setTimeout(t,e)})}async function Vr(e){let t=await C(Bs(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 Gs(e,t){await T(Bs(e),`${JSON.stringify({ids:t})}
|
|
15
|
-
`)}async function Ur(e,t){let n=t.filter(o=>typeof o=="string"&&o.trim().length>0);if(n.length===0)return;let r=async()=>{let o=await Vr(e),i=[...new Set([...o,...n])].sort((s,a)=>s.localeCompare(a));await Gs(e,i)};await Ys(e,async()=>(await r(),!0),!1)||await r()}async function Dm(e){return Ys(e,async()=>{let t=await Vr(e);return t.length>0&&await Gs(e,[]),t},[])}function Nm(){return _n.join(ct(import.meta.url,["../../.."]),"dist","cli","search-refresh.js")}function Hr(e){try{let t=Em(process.execPath,[Nm()],{detached:!0,stdio:"ignore",env:{...process.env,PM_PATH:e,[qs]:"1"}});t.on("error",()=>{}),t.unref()}catch{}}function Mm(e){setTimeout(()=>Hr(e),Am)}async function Ks(e,t){await Ur(e,t),Hr(e)}async function yS(e,t,n=Mm){let r=[],o=[];if(!await j(e))return{processed:o,rounds:0,warnings:r};let i;try{let l=await ze(e),u=l.warnings.find(m=>m.startsWith("settings_read_"));if(u)return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${u}`]};i=He(l.settings).settings}catch(l){return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${S(l)}`]}}let s=null;try{s=await Ee(e,Hs,i.locks.ttl_seconds,dt(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 Dm(e);if(l.length===0)break;a+=1;try{let u=await t(e,l);if(r.push(...u.warnings),u.warnings.some(m=>m.startsWith("search_semantic_refresh_skipped:settings_read_failed:"))){await Ur(e,l),c=!0,d=!0;break}o.push(...u.refreshed)}catch(u){r.push(`search_background_refresh_failed:${S(u)}`),await Ur(e,l),c=!0;break}}}finally{await s?.()}return d&&n(e),(c?[]:await Vr(e)).length>0&&Hr(e),{processed:[...new Set(o)].sort((l,u)=>l.localeCompare(u)),rounds:a,warnings:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function It(e,t=!1){let n=e[0];if(n?.op!=="history_compact_baseline")return 0;let r=n.context?.history_compaction,o=typeof r=="object"&&r!==null&&"version_offset"in r?r.version_offset:void 0;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&Number.isSafeInteger(o+e.length))return o;if(t)return null;throw new p("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",f.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 Lm(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}.`,f.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 $m(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 Xs(e,t,n={}){let r=e.trim(),o=n.errorSubject??"history",i=o==="restore"?"Restore":"History",{guidance:s,lastTimestamp:a}=Pm(t,It(t,!0));if(!r)throw new p(`Missing ${o} target. Use a timestamp or version number.`,f.USAGE,s);if(/^\d+$/.test(r)){let l=It(t),u=Number(r);if(u>=1&&u<=l)throw new p(`History version ${u} was pruned by compaction.`,f.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.`,f.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.`,f.USAGE,s);let d=Lm(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}.`,f.USAGE,s);return{kind:"timestamp",raw:r,historyIndex:d}}function qr(e,t,n,r){let o=_t(e,t);if(o.ok)return o.document;let i=$m(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)}`,f.GENERIC_FAILURE)}function Js(e,t){let n=e[0];if(n&&n.op!=="create"&&n.op!=="history_compact_baseline"){let s=_t(pt,n.patch);if(!s.ok||typeof s.document.metadata.id!="string")throw new p("History starts without a reconstructable item baseline.",f.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}let r=e.slice(0,t+1),o=ht([...r]),i=structuredClone(pt);for(let s=0;s<=t;s+=1){let a=e[s];if(!a)throw new p(`History target entry ${s+1} does not exist.`,f.USAGE);i=qr(i,a.patch,s+1,a.op)}if(!o.ok)throw new p(`History cannot be replayed: ${o.errors.join(", ")}.`,f.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 CS(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.",f.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.`,f.USAGE)}import Zs from"node:fs/promises";import Ct from"node:path";import{isUtf8 as Fm}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="697f1dbe-8315-5901-ab11-e0c5211dbdbf")}catch{}})();var jm=1048576,zm=4194304;async function Qs(e,t){let n=Ct.dirname(e);for(;n!==Ct.parse(e).root;){let o=await Zs.stat(n).catch(i=>{if(P(i))return null;throw i});if(o!==null){if(!o.isDirectory())throw new p("Workflow policy storage ancestor must be a directory.",f.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}n=Ct.dirname(n)}let r=await Zs.open(e,"r").catch(o=>{if(P(o))return null;throw o});if(r===null)return null;try{let o=(await r.stat()).size,i=Buffer.alloc(Math.min(t,o)+1),s=0;for(;s<i.length;){let a=await r.read(i,s,i.length-s,s);if(a.bytesRead===0)break;s+=a.bytesRead}if(s===i.length||!Fm(i.subarray(0,s)))throw new p("Workflow policy input exceeds its byte bound or is not valid UTF-8.",f.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 Um(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.",f.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return bi(t)}async function Vm(e){return Um(await Qs(Ct.join(e,"schema","policies.json"),jm))}async function Hm(e,t){let n=await Qs(te(e,t),zm);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.",f.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 qm(e,t,n){let r=n.before?.status!==n.after?.status&&t.policies.some(s=>s.rule.kind==="approval"&&Ei(s,n)),o=n.before?.id??n.after?.id,i=r&&typeof o=="string"?await Hm(e,o):[];return Si(t,{...n,approvals:i})}async function Br(e){let t=await Vm(e.pmRoot),n=await qm(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(m=>!m.satisfied&&m.effect==="refuse"),o=[],i="";if(!e.dryRun)try{let m=await Sr({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:n.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms});o.push({path:"history/_workspace.jsonl",op:"policy_refused",record_hash:m.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(m){let _=new p("Workflow policy refusal could not be recorded in workspace history.",f.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=m,_}let s=r.slice(0,3).map(m=>({policy_id:m.policy_id,rule:m.rule,description:t.policies.find(_=>_.id===m.policy_id).description,missing_fields:m.missing_fields})),a=[...new Set(s.flatMap(m=>m.missing_fields))],c=s.map(m=>`${m.policy_id} (${m.rule})`).join(", "),d=r.length>3?` and ${r.length-3} more`:"",l=e.after?.metadata.id??e.before.metadata.id,u=a.map(m=>{if(e.before===null)return`Supply ${m} in the original ${e.operation} request, then retry; the item was not created.`;let _=lr("update",m);return _===void 0?`Supply ${m} using its declared SDK or package mutation contract, then retry.`:q(["update",l,ur("update",_),`<${m}>`,"--pm-path",Ct.resolve(e.pmRoot)])});throw new p(`Workflow policy refused ${e.operation}: ${c}${d}.${a.length?` Missing: ${a.join(", ")}.`:""}${i}`,f.CONFLICT,{code:"workflow_policy_refused",side_effects:o,reason:s.map(m=>m.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(m=>m.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:a},nextSteps:[...u,...new Set(r.slice(0,3).filter(m=>m.missing_fields.length===0).map(m=>m.remediation)),...r.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as Bm}from"node:async_hooks";import{channel as Wm}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var Wr=new Bm,Yr=Wm("@unbrained/pm-cli/item-metadata-enumeration/v1");function hn(e){Yr.publish(e)}async function HS(e){let t={enumeration_calls:0,metadata_rows:0},n=r=>{Wr.getStore()?.includes(t)&&(t.enumeration_calls+=1,t.metadata_rows+=r)};Yr.subscribe(n);try{return{result:await Wr.run([...Wr.getStore()??[],t],e),work:{...t}}}finally{Yr.unsubscribe(n)}}import{AsyncLocalStorage as ea}from"node:async_hooks";import{realpathSync as Ym}from"node:fs";import Kr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0d72cf82-14ea-573b-a36e-0077c82c0c1d")}catch{}})();var Gr=new ea;function QS(e,t){return Gr.run([...Gr.getStore()??[],{...e,pmRoot:Kr.resolve(e.pmRoot)}],t)}var Gm=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),Km=globalThis,At=Km[Gm]??=new ea;function qe(e){let t=Kr.resolve(e);try{return Ym.native(t)}catch{return t}}function e0(){return{entries:new Map}}function t0(e,t){return At.run([...At.getStore()??[],e],t)}function n0(e,t,n){let r=qe(t);if(e.pmRoot!==void 0&&e.pmRoot!==r)throw new p("An expected-revision scope is already bound to another tracker.",f.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});e.pmRoot=r;for(let{id:o,itemHash:i}of n){let s=e.entries.get(o);if(s!==void 0&&s.declared!==i)throw new p(`Item ${o} has two different expected revisions.`,f.USAGE,{code:"expected_revision_duplicate",item_id:o,required:"Declare at most one expected revision per item."});e.entries.set(o,s??{declared:i,expected:i,checked:!1,committed:!1})}}function r0(e){let t=[...e.entries.entries()];return{checked:t.filter(([,n])=>n.checked).map(([n])=>n),unchecked:t.filter(([,n])=>!n.checked).map(([n])=>n)}}function Xr(e,t){let n=At.getStore()??[];if(n.length===0)return[];let r=qe(e),o=new Set(t.filter(i=>typeof i=="string"));return[...new Set(n.flatMap(i=>i.pmRoot===r?[...o].flatMap(s=>i.entries.get(s)??[]):[]))]}function o0(e){let t=At.getStore()??[];if(t.length===0)return[];let n=qe(e),r=new Map;for(let o of t)if(o.pmRoot===n)for(let[i,s]of o.entries){if(s.expected!==s.declared)return;r.set(i,(r.get(i)??new Set).add(s.expected))}if(![...r.values()].some(o=>o.size>1))return[...r].map(([o,i])=>`${o}=${[...i][0]}`)}function i0(e){let t=qe(e);return(At.getStore()??[]).some(n=>n.pmRoot===t&&n.entries.size>0)}function Xm(e,t,n){let r=Xr(e,[n,t.metadata.id]);r.length>0&&ra(r,n,en(t),!1,e)}function s0(e,t,n){let r=Xr(e,[t]);r.length>0&&ra(r,t,gi(n),!0,e)}var Jm="revision_changed",Zm="document_unreadable";function Qm(e,t,n={}){let r=[...n.scopeArgs??[]],o=[...n.outputArgs??["--json"]],i=q([...r,"get",e,...o]),s=q([...r,"history",e,"--limit","5",...o]);return{required:t?`Recover ${e} without --expect-hash (${q([...r,"restore",e,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${e} (${i} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[q([...r,"get",e,"--fields","item_hash",...o]),s],nextSteps:[i,s]}}var ef=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),tf=globalThis,Jr=tf[ef]??=new WeakMap,nf=8;function ta(e){for(let t of na(e)){let n=Jr.get(t);if(n!==void 0)return n}}function*na(e){let t=e;for(let n=0;n<nf&&typeof t=="object"&&t!==null;n+=1){yield t;try{t=t.cause}catch{return}}}function ra(e,t,n,r,o){for(let i of e)if(i.checked=!0,!(!r&&i.expected===n))throw af(o,new p(`Item ${t} is no longer at the expected revision ${i.expected.slice(0,12)}${r?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${i.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,f.CONFLICT,{code:"item_revision_conflict",item_id:t,expected_revision:i.expected,current_revision:n,reason:r?Zm:Jm,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...Qm(t,r)}))}function a0(e,t){let n=ta(e);return n===void 0||n===qe(t)}var rf=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),of=globalThis,Zr=of[rf]??=new WeakSet;function sf(e){for(let t of na(e))if(Zr.has(t))return!0;return!1}function c0(e){return Zr.add(e),e}function d0(e,t){let n=ta(e);return n!==void 0&&Jr.set(t,n),sf(e)&&Zr.add(t),t}function af(e,t){return Jr.set(t,qe(e)),t}function Qr(e,t,n=t.metadata.id){Xm(e,t,n);for(let r of eo(e,[n,t.metadata.id]))r.validate(t)}function eo(e,t){let n=Kr.resolve(e);return(Gr.getStore()??[]).filter(r=>r.pmRoot===n&&t.includes(r.id))}function to(e,t,n=t.metadata.id,r=[],o){let i=Xr(e,[n,t.metadata.id,...r]);if(i.length>0){let s=o??en(t);for(let a of i)a.expected=s,a.committed=!0}for(let s of eo(e,[n,t.metadata.id,...r]))s.committed?.(t)}function oa(e,t){return Object.assign({},...eo(e,t).map(n=>n.historyContext))}import Ie from"node:fs/promises";import sa from"node:path";import{randomUUID as cf}from"node:crypto";import{createRequire as df}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 lf="metadata-query-index.sqlite",xt="5",no;function Rt(){return no!==void 0||(no=Hi(process.versions.node,df(import.meta.url))),no}function ia(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function Be(e){return sa.join(e,"runtime",lf)}function uf(e){e.exec(`
|
|
16
|
-
PRAGMA foreign_keys = ON;
|
|
17
|
-
PRAGMA journal_mode = OFF;
|
|
18
|
-
PRAGMA synchronous = OFF;
|
|
19
|
-
CREATE TABLE metadata (
|
|
20
|
-
key TEXT PRIMARY KEY,
|
|
21
|
-
value TEXT NOT NULL
|
|
22
|
-
) STRICT;
|
|
23
|
-
CREATE TABLE items (
|
|
24
|
-
id TEXT PRIMARY KEY,
|
|
25
|
-
relative_path TEXT NOT NULL UNIQUE,
|
|
26
|
-
metadata_json TEXT NOT NULL,
|
|
27
|
-
status TEXT NOT NULL,
|
|
28
|
-
type TEXT NOT NULL,
|
|
29
|
-
priority INTEGER NOT NULL,
|
|
30
|
-
updated_at TEXT NOT NULL,
|
|
31
|
-
created_at TEXT NOT NULL,
|
|
32
|
-
parent TEXT,
|
|
33
|
-
assignee TEXT,
|
|
34
|
-
sprint TEXT,
|
|
35
|
-
release TEXT
|
|
36
|
-
) STRICT;
|
|
37
|
-
CREATE INDEX items_default_order
|
|
38
|
-
ON items(priority, updated_at DESC, id);
|
|
39
|
-
CREATE INDEX items_status_default_order
|
|
40
|
-
ON items(status, priority, updated_at DESC, id);
|
|
41
|
-
CREATE INDEX items_type_default_order
|
|
42
|
-
ON items(type, priority, updated_at DESC, id);
|
|
43
|
-
CREATE INDEX items_parent_default_order
|
|
44
|
-
ON items(parent, priority, updated_at DESC, id);
|
|
45
|
-
CREATE TABLE item_metadata_keys (
|
|
46
|
-
item_id TEXT NOT NULL,
|
|
47
|
-
key TEXT NOT NULL,
|
|
48
|
-
PRIMARY KEY(item_id, key),
|
|
49
|
-
FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE
|
|
50
|
-
) STRICT;
|
|
51
|
-
CREATE INDEX item_metadata_keys_key_item
|
|
52
|
-
ON item_metadata_keys(key, item_id);
|
|
53
|
-
CREATE TABLE item_linked_files (
|
|
54
|
-
item_id TEXT NOT NULL,
|
|
55
|
-
path TEXT NOT NULL,
|
|
56
|
-
scope TEXT NOT NULL,
|
|
57
|
-
note TEXT,
|
|
58
|
-
PRIMARY KEY(item_id, path, scope),
|
|
59
|
-
FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE
|
|
60
|
-
) STRICT;
|
|
61
|
-
CREATE INDEX item_linked_files_path_scope_item
|
|
62
|
-
ON item_linked_files(path, scope, item_id);
|
|
63
|
-
CREATE VIRTUAL TABLE item_search USING fts5(
|
|
64
|
-
id UNINDEXED,
|
|
65
|
-
title,
|
|
66
|
-
description,
|
|
67
|
-
tags,
|
|
68
|
-
tokenize = 'unicode61'
|
|
69
|
-
);
|
|
70
|
-
`)}function gn(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function aa(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
|
|
71
|
-
id, relative_path, metadata_json, status, type, priority,
|
|
72
|
-
updated_at, created_at, parent, assignee, sprint, release
|
|
73
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
74
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
75
|
-
relative_path = excluded.relative_path,
|
|
76
|
-
metadata_json = excluded.metadata_json,
|
|
77
|
-
status = excluded.status,
|
|
78
|
-
type = excluded.type,
|
|
79
|
-
priority = excluded.priority,
|
|
80
|
-
updated_at = excluded.updated_at,
|
|
81
|
-
created_at = excluded.created_at,
|
|
82
|
-
parent = excluded.parent,
|
|
83
|
-
assignee = excluded.assignee,
|
|
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 ca(e){let t=Be(e.pmRoot),n=Rt();if(!n){await Ie.rm(t,{force:!0});return}await Ie.mkdir(sa.dirname(t),{recursive:!0});let r=`${t}.${cf()}.tmp`,o;try{o=new n(r),uf(o),o.exec("BEGIN IMMEDIATE"),gn(o,"version",xt),gn(o,"context_fingerprint",e.contextFingerprint),gn(o,"source_cursor",e.sourceCursor);for(let i of e.rows)aa(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Ie.rm(t,{force:!0}),await Ie.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Ie.rm(r,{force:!0})]),i}}function wn(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function da(e){let t=Rt();if(!t)return!1;let n=Be(e.pmRoot),r;try{await Ie.access(n),r=new t(n),r.exec("PRAGMA foreign_keys = ON");let o=wn(r);if(o.version!==xt||o.context_fingerprint!==e.contextFingerprint||o.source_cursor!==e.expectedSourceCursor)return r.close(),!1;r.exec("BEGIN IMMEDIATE");let i=r.prepare("DELETE FROM items WHERE relative_path = ?"),s=r.prepare("SELECT rowid FROM items WHERE relative_path = ?"),a=r.prepare("DELETE FROM item_search WHERE rowid = ?");for(let c of e.deletedRelativePaths??[]){let d=s.get(c);i.run(c),d&&a.run(d.rowid)}return e.row&&aa(r,e.row),gn(r,"source_cursor",e.sourceCursor),r.exec("COMMIT"),r.close(),!0}catch{try{r?.exec("ROLLBACK")}catch{}return r?.close(),!1}}function yn(e,t,n,r,o){!r||r.length===0||(e.push(`${n} ${o} (${r.map(()=>"?").join(", ")})`),t.push(...r))}function mf(e){let t=[],n=[];yn(t,n,"status",e.statuses,"IN"),yn(t,n,"status",e.excludeStatuses,"NOT IN"),yn(t,n,"type",e.types,"IN"),yn(t,n,"id",e.ids,"IN");for(let r of e.metadataKeys??[])t.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),n.push(r);for(let[r,o]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])o!==void 0&&(t.push(`${r} = ?`),n.push(o));return e.priority!==void 0&&(t.push("priority = ?"),n.push(e.priority)),{where:t.length===0?"":` WHERE ${t.join(" AND ")}`,parameters:n}}async function y0(e){let t=Rt();if(!t)return null;let n=e.query??{},{where:r,parameters:o}=mf(n),i;try{i=new t(Be(e.pmRoot),{readOnly:!0});let s=wn(i);if(s.version!==xt||s.source_cursor!==e.expectedSourceCursor)return i.close(),null;let a=i.prepare(`SELECT COUNT(*) AS count FROM items${r}`).get(...o),c=[],d="";n.limit!==void 0?(d+=" LIMIT ?",c.push(Math.max(0,Math.floor(n.limit))),n.offset!==void 0&&(d+=" OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))))):n.offset!==void 0&&(d+=" LIMIT -1 OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))));let l=i.prepare(`SELECT metadata_json FROM items${r}
|
|
86
|
-
ORDER BY ${n.terminalStatuses&&n.terminalStatuses.length>0?`CASE WHEN status IN (${n.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${d}`).all(...o,...n.terminalStatuses??[],...c).map(u=>{let m=JSON.parse(String(u.metadata_json));if(!m.id)throw new TypeError("Indexed metadata row has no id");return m});return i.close(),{source_cursor:s.source_cursor,total:Number(a.count),items:l}}catch{return i?.close(),null}}async function g0(e){let t=Rt();if(!t||e.paths.length===0)return null;let n;try{n=new t(Be(e.pmRoot),{readOnly:!0});let r=wn(n);if(r.version!==xt||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let o=e.paths.map(()=>"?").join(", "),i=e.scope===void 0?"":" AND scope = ?",s=[...e.paths,...e.scope===void 0?[]:[e.scope]],a=`path IN (${o})${i}`,c=n.prepare(`SELECT COUNT(DISTINCT item_id) AS count
|
|
87
|
-
FROM item_linked_files
|
|
88
|
-
WHERE ${a}`).get(...s),d=ia(e.limit,50),l=ia(e.offset,0),u=n.prepare(`SELECT items.id, items.metadata_json
|
|
89
|
-
FROM items
|
|
90
|
-
WHERE EXISTS (
|
|
91
|
-
SELECT 1 FROM item_linked_files
|
|
92
|
-
WHERE item_linked_files.item_id = items.id AND ${a}
|
|
93
|
-
)
|
|
94
|
-
ORDER BY items.priority ASC, items.updated_at DESC, items.id ASC
|
|
95
|
-
LIMIT ? OFFSET ?`).all(...s,d,l),m=[];if(u.length>0){let _=u.map(h=>String(h.id)),y=n.prepare(`SELECT item_id, path, scope, note
|
|
96
|
-
FROM item_linked_files
|
|
97
|
-
WHERE item_id IN (${_.map(()=>"?").join(", ")})
|
|
98
|
-
AND ${a}
|
|
99
|
-
ORDER BY path ASC, scope ASC`).all(..._,...s),g=new Map(_.map(h=>[h,[]]));for(let h of y){let w=String(h.item_id),b=g.get(w);b.push({path:String(h.path),scope:String(h.scope),...h.note===null?{}:{note:String(h.note)}}),g.set(w,b)}for(let h of u){let w=JSON.parse(String(h.metadata_json));m.push({item:w,files:g.get(String(h.id))})}}return n.close(),{source_cursor:r.source_cursor,total:Number(c.count),matches:m}}catch{return n?.close(),null}}async function w0(e){let t=Rt();if(!t)return null;let n;try{n=new t(Be(e.pmRoot),{readOnly:!0});let r=wn(n);if(r.version!==xt||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let o=n.prepare(`SELECT items.metadata_json
|
|
100
|
-
FROM item_search
|
|
101
|
-
JOIN items ON items.id = item_search.id
|
|
102
|
-
WHERE item_search MATCH ?
|
|
103
|
-
ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
|
|
104
|
-
LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(i=>JSON.parse(String(i.metadata_json)));return n.close(),{source_cursor:r.source_cursor,items:o}}catch{return n?.close(),null}}async function bn(e){await Ie.rm(Be(e),{force:!0})}import N from"node:fs/promises";import v from"node:path";import{createHash as ff,randomUUID as pa}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();var re=8,_a=500,pf="metadata-derived-index",_f="metadata-cache.json",hf="metadata-cache-bodies.json",yf="metadata-cache-collections.json",gf="metadata-cache-delta.json",wf="metadata-cache-manifest.json",la=4,bf=["comments","notes","learnings","files","tests","test_runs","docs"];function ha(){return Tt(fe())}function Sn(e){let t={...e},n={};for(let r of bf)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function ya(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function ga(e,t,n,r){let o=ff("sha256");o.update(`format:${e??"default"}`);let i=Object.entries(t).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}=${a}`).join(",");return o.update(`|types:${i}`),n&&o.update(`|schema:${JSON.stringify(n)}`),r.length>0&&o.update(`|extension_fields:${r.join(",")}`),o.digest("hex").slice(0,16)}function vn(e){return v.join(e,"runtime",_f)}function Tn(e){return v.join(e,"runtime",hf)}function In(e){return v.join(e,"runtime",yf)}function oo(e){return v.join(e,"runtime",gf)}function io(e){return v.join(e,"runtime",wf)}function Cn(e,t){let n=v.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var Ef=24,B=new Map,An=new WeakMap;function so(e){return An.get(e)??e.source_cursor}function Sf(e,t){let n=so(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){An.set(e,n);for(let[r,o]of Object.entries(t.changes))o.entry?e.entries[r]=o.entry:delete e.entries[r];e.directory_signatures=t.directory_signatures,e.source_cursor=t.source_cursor}}function vf(e,t){if(!e)return;let n=so(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){An.set(e,n);for(let[r,o]of Object.entries(t.changes))o.body?e.bodies[r]=o.body:delete e.bodies[r];e.source_cursor=t.source_cursor}}function Tf(e,t){if(!e)return;let n=so(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){An.set(e,n);for(let[r,o]of Object.entries(t.changes))o.collections?e.collections[r]=o.collections:delete e.collections[r];e.source_cursor=t.source_cursor}}function If(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(Sf(e,r),vf(t,r),Tf(n,r))}function ro(e,t){B.size>=Ef&&!B.has(e)&&Ni(B),B.set(e,t)}async function _e(e,t){let n;try{n=await N.stat(e)}catch{return B.delete(e),null}let r=B.get(e);if(r&&kt(r.signature,n.mtimeMs,n.ctimeMs,n.size))return B.delete(e),B.set(e,r),r.envelope;let o;try{o=t(await N.readFile(e,"utf8"))}catch{o=null}return ro(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function Cf(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==re||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=vn(e),i=await _e(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await _e(Cn(o,t),r);return s===null&&Nt(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function Af(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==re||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Tn(e),o=await _e(r,n);return t&&o?.context_fingerprint!==t?await _e(Cn(r,t),n):o}async function xf(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==re||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=In(e),o=await _e(r,n);return t&&o?.context_fingerprint!==t?await _e(Cn(r,t),n):o}async function ao(e){let t=oo(e),n=await _e(t,r=>{let o=JSON.parse(r);return o.version!==re||typeof o.base_source_cursor!="string"||typeof o.source_cursor!="string"||typeof o.changes!="object"||o.changes===null?null:o});if(n)return{envelope:n,invalid:!1};try{return await N.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function co(e){let t=io(e),n=await _e(t,r=>{let o=JSON.parse(r);return o.version!==re||typeof o.context_fingerprint!="string"||typeof o.source_cursor!="string"||!Number.isInteger(o.entry_count)||o.entry_count<0||typeof o.directory_signatures!="object"||o.directory_signatures===null?null:o});if(n)return n;try{await N.stat(t),await We(e)}catch{}return null}async function Ot(e,t){await N.mkdir(v.dirname(e),{recursive:!0}),await T(e,JSON.stringify(t));try{let r=await N.stat(e);ro(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{B.delete(e)}let n=v.dirname(v.dirname(e));if(e===vn(n)||e===Tn(n)||e===In(n)){let r=Cn(e,t.context_fingerprint);await T(r,JSON.stringify(t));try{let c=await N.stat(r);ro(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{B.delete(r)}let o=v.dirname(e),i=v.extname(e),s=v.basename(e,i),a=(await N.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==v.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>v.join(o,c.name));if(a.length>la){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-la)))await N.rm(d.path,{force:!0}),B.delete(d.path)}}}function Rf(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function wa(e,t,n){return e===void 0||Rf(e,t,n)}function Nt(e,t){e&&!e.includes(t)&&e.push(t)}function kt(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function kf(e,t,n){let r=v.join(e,t);try{let o=await N.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!P(o)&&Nt(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function Of(e,t){try{let n=await N.stat(v.join(e,t));return[t,{exists:!0,mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size}]}catch{return[t,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function En(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await Of(e,n))))}function Dt(e,t){return!e||Object.keys(e).length!==Object.keys(t).length?!1:Object.entries(t).every(([n,r])=>{let o=e[n];return o!==void 0&&o.exists===r.exists&&kt(o,r.mtime_ms,r.ctime_ms,r.size)})}function Df(e){return Gt.some(t=>e.toLowerCase().endsWith(t))}function Nf(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function Mf(e,t,n){if(n)for(let r of await Se({path:e,scope:"project"}))Nt(t,r)}function ua(e,t,n,r){if(e)return t&&n?n.collections:r}async function Lf(e,t,n){let r=await N.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=st(e);await Mf(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],d=!n.forceSourceRead&&c!==void 0&&kt(c,o,i,s),l=n.previousBodies[t],u=!n.forceSourceRead&&l!==void 0&&kt(l,o,i,s),m=n.previousCollections[t],_=!n.forceSourceRead&&m!==void 0&&kt(m,o,i,s);if(!(!d||n.includeBody&&!u||n.includeCollections&&!_))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:ua(n.includeCollections,_,m,void 0),bodyLength:c.body_length,body:n.includeBody?l.body:void 0};let y=await N.readFile(e,"utf8"),g=ce(y,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:w=>Nt(n.warnings,w)}),h=Sn(g.metadata);return Nf(n.state.misses,n.includeBody,n.includeCollections,d,u,_),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:d?c.metadata:h.light,heavyMetadata:ua(n.includeCollections,_,m,h.heavy),bodyLength:d?c.body_length:g.body.length,body:n.includeBody?g.body:void 0}}function Pf(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?ya(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};wa(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function $f(e,t,n,r){try{let o=await Lf(t,n,r);Pf(t,n,r,o)}catch{Nt(r.warnings,`item_list_item_read_failed:${e}/${v.basename(t)}`)}}function Ff(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function jf(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function zf(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function Uf(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function Vf(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!Df(s))continue;let a=v.join(o,s),c=v.relative(t.pmRoot,a);n.push($f(r,a,c,t)),n.length===32&&(await Promise.all(n),n.length=0)}await Promise.all(n)}async function Hf(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Dt(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Ot(vn(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Ot(io(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let t=[...e.state.documentsById.values()].map(({candidate:n})=>({relativePath:v.relative(e.pmRoot,n.item_path),metadata:Sn(n.metadata).light,linkedFiles:n.metadata.files??[]}));t.length>=e.minimumIndexedItems?await ca({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:t}):await bn(e.pmRoot)}catch{}}async function qf(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await Ot(Tn(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function Bf(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await Ot(In(e.pmRoot),{version:re,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function lo(e,t,n={}){let r=await co(e);return n.required!==!0&&(r===null||r.entry_count<_a)?async()=>{}:Ee(e,pf,30,t,!1,!1,3e3)}async function D0(e,t){let n=await co(e);if(n===null)return null;let r=await ao(e);if(r.invalid)return await We(e),null;let o=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.source_cursor:n.source_cursor,i=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.directory_signatures:n.directory_signatures;return t&&!Dt(i,await En(e,t))?null:{source_cursor:o,entry_count:n.entry_count}}function ma(e,t){let n=v.relative(e,t);return n===""||n===".."||n.startsWith(`..${v.sep}`)||v.isAbsolute(n)?null:n}async function We(e){await Promise.all([vn(e),Tn(e),In(e),oo(e),io(e)].map(async t=>{await N.rm(t,{force:!0}),B.delete(t)})),await bn(e)}async function Wf(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await N.stat(e.mutation.itemPath),n=Sn(e.mutation.document.metadata),r={mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size};return{entry:{...r,metadata:n.light,body_length:e.mutation.document.body.length},body:{...r,body:e.mutation.document.body},collections:{...r,collections:n.heavy}}}function Yf(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function uo(e){let t=ma(e.pmRoot,e.itemPath),n=e.previousItemPath?ma(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await We(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=ga(e.preferredFormat,e.typeToFolder,e.schema,ha()),o=await co(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await ao(e.pmRoot);if(s.invalid)return await We(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=Yf(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 Wf({mutation:e});let d=pa();return await Ot(oo(e.pmRoot),{version:re,context_fingerprint:r,base_source_cursor:i,source_cursor:d,directory_signatures:await En(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await da({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:d,row:e.document===null?null:{relativePath:t,metadata:Sn(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await bn(e.pmRoot),[]}catch{return await We(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function Gf(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function fa(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function Kf(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function Xf(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=st(n);if(!o)continue;let i=e.includeCollections?ya(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);wa(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 Jf(e){return e.forceSourceScan||gr()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Dt(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||fa(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||fa(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&Kf(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Mt(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=ha(),d=ga(t,n,o,c),l=await ao(e);l.invalid&&await We(e);let u=await Cf(e,d,i.cacheDiagnostics),m=s?await Af(e,d):null,_=a?await xf(e,d):null;If(u,m,_,l.envelope);let y=Ff(u,d),g=jf(m,d),h=zf(_,d),w=[...new Set(Object.values(n))],b=await En(e,w),I=Object.keys(y),A=Math.max(1,Math.floor(i.derivedIndexMinimumItems??_a));if(Jf({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:d,existingCache:u,existingBodyCache:m,existingCollectionsCache:_,directorySignatures:b,entryKeys:I,minimumIndexedItems:A,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:h}))return Xf({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:y,previousBodies:g,previousCollections:h});let L=await Promise.all(w.map(Wt=>kf(e,Wt,r))),x=gr(),D=Uf(),Z={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 Vf(L,Z);let ae=await En(e,w),Q=Dt(b,ae)?ae:{},H=D.misses.metadata||Object.keys(y).length!==Object.keys(D.newEntries).length||!Dt(u?.directory_signatures,Q)||u===null?pa():u.source_cursor;return await Hf({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCache:u,previousEntries:y,directorySignatures:Q,state:D,minimumIndexedItems:A}),s&&await qf({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingBodyCache:m,previousBodies:g,state:D}),a&&await Bf({pmRoot:e,contextFingerprint:d,sourceCursor:H,existingCollectionsCache:_,previousCollections:h,state:D}),Gf(D)}async function ba(e,t,n,r,o){return(await Mt(e,t,n,r,o,{includeBody:!1})).map(i=>({metadata:i.metadata,body:i.body??""}))}async function Ea(e,t,n,r,o){return(await Mt(e,t,n,r,o,{includeBody:!1,includeCollections:!1})).map(i=>({metadata:i.metadata,body:i.body??""}))}import he from"node:fs/promises";import{statSync as Zf}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 Qf(e,t){let n=-1,r=structuredClone(pt);for(let[a,c]of e.entries()){if(r=qr(r,c.patch,a+1,c.op),r.metadata.id!==void 0&&r.metadata.id!==t)throw new p(`History belongs to item ${String(r.metadata.id)}, expected ${t}.`,f.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});r.metadata.id===t&&Array.isArray(r.metadata.tags)&&(n=a)}let o=It(e,!0),i=n<0||o===null?null:o+n+1,s=i===null?void 0:String(i);if(n>=0&&s===void 0){let a=e[n].ts;Xs(a,e).historyIndex===n&&(s=a)}return{version:i,target:s}}async function Sa(e,t,n){let r=new Set([le(t,n),Ve(t)]);for(let o of r){let i=te(e,o);if(!Zf(i,{throwIfNoEntry:!1})?.isFile())continue;let s=await ft(i,o),a=-1;if(s.forEach((_,y)=>{_.op==="delete"&&(a=y)}),a<0)continue;let c=Js(s,s.length-1);if(Object.keys(c.metadata).length!==0)continue;let{version:d,target:l}=Qf(s,o),u=l===void 0?["history",o,"--verify"]:["get",o,"--at",l],m=q(u);return new p(`Item ${o} was deleted at ${s[a].ts}; its history is retained.`,f.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:[m,...l===void 0?["Recover the pre-compaction history from version control."]:[q(["restore",o,l])]],recovery:{suggested_retry:m,suggested_retry_args:u}})}}import{AsyncLocalStorage as ep}from"node:async_hooks";import va 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 Ta=new ep;function Y0(e,t){return Ta.run({...e,pmRoot:va.resolve(e.pmRoot)},t)}function Ia(e,t){let n=Ta.getStore();return n?.pmRoot===va.resolve(e)&&n.itemId===t?{bulk_checkpoint:n.checkpointId}:void 0}import mo from"node:path";import{isUtf8 as tp}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]="f5a647c3-870f-59f1-9685-4e5aa0794c8c")}catch{}})();async function np(e){try{return await he.access(e),!0}catch{return!1}}function rp(e,t){e&&(e.includes(t)||e.push(t))}function fo(e){return e??Tt(fe())}function op(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Ye(e,t,n="pm-",r,o=ee){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=le(t,n),c=Ve(t),d=[...new Set([s,a,c])].filter(m=>m.length>0),l=Object.entries(o),u=op(r);for(let m of d){let _=new Map;for(let[y]of l)for(let g of u){let h=$e(e,y,m,g,o);await np(h)&&_.set(h,_.get(h)??{id:m,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 ${m} has ambiguous identity across ${y.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,f.CONFLICT,{code:"item_identity_ambiguous",item_id:m,paths:y})}for(let y of _.values())return y}return null}async function Lt(e,t={}){let n=await ip(e,t);if(n.error!==null)throw n.error;return{raw:n.raw,document:n.document}}async function ip(e,t={}){let n=await he.readFile(e.itemPath);if(!tp(n))throw new p("Item contains invalid UTF-8; preserve a binary backup before recovering it.",f.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 Se({path:e.itemPath,scope:"project"});let o;try{o=ce(r,{format:e.item_format,requireSupportedFormat:!0,schema:t.schema,extensionFieldNames:fo(t.extensionFieldNames),onWarning:i=>rp(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 Aa(e,t,n=ee,r,o){await on(e);let i=await ba(e,t,n,r,o);return hn(i.length),i.map(s=>s.metadata)}async function sp(e,t,n=ee,r,o){await on(e);let i=await Ea(e,t,n,r,o);return hn(i.length),i.map(s=>s.metadata)}async function Cv(e,t,n=ee,r,o,i={}){await on(e);let s=await Mt(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan});return hn(s.length),s.map(a=>({...a.metadata,body:a.body}))}function po(e){return{async get(t){let n=await Ye(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Lt(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>Aa(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function ap(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await he.readdir(mo.join(e,o));for(let s of i)for(let a of Gt)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function cp(e,t,n,r){let o=le(t,n),i=await ap(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(a=>({id:a,distance:be(a,o,s)})).filter(a=>a.distance!==null).sort((a,c)=>a.distance-c.distance).slice(0,3).map(a=>a.id)}async function xa(e,t,n,r){let o=await Sa(e,t,n);if(o)return o;let i=await cp(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`,f.NOT_FOUND,{code:"item_not_found",id:t,nextSteps:s})}function dp(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 Ra(e){let t=e.typeToFolder??it(e.settings,fe()).type_to_folder,n=await Ye(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await xa(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await _r(e.pmRoot,n.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms,{waitPolicy:"progress"}),o=r.release;try{let i=[],{raw:s,document:a}=await Lt(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:i}),c=a.metadata.assignee?.trim(),d=ki(c),l=a.metadata.claim_principal?.trim()||c,u=yr(e.author),m=Wi(e.settings);if(d&&l!==u&&!e.force&&!dp(e.op,e.bypassAssigneeConflict)){if(m.ownership_enforcement==="strict")throw new p(`Item ${n.id} is assigned to ${d}. Use --force to override.`,f.CONFLICT);m.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}}async function ka(e,t,n,r){return e.fence(async()=>{let o;try{o=await he.readFile(t.itemPath,"utf8")}catch(i){if(!P(i))throw i;o=null}if(o!==n)throw new p(`Item ${t.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,f.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 lp(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 Oa(e){try{let t=await Ye(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return{document:cr};let n=ce(await he.readFile(t.itemPath,"utf8"),{format:t.item_format,requireSupportedFormat:!0,schema:e.settings.schema,extensionFieldNames:fo(e.extensionFieldNames)});return n.metadata.id===e.embeddedId?{document:n}:{document:e.fallback,revision:Ca}}catch{return{document:e.fallback,revision:Ca}}}var Ca="unreadable-after-storage-override";async function up(e){let t=await Qt("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 mp(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 fp(e,t){Ui(e.metadata)&&t.push("deferred_fields")}async function _o(e){Vi(e.op);let t=await Ra({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:n,located:r,originalRaw:o,document:i,warnings:s,releaseLock:a,lease:c}=t;try{Qr(e.pmRoot,i,r.id);let d=je(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=je(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(l);if(fp(l,u.changedFields),e.skipNoop===!0&&u.changedFields.length===0)return{item:d.metadata,body:d.body,changedFields:[],warnings:[...s,...u.warnings??[]]};let m={...e.resolveHistoryContext?.(),...Ia(e.pmRoot,r.id),...oa(e.pmRoot,[r.id,i.metadata.id])},_=Math.max(br(d.metadata),br(l.metadata));Yi(fr(e.pmRoot),_),_>zi(l.metadata)&&(l.metadata.pm_format_version=_,u.changedFields.push("pm_format_version")),l.metadata.updated_at=$();let y=je(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=await Br({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:d,after:y});await Zt({pm_root:e.pmRoot,operation:e.op,before:d,after:y,changed_fields:u.changedFields,author:e.author,sdk:po({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let h=await un({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),w="toon",b=mt(y,{format:w,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),I=$e(e.pmRoot,y.metadata.type,r.id,w,n),A=te(e.pmRoot,r.id),L=await ka(c,r,o,async()=>{let Q=await Qt("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:I,history_path:A,item_format:w,before:d,after:y,contents:b}),{effectiveTargetItemPath:H,effectiveSerializedAfter:Wt,skipItemWrite:tt}=lp(Q,I,b),Xd=await lo(e.pmRoot,e.author),yi=[];try{tt||await T(H,Wt),!tt&&H!==r.itemPath&&await he.rm(r.itemPath);let Zd=tn({nowIso:y.metadata.updated_at,author:e.author,op:e.op,before:d,after:y,message:e.message,context:g.decisions.length===0?Object.keys(m).length===0?void 0:m:{...m,workflow_policies:g.decisions}});try{await nn(A,Zd)}catch(Qd){throw await mp({skipItemWrite:tt,effectiveTargetItemPath:H,originalItemPath:r.itemPath,originalRaw:o}),Qd}tt||(yi=await uo({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:H,previousItemPath:r.itemPath,document:y}))}finally{await Xd()}let Jd=tt||H!==I||Wt!==b;return{derivedIndexWarnings:yi,effectiveTargetItemPath:H,overrideWarnings:Q.warnings,stored:Jd?await Oa({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:Z}=L;to(e.pmRoot,Z.document,r.id,[y.metadata.id],Z.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:A,scope:"project",op:`${e.op}:history`,item_id:y.metadata.id,item_type:y.metadata.type,before:d,after:y,changed_fields:u.changedFields})];return Jt({id:y.metadata.id,op:e.op,item_type:y.metadata.type,previous_status:d.metadata.status,status:y.metadata.status,previous:lt(d.metadata,u.changedFields),current:lt(y.metadata,u.changedFields),changed_fields:u.changedFields}),{item:y.metadata,body:y.body,changedFields:u.changedFields,warnings:[...s,...u.warnings??[],...g.warnings,...h.warnings,...L.overrideWarnings,...x,...ae]}}finally{await a()}}async function pp(e){let{historyContext:t,...n}=e;return _o({...n,resolveHistoryContext:()=>t})}async function Av(e){return _o(e)}async function _p(e){return _o(e)}async function hp(e){let t=await Ra({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:n,originalRaw:r,document:o,warnings:i,releaseLock:s,lease:a}=t;try{Qr(e.pmRoot,o,n.id);let c=fo(void 0),d=je(o,{schema:e.settings.schema,extensionFieldNames:c}),l=await Br({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:d,after:null,dryRun:e.dryRun});await Zt({pm_root:e.pmRoot,operation:"delete",before:d,after:null,changed_fields:["deleted"],author:e.author,dry_run:e.dryRun===!0,sdk:po({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let u=await un({pmRoot:e.pmRoot,settings:e.settings,itemId:n.id,commandLabel:"delete"}),m=$(),_=cr,y=tn({nowIso:m,author:e.author,op:"delete",before:d,after:_,message:e.message,context:l.decisions.length===0?void 0:{workflow_policies:l.decisions}}),g=te(e.pmRoot,n.id),h=()=>up({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 ka(a,n,r,async()=>{let{effectiveItemPath:x,skipDelete:D,warnings:Z}=await h(),ae=await lo(e.pmRoot,e.author),Q=[];try{D||await he.rm(x);try{await nn(g,y)}catch(H){throw D||await T(x,r),H}D||(Q=await uo({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:x,document:null}))}finally{await ae()}return{derivedIndexWarnings:Q,effectiveItemPath:x,overrideWarnings:Z,stored:D||x!==n.itemPath?await Oa({pmRoot:e.pmRoot,settings:e.settings,id:n.id,typeToFolder:t.typeToFolder,fallback:_,embeddedId:o.metadata.id}):{document:_}}}),{derivedIndexWarnings:b,effectiveItemPath:I,stored:A}=w;to(e.pmRoot,A.document,n.id,[o.metadata.id],A.revision);let L=[...await 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 Jt({id:d.metadata.id,op:"delete",item_type:d.metadata.type,previous_status:d.metadata.status,previous:lt(d.metadata,Object.keys(d.metadata)),changed_fields:["deleted"]}),{item:d.metadata,changedFields:["deleted"],warnings:[...i,...l.warnings,...u.warnings,...w.overrideWarnings,...b,...L]}}finally{await s()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b58b44d-819c-5115-b011-f9dfa8e2ab41")}catch{}})();var yp=3e4,Pt=class extends Error{status;constructor(t,n){super(t),this.name="SearchHttpError",this.status=n}};function Ce(e,t,n=yp){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} timeout must be a positive finite number`);return Math.floor(r)}function Ae(e,t){if(e)return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error(`${t} execution requires a fetch implementation`)}async function gp(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${S(t)})`}}async function xn(e){let t=new AbortController,n=setTimeout(()=>{t.abort()},e.timeoutMs);try{let r;try{r=await e.fetcher(e.endpoint,{method:e.method,headers:e.headers,body:JSON.stringify(e.body),signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`${e.requestLabel} timed out after ${e.timeoutMs}ms`):new Error(`${e.requestLabel} execution failed: ${S(o)}`)}if(!r.ok){let o=await gp(r),i=o.length>0?`: ${o}`:"";throw new Pt(`${e.requestLabel} failed with status ${r.status} ${r.statusText}${i}`,r.status)}try{return await r.json()}catch(o){throw new Error(`${e.responseLabel} JSON parse failed: ${S(o)}`)}}finally{clearTimeout(n)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5452a392-2477-5028-8aa8-521c6b245f52")}catch{}})();function Nv(e,t){let n=E(e);if(!n)return"unconfigured";let r=E(t);return r&&r.toLowerCase()===n.toLowerCase()?"configured":"auto-detected"}function wp(e){let t=at(e),n=t.toLowerCase();return n.endsWith("/embeddings")?t:n.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function Na(e){let t=e.search?.embedding_model;return E(t)||null}function bp(e){let t=E(e.providers?.openai?.base_url),n=E(e.providers?.openai?.model);if(!t||!n)return null;let r=Na(e),o=E(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:r??n,...o?{api_key:o}:{}}}function Ep(e){let t=E(e.providers?.ollama?.base_url),n=E(e.providers?.ollama?.model);if(!t||!n)return null;let r=Na(e);return{name:"ollama",base_url:t,model:r??n}}function Ma(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 Sp(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 vp(e){let t=e.map((n,r)=>({embedding:n.embedding,index:n.index,position:r}));if(t.some(n=>n.index!==void 0)){for(let n of t)if(!Number.isInteger(n.index))throw new TypeError(`OpenAI embedding response entry at position ${n.position} is missing a valid integer index`);return[...t].sort((n,r)=>{let o=n.index-r.index;return o!==0?o:n.position-r.position})}return t}function Rn(e){let t=bp(e),n=Ep(e),r=[t,n].filter(s=>s!==null),o=E(e.search?.provider),i=o?o.toLowerCase():null;return{active:(i?r.find(s=>s.name===i):void 0)??r[0]??null,available:r}}function Da(e){let t=at(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:wp(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function Tp(e,t){let n=Ma(t);return e.name==="openai"?{target:Da(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:Da(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:n}}}function Ip(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 vp(o).map((i,s)=>{let a=i.embedding;if(!Fe(a))throw new Error(`OpenAI embedding response entry at index ${s} is missing a numeric embedding vector`);return[...a]})}let n=t.embedding;if(Fe(n))return[[...n]];let r=t.embeddings;if(Array.isArray(r)&&r.length>0)return r.map((o,i)=>{if(!Fe(o))throw new Error(`Ollama embedding response entry at index ${i} is missing a numeric embedding vector`);return[...o]});throw new Error("Ollama embedding response must include embedding or embeddings vectors")}async function La(e,t,n={}){let r=Ce(n.timeout_ms,"Embedding request"),o=Ae(n.fetcher,"Embedding request"),i=Ma(t),s=Sp(i),a=Tp(e,s.uniqueInputs),c=await xn({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:r,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),d=Ip(e,c);if(d.length!==s.uniqueInputs.length)throw new Error(`Embedding response cardinality mismatch: expected ${s.uniqueInputs.length} vector(s), received ${d.length}`);return s.originalToUniqueIndex.map(l=>[...d[l]])}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d563454-0999-5df5-afb9-58503b409436")}catch{}})();var kn=["title","description","tags","status","type","priority","assignee","parent","goal","value","why_now","risk","confidence","estimated_minutes","acceptance_criteria","resolution","expected_result","actual_result","body","comments","notes","learnings","reminders","events","dependencies","plan"];function yo(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...kn];let n=new Set(kn),r=Array.from(new Set(t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0&&n.has(o))));return r.length>0?r:[...kn]}var Cp=8e3,Ap=3200,xe="...[semantic corpus truncated]",xp="search_embedding_corpus_max_characters_invalid:using_provider_default";function ie(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function Rp(e){return(e.reminders??[]).map(t=>ie([t.at,t.text]))}function kp(e){return(e.events??[]).map(t=>ie([t.start_at,t.end_at,t.title,t.description,t.location,t.all_day===!0?"all day":void 0,t.timezone,t.recurrence?.freq,t.recurrence?.interval,t.recurrence?.count,t.recurrence?.until,t.recurrence?.by_weekday?.join(" "),t.recurrence?.by_month_day?.join(" "),t.recurrence?.exdates?.join(" ")]))}function Op(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 Dp(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 Pv(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??[])Op(t,n);return Dp(t,e),t.filter(n=>typeof n=="string"&&n.length>0).join(" ")}function Np(e){let t=(e.plan_steps??[]).map(i=>ie([i.order,i.id,i.title,i.body,i.status,i.owner,i.evidence,i.blocked_reason,i.superseded_by,(i.linked_items??[]).map(s=>ie([s.kind,s.id,s.note])).join(" "),(i.files??[]).map(s=>ie([s.path,s.note])).join(" "),(i.tests??[]).map(s=>ie([s.command,s.path,s.note])).join(" "),(i.docs??[]).map(s=>ie([s.path,s.note])).join(" ")])),n=(e.plan_decisions??[]).map(i=>ie([i.decision,i.rationale,i.evidence,i.step_id])),r=(e.plan_discoveries??[]).map(i=>ie([i.text,i.step_id])),o=(e.plan_validation??[]).map(i=>ie([i.text,i.command,i.expected]));if([e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context,...t,...n,...r,...o].some(i=>i!==void 0))return{mode:e.plan_mode,scope:e.plan_scope,harness:e.plan_harness,resume_context:e.plan_resume_context,steps:t,decisions:n,discoveries:r,validation:o}}function ho(e){return(e??[]).flatMap(t=>Object.prototype.toString.call(t)==="[object Object]"&&typeof t.text=="string"?[t.text]:[])}function oe(e){return typeof e=="string"&&e.trim().length>0}var Mp={title:e=>e.metadata.title,description:e=>e.metadata.description,tags:e=>e.metadata.tags,status:e=>e.metadata.status,type:e=>e.metadata.type,priority:e=>typeof e.metadata.priority=="number"?e.metadata.priority:void 0,assignee:e=>oe(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>oe(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>oe(e.metadata.goal)?e.metadata.goal:void 0,value:e=>oe(e.metadata.value)?e.metadata.value:void 0,why_now:e=>oe(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>oe(e.metadata.risk)?e.metadata.risk:void 0,confidence:e=>e.metadata.confidence!==void 0&&e.metadata.confidence!==null?e.metadata.confidence:void 0,estimated_minutes:e=>typeof e.metadata.estimated_minutes=="number"?e.metadata.estimated_minutes:void 0,acceptance_criteria:e=>oe(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>oe(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>oe(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>oe(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>ho(e.metadata.comments),notes:e=>ho(e.metadata.notes),learnings:e=>ho(e.metadata.learnings),reminders:e=>Rp(e.metadata),events:e=>kp(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>Np(e.metadata)};function Pa(e,t={}){let n=t.fields??kn,r={};for(let o of n){let i=Mp[o];if(!i)continue;let s=i(e);s!==void 0&&(r[o]=s)}return r}function Lp(e){return e?.trim().toLowerCase()==="ollama"?Ap:Cp}function Ge(e,t){let n=Lp(e),r=Di(t);return r!==null?{maxCharacters:r,warning:null}:{maxCharacters:n,warning:t==null?null:xp}}function go(e,t={}){let n=JSON.stringify(Pa(e,{fields:t.fields})),r=Ge(t.providerName,t.maxCharacters).maxCharacters;if(n.length<=r)return n;if(r<=xe.length)return xe.slice(0,r);let o=Math.max(0,r-xe.length);return`${n.slice(0,o)}${xe}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67bae1a1-19d1-50ea-816f-4b68e6bb69d9")}catch{}})();function Pp(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 $p(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 Fp(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let n=Math.max(0,t-xe.length);return`${e.slice(0,n)}${xe}`.slice(0,t)}function $a(e){let t=S(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function jp(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 $a(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 zp(e){return e instanceof Pt?e.status===413?"payload_too_large":null:$a(e)?"timeout":null}async function wo(e,t,n,r,o,i,s){let a=null;for(let c=0;c<=o;c+=1)try{s.requests+=1;let d=await La(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=zp(d);if(l!==null&&t.length>1){s.split_batches+=1;let u=Math.ceil(t.length/2),m=t.slice(0,u),_=t.slice(u);return i.push(`search_embedding_batch_split_after_${l}:batch=${n}:size=${t.length}:parts=${m.length}|${_.length}`),[...await wo(e,m,`${n}.1`,r,o,i,s),...await wo(e,_,`${n}.2`,r,o,i,s)]}if(c<o){s.retries+=1;let u=Math.min(1e3*2**c,8e3);await new Promise(m=>setTimeout(m,u))}}throw new Error(jp(e,n,t.length,r,o+1,a))}async function bo(e,t,n,r={}){if(n.length===0)return{vectors:[],warnings:[]};let o=performance.now(),i=r.maxRequestBytes??262144;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError("maxRequestBytes must be a positive safe integer");let s={provider:e.name,model:e.model,max_request_bytes:i,limit_source:r.maxRequestBytes===void 0?"default":"caller",planned_batches:0,requests:0,successful_batches:0,split_batches:0,retries:0,batch_size_histogram:{},elapsed_ms:0,inputs_per_second:0},a=[],c=Ge(e.name,t.search.embedding_corpus_max_characters);c.warning&&a.push(c.warning);let d=Pp(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=Fp(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 m=$p(e,u,d.batchSize,d.maxRequestBytes);s.planned_batches=m.length;let _=[],y=0;for(let g=0;g<m.length;g+=1){let h=m[g];r.onProgress?.({batch_index:g+1,batch_total:m.length,batch_size:h.length,completed_inputs:y,total_inputs:u.length,phase:"start"}),_.push(...await wo(e,h,String(g+1),d.timeoutMs,d.maxRetries,a,s)),y+=h.length,r.onProgress?.({batch_index:g+1,batch_total:m.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 Up,readFile as Vp,stat as vo,unlink as Hp}from"node:fs/promises";import{basename as Fa,dirname as Eo,isAbsolute as qp,join as Bp,resolve as To}from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f917418-051d-5458-9080-fa23cd36c4d1")}catch{}})();var Io="pm_items",Wp=/[^a-zA-Z0-9_-]/g,Yp=128,Gp=".pm-cli-local-vectors",So=1,Re=new Map;function Ft(e){return(E(e.collection_name)??Io).replaceAll(Wp,"_").slice(0,Yp)}function On(e){if(!Fe(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function za(e){if(!Number.isFinite(e)||e<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(e)}function Kp(e){let t=e.result;if(!Array.isArray(t))throw new TypeError("Qdrant query response must include a result array");let n=t.map((r,o)=>{let i=r.id,s=typeof i=="number"?String(i):i,a=E(s);if(!a)throw new Error(`Qdrant query response entry at index ${o} is missing a non-empty id`);let c=r.score;if(typeof c!="number"||!Number.isFinite(c))throw new TypeError(`Qdrant query response entry at index ${o} is missing a finite numeric score`);let d=r.payload;if(d!==void 0&&(typeof d!="object"||d===null||Array.isArray(d)))throw new Error(`Qdrant query response entry at index ${o} must provide payload as an object when set`);return{id:a,score:c,...d?{payload:d}:{}}});return n.sort((r,o)=>r.score!==o.score?o.score-r.score:r.id.localeCompare(o.id)),n}function Co(e){let t=E(e.result?.status);if(t)return{status:t};let n=E(e.status);if(n)return{status:n};throw new Error("Qdrant upsert response must include status metadata")}async function $t(e,t,n,r,o){return await xn({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:n,fetcher:r,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function Xp(e){let t=E(e.vector_store?.qdrant?.url);if(!t)return null;let n=E(e.vector_store?.collection_name),r=E(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...n&&n!==Io?{collection_name:n}:{},...r?{api_key:r}:{}}}function Jp(e){let t=To(e),n=Eo(t);return Fa(t)==="pm"&&Fa(n)===".agents"?Eo(n):t}function Zp(e,t){return!t||qp(e)?e:To(Jp(t),e)}function Qp(e,t){let n=E(e.vector_store?.lancedb?.path);if(!n)return null;let r=E(e.vector_store?.collection_name);return{name:"lancedb",path:Zp(n,t),...r&&r!==Io?{collection_name:r}:{}}}function e_(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector upsert records must include at least one entry");return e.map((t,n)=>{let r=E(t.id);if(!r)throw new Error(`Vector upsert record at index ${n} is missing a non-empty id`);let o=On(t.vector),i=t.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`Vector upsert record at index ${n} must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}})}function t_(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector delete ids must include at least one entry");let t=e.map((r,o)=>{let i=E(r);if(!i)throw new Error(`Vector delete id at index ${o} is missing a non-empty value`);return i}).sort((r,o)=>r.localeCompare(o)),n=[];for(let r of t)n.at(-1)!==r&&n.push(r);return n}function n_(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function r_(e){return e.replace(/\/points\?wait=true$/,"")}function Dn(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function Nn(e,t){return Ke(e,t)}function Ke(e,t){return Bp(To(e),Gp,`${t}.json`)}function o_(e,t,n){let r=E(e.id);if(!r)throw new Error(`LanceDB local snapshot '${n}' record at index ${t} is missing a non-empty id`);let o=On(e.vector),i=e.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`LanceDB local snapshot '${n}' record '${r}' must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}}function i_(e,t,n){let r;try{r=JSON.parse(n)}catch(a){throw new Error(`LanceDB local snapshot at '${e}' is not valid JSON: ${S(a)}`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`LanceDB local snapshot at '${e}' must be a JSON object`);if(r.version!==So)throw new Error(`LanceDB local snapshot at '${e}' must include version=${So}`);let o=E(r.table);if(!o)throw new Error(`LanceDB local snapshot at '${e}' must include a non-empty table value`);if(o!==t)throw new Error(`LanceDB local snapshot at '${e}' table mismatch: expected '${t}', received '${o}'`);let i=r.records;if(!Array.isArray(i))throw new TypeError(`LanceDB local snapshot at '${e}' must include a records array`);let s=new Map;for(let a=0;a<i.length;a+=1){let c=o_(i[a],a,e);s.set(c.id,c)}return s}async function s_(e){try{let t=await vo(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!P(t))throw t;return null}}function a_(e,t){if(!t)return null;if(t.mtimeMs===null&&t.size===null&&t.records.size===0)return t.records;let n=new Map;return Re.set(e,{records:n,mtimeMs:null,size:null}),n}function c_(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ao(e,t){let n=Nn(e,t),r=Ke(e,t),o=await s_(r),i=Re.get(n);if(!o){let a=a_(n,i);if(a)return a}if(c_(i,o))return i.records;let s=new Map;try{let a=await Vp(r,"utf8");s=i_(r,t,a)}catch(a){if(!P(a))throw a}return Re.set(n,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function d_(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 Ua(e){try{await Hp(e)}catch(t){if(!P(t))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${S(t)}`)}}async function Va(e,t,n){let r=Ke(e,t);if(n.size===0){await Ua(r);return}let o=Eo(r);try{await Up(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${S(s)}`)}let i=`${JSON.stringify({version:So,table:t,records:d_(n)})}
|
|
105
|
-
`;try{await T(r,i)}catch(s){throw new Error(`LanceDB local snapshot write failed at '${r}': ${S(s)}`)}}async function l_(e,t){let n=Nn(e,t),r=Ke(e,t);await Ua(r),Re.delete(n)}function ja(e){let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.sqrt(t)}function u_(e,t){let n=0;for(let i=0;i<e.length;i+=1)n+=e[i]*t[i];let r=ja(e),o=ja(t);return r===0||o===0?0:n/(r*o)}function Mn(e,t){let n=Xp(e),r=Qp(e,t),o=[n,r].filter(a=>a!==null),i=E(e.vector_store?.adapter),s=i?i.toLowerCase():null;return{active:(s?o.find(a=>a.name===s):void 0)??o[0]??null,available:o}}function Ln(e){let t=Ft(e);if(e.name==="qdrant"){let o=at(e.url),i=encodeURIComponent(t);return{store:"qdrant",query_target:`${o}/collections/${i}/points/search`,upsert_target:`${o}/collections/${i}/points?wait=true`}}let n=encodeURIComponent(e.path),r=encodeURIComponent(t);return{store:"lancedb",query_target:`lancedb://${n}#${r}`,upsert_target:`lancedb://${n}#${r}`}}function m_(e,t,n){let r=Ln(e),o=On(t),i=za(n);return e.name==="qdrant"?{target:r,method:"POST",headers:Dn(e),body:{vector:o,limit:i,with_payload:!0}}:{target:r,method:"LOCAL",headers:{},body:{table:Ft(e),vector:o,limit:i}}}function f_(e,t){let n=Ln(e),r=e_(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Dn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ft(e),records:r}}}function p_(e,t){let n=Ln(e),r=t_(t);return e.name==="qdrant"?{target:n,method:"POST",headers:Dn(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ft(e),ids:r}}}async function Gv(e,t,n,r={}){let o=m_(e,t,n);if(o.method==="LOCAL"){let c=e,d=o.body,l=await Ao(c.path,d.table);if(l.size===0)return[];let u=On(d.vector),m=za(d.limit),_=[],y=0;for(let g of l.values()){if(g.vector.length!==u.length){y++;continue}_.push({id:g.id,score:u_(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,m)}let i=Ce(r.timeout_ms,"Vector request"),s=Ae(r.fetcher,"Vector request"),a=await $t(o.target.query_target,{method:"POST",headers:o.headers,body:o.body},i,s,"query");return Kp(a)}async function xo(e,t,n={}){let r=f_(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=Nn(a.path,c.table),l=await Ao(a.path,c.table);for(let _ of c.records)l.set(_.id,_);await Va(a.path,c.table,l);let u=Ke(a.path,c.table),m=await vo(u);return Re.set(d,{records:l,mtimeMs:m.mtimeMs,size:m.size}),{status:"ok"}}let o=Ce(n.timeout_ms,"Vector request"),i=Ae(n.fetcher,"Vector request"),s=await $t(r.target.upsert_target,{method:"POST",headers:r.headers,body:r.body},o,i,"upsert");return Co(s)}async function Pn(e,t,n={}){let r=p_(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,d=Nn(a.path,c.table),l=await Ao(a.path,c.table);if(l.size===0)return{status:"ok"};for(let u of c.ids)l.delete(u);if(await Va(a.path,c.table,l),l.size===0)Re.delete(d);else{let u=Ke(a.path,c.table),m=await vo(u);Re.set(d,{records:l,mtimeMs:m.mtimeMs,size:m.size})}return{status:"ok"}}let o=Ce(n.timeout_ms,"Vector request"),i=Ae(n.fetcher,"Vector request"),s=await $t(n_(r.target.upsert_target),{method:"POST",headers:r.headers,body:r.body},o,i,"delete");return Co(s)}async function Ha(e,t=[],n={},r){if(e.name==="lancedb")return await l_(e.path,Ft(e)),{status:"ok"};if(r!==void 0){if(!Number.isInteger(r)||r<=0)throw new Error("Vector reset dimension must be a positive integer when provided");let i=Ln(e),s=r_(i.upsert_target),a=Ce(n.timeout_ms,"Vector request"),c=Ae(n.fetcher,"Vector request"),d=Dn(e);try{await $t(s,{method:"DELETE",headers:d,body:{}},a,c,"delete")}catch(u){if(!S(u).includes("failed with status 404"))throw u}let l=await $t(s,{method:"PUT",headers:d,body:{vectors:{size:r,distance:"Cosine"}}},a,c,"upsert");return Co(l)}let o=t.map(i=>i.trim()).filter(i=>i.length>0);return o.length===0?{status:"ok"}:await Pn(e,o,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f8acaac5-64f7-5e22-987e-4eb12a1aa1cf")}catch{}})();function $n(e,t){let n=E(e),r=E(t);return!n||!r?null:{provider:n,model:r}}function qa(e){if(e==null)return null;if(typeof e!="object"||Array.isArray(e))throw new Error("Vectorization embedding metadata must be an object when set");let t=$n(e.provider,e.model),n=e.vector_dimension;if(!t||typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error("Vectorization embedding metadata must include provider, model, and positive vector_dimension");return{...t,vector_dimension:n}}function Ro(e,t){if(!Number.isInteger(t)||t<=0)throw new Error("Vectorization embedding metadata requires a positive vector dimension");return{provider:e.provider,model:e.model,vector_dimension:t}}function ko(e,t){return!e||e.provider!==t.provider||e.model!==t.model}function Oo(e,t){return!!(e&&e.vector_dimension!==t)}function Do(e,t){if(e.length===0)throw new Error(`${t} returned no vectors`);let n=e[0].length;if(!Number.isInteger(n)||n<=0)throw new Error(`${t} returned an empty vector`);for(let r=1;r<e.length;r+=1)if(e[r]?.length!==n)throw new Error(`${t} returned mixed vector dimensions`);return n}import No from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7113dff5-c8e0-5ba6-b0ae-2ff849ed94df")}catch{}})();var __=["index/manifest.json","search/embeddings.jsonl"],Wa="search/vectorization-status.json";function h_(e,t){return`search_cache_invalidation_failed:${e}:${String(t)}`}function Xe(e){return[...new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ya(e){return typeof e=="string"&&e.trim().length>0&&Number.isFinite(Date.parse(e))}function Ga(e){let t=new Map;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!Ya(r)||t.set(o,r)}return Object.fromEntries([...t.entries()].sort((n,r)=>n[0].localeCompare(r[0])))}async function Ka(e){let t=No.join(e,Wa),n=await C(t);if(n===null||n.trim().length===0)return{entries:{},embedding:null,warnings:[]};let r;try{r=JSON.parse(n)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}if(typeof r!="object"||r===null||r.version!==1||!Array.isArray(r.items))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let o=new Map;for(let s of r.items){if(typeof s!="object"||s===null)return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let a=s.id,c=s.updated_at;if(typeof a!="string"||a.trim().length===0||!Ya(c))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};o.set(a.trim(),c)}let i=null;try{i=qa(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 Xa(e,t,n){let r=Ga(t),o=No.join(e,Wa),i=`${JSON.stringify({version:1,generated_at:$(),...n?{embedding:n}:{},items:Object.entries(r).map(([s,a])=>({id:s,updated_at:a}))},null,2)}
|
|
106
|
-
`;await T(o,i)}function y_(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function g_(e){let t=$n(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function jt(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function w_(e,t,n){if(!n.settings&&!await j(we(e)))return jt(t,"search_semantic_refresh_skipped:settings_not_initialized");let r;try{if(n.settings)r=n.settings;else{let a=await ze(e),c=a.warnings.find(d=>d.startsWith("settings_read_"));if(c)return jt(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);r=a.settings}}catch(a){return jt(t,`search_semantic_refresh_skipped:settings_read_failed:${S(a)}`)}let o=n.apply_runtime_defaults?He(r).settings:r,i=Rn(o).active;if(!i)return jt(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=Mn(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:jt(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function b_(e,t,n,r,o,i){let s=[],a=new Set,c=new Set,d=[];for(let l of r){let u=await Ye(e,l,t,n,o);if(!u){c.add(l);continue}try{let m=await Lt(u,{schema:i});d.push({id:m.document.metadata.id,document:m.document})}catch(m){a.add(u.id),s.push(`search_semantic_refresh_item_read_failed:${u.id}:${S(m)}`)}}return d.sort((l,u)=>l.id.localeCompare(u.id)),{documents:d,missingIds:Xe(c),skippedIds:Xe(a),warnings:s}}async function E_(e,t,n){let r=Ge(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=yo(e),i=n.map(a=>go(a.document,{providerName:t.name,maxCharacters:r,fields:o})),s=await bo(t,e,i);return{vectors:s.vectors,vector_dimension:Do(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function S_(e,t,n){return await xo(e,t.map((r,o)=>({id:r.id,vector:n[o],payload:y_(r.document.metadata)}))),{refreshed:t.map(r=>r.id),skipped:[],warnings:[]}}async function v_(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await Pn(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(n){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${S(n)}`]}}}async function T_(e){let t=[],n=[];for(let r of __){let o=No.join(e,r);try{if(!await j(o))continue;await rt(o),t.push(r)}catch(i){n.push(h_(r,i))}}return{invalidated:t,warnings:n}}async function Ba(e,t,n={}){let r=Xe(t);if(r.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await w_(e,r,n);if(!("settings"in o))return o;let i=it(o.settings,fe()),s=await b_(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 Ka(e):{entries:{},embedding:null,warnings:[]},c=g_(o.provider),d=a.entries,l={refreshed:[],skipped:[],warnings:[]},u=a.embedding;if(s.documents.length>0)if(a.embedding&&ko(a.embedding,c))l={refreshed:[],skipped:s.documents.map(h=>h.id),warnings:["search_semantic_refresh_requires_reindex:embedding_identity_changed"]};else try{let h=await E_(o.settings,o.provider,s.documents);if(Oo(a.embedding,h.vector_dimension))l={refreshed:[],skipped:s.documents.map(w=>w.id),warnings:[...h.warnings,"search_semantic_refresh_requires_reindex:vector_dimension_changed"]};else{u=Ro(c,h.vector_dimension);let w=await S_(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 m=await v_(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,...Ga(y)};for(let w of s.missingIds)delete h[w];try{await Xa(e,h,u)}catch(w){g.push(`search_vectorization_status_ledger_write_failed:${S(w)}`)}g.push(...a.warnings)}return{refreshed:Xe([...l.refreshed,...m.refreshed]),skipped:Xe([...s.skippedIds,...l.skipped,...m.skipped]),warnings:[...s.warnings,...l.warnings,...m.warnings,...g]}}function I_(e,t){let n=t?He(e).settings:e;return!!(Rn(n).active&&Mn(n).active)}async function C_(e,t,n={}){let r=await T_(e),o=Xe(t);if(o.length===0)return{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:r.warnings};if(!await j(we(e))){let c=await Ba(e,o);return{invalidated:r.invalidated,refreshed:c.refreshed,skipped:c.skipped,warnings:[...r.warnings,...c.warnings]}}let i;try{let c=await ze(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&&I_(i,s))return await Ks(e,o),{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:[...r.warnings,"search_semantic_refresh_scheduled_background"],scheduled:!0};let a=await Ba(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 A_}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="225abd7e-ddd7-5597-818d-efadc974b7e3")}catch{}})();var x_=new Set(["1","true","yes","on"]),Fn=["user","automation","test","dogfood"],Ja=new Set(Fn);function Je(e={},t=process.env,n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let r=(t.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();if(Ja.has(r))return{source_context:r,source_context_source:"env_override"};let o=r?"env_override_rejected":"inferred";return jn(t)?{source_context:"test",source_context_source:o}:{source_context:!n||zt("CI",t)||e.json===!0||e.quiet===!0?"automation":"user",source_context_source:o}}function jn(e=process.env){return typeof e.VITEST=="string"||typeof e.VITEST_WORKER_ID=="string"||typeof e.NODE_TEST_CONTEXT=="string"||(e.NODE_ENV??"").trim().toLowerCase()==="test"}var zn=new Set(["stats","ops stats","list","get","next","context","activity","aggregate"]);function Za(e,t,n=process.env){let r=n.PM_TELEMETRY_READ_SAMPLE_RATE?.trim();if(!r||!t||!zn.has(e))return 1;let o=Number(r);return Number.isFinite(o)&&o>0&&o<=1?o:1}function zt(e,t){return x_.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 Ut(e,t=z().endpoint){if(t===null)return e;let n=A_("sha256").update(t).digest("hex").slice(0,16);return e.replace(/\.(jsonl|json)$/u,`.${n}.$1`)}function R_(e){return e.replaceAll(/(\/\/)[^/?#\s]*@/gu,"$1")}function Un(e){let t=e.trim();if(!URL.canParse(t))return R_(t).replace(/[?#].*$/su,"");let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}function Vn(e){return e.replaceAll(/\b[a-z][a-z\d+.-]*:\/\/[^\s"'<>]+/giu,t=>Un(t))}function hT(e,t=process.env){return z(t).endpoint??e}function K(e=process.env){let t=zt("DO_NOT_TRACK",e),n=z(e),r=(e.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase(),o=jn(e)&&!Ja.has(r)&&!zt("PM_TELEMETRY_SEND_TEST_EVENTS",e);return{telemetry_disabled:t||o||n.invalid||zt("PM_TELEMETRY_DISABLED",e)||zt("PM_NO_TELEMETRY",e),do_not_track:t,test_suppressed:o,endpoint_override:n.endpoint===null?null:Un(n.endpoint),endpoint_override_invalid:n.invalid}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a483f454-e261-5232-bae0-da3cdb8c0518")}catch{}})();var ke=Object.freeze({max_bytes:4096,max_depth:8}),Qa=160,k_=new Set(["not_plain_object","unsupported_value","non_finite_number","malformed_unicode","reserved_key","depth_limit","byte_limit","diagnostic_budget"]),tc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,O_=new Set(["__proto__"]),M=class extends Error{reason;path;constructor(t,n){super(t),this.reason=t,this.path=n}};function Lo(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function D_(e,t){return/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function nc(e){if(Buffer.byteLength(e,"utf8")<=Qa)return e;let t="",n=Buffer.byteLength("\u2026","utf8");for(let r of e){if(n+=Buffer.byteLength(r,"utf8"),n>Qa)break;t+=r}return`${t}\u2026`}function Hn(e,t,n){if(e.bytes+=t,!(e.bytes<=ke.max_bytes))throw new M("byte_limit",n)}function rc(e,t,n){if(e.bytes+t>ke.max_bytes)throw new M("byte_limit",n)}function Mo(e,t,n){let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||!("value"in r))throw new M("unsupported_value",n);return r.value}function N_(e,t,n){if(typeof e=="number"&&!Number.isFinite(e))throw new M("non_finite_number",t);if(typeof e=="string"&&(rc(n,e.length+2,t),tc.test(e)))throw new M("malformed_unicode",t);if(e!==null&&!["boolean","number","string"].includes(typeof e))throw new M("unsupported_value",t);return Hn(n,Buffer.byteLength(JSON.stringify(e),"utf8"),t),e}function oc(e,t,n,r){if(typeof e!="object"||e===null)return N_(e,t,r);if(n>=ke.max_depth)throw new M("depth_limit",t);if(Array.isArray(e)){let o=Mo(e,"length",t);if(typeof o!="number"||!Number.isSafeInteger(o)||o<0)throw new M("unsupported_value",t);Hn(r,o>0?o+1:2,t);let i=[];for(let s=0;s<o;s+=1){let a=`${t}[${s}]`;i.push(oc(Mo(e,String(s),a),a,n+1,r))}return i}if(!Lo(e))throw new M("unsupported_value",t);return ic(e,t,n+1,r)}function ic(e,t,n,r){let o=Object.keys(e);Hn(r,o.length>0?o.length+1:2,t);let i={};for(let s of o){rc(r,s.length+3,t);let a=D_(t,s);if(O_.has(s))throw new M("reserved_key",a);if(tc.test(s))throw new M("malformed_unicode",a);Hn(r,Buffer.byteLength(JSON.stringify(s),"utf8")+1,a),i[s]=oc(Mo(e,s,a),a,n,r)}return i}function M_(e){try{if(e instanceof M)return e}catch{}return new M("unsupported_value","details")}function Bn(e){let t=ke.max_bytes,n={bytes:0};try{if(!Lo(e))throw new M("not_plain_object","details");return{ok:!0,details:ic(e,"details",0,n),byte_length:n.bytes}}catch(r){let o=M_(r);return{ok:!1,omission:o.reason==="byte_limit"?{reason:"byte_limit",byte_limit:t}:{reason:o.reason,path:nc(o.path),byte_limit:t}}}}function L_(e){return Bn(e).ok}function sc(e){if(e===void 0)return;let t=Bn(e);return t.ok?{details:t.details}:{details_omitted:t.omission}}function qn(){return{reason:"unsupported_value",path:"details",byte_limit:ke.max_bytes}}function ec(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n?n.value:void 0}function P_(e){if(!Lo(e))return;let t=ec(e,"reason");if(typeof t!="string"||!k_.has(t))return;let n=ec(e,"path"),r=typeof n=="string"?nc(n):void 0;return{reason:t,...r===void 0?{}:{path:r},byte_limit:ke.max_bytes}}function ac(e){let t={};try{if(typeof e!="object"||e===null||Array.isArray(e))return t;for(let[n,r]of Object.entries(Object.getOwnPropertyDescriptors(e)))r.enumerable&&("value"in r?Object.defineProperty(t,n,{value:r.value,enumerable:!0,writable:!0,configurable:!0}):n==="details"&&(t.details_omitted=qn()));return t}catch{return{}}}function cc(e){if(!(typeof e!="object"||e===null))try{let t=Object.getOwnPropertyDescriptor(e,"details");if(t!==void 0&&!("value"in t))return{details_omitted:qn()};if(t!==void 0&&t.value!==void 0)return sc(t.value);let n=Object.getOwnPropertyDescriptor(e,"details_omitted"),r=n!==void 0&&"value"in n?P_(n.value):void 0;return r===void 0?void 0:{details_omitted:r}}catch{return{details_omitted:qn()}}}var dc=new Set(["details","details_omitted"]);function $_(e){let t={};for(let n of Object.keys(e)){if(dc.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 F_(e){if(typeof e!="object"||e===null)return e;try{return Array.isArray(e)?e:{...$_(e),...cc(e)}}catch{return{details_omitted:qn()}}}function Ze(e){let t={};for(let[n,r]of Object.entries(ac(e)))dc.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 j_=12,z_=new Set(["context","error_context"]),U_=new Set(["arguments"]);function lc(e){let t=new WeakSet,n=(r,o)=>{if(typeof r!="object"||r===null||o>j_||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=z_.has(a)?{}:U_.has(a)?[]:d;l!==d&&(i[a]=l),n(l,o+1)}};n(e,0)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e82bc812-181f-57ab-a29a-61703e8bec1b")}catch{}})();function Po(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function vT(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!Po(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return Po(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&Po(t.feasible_tokens)&&t.reason===void 0;case"unavailable":return t.minimum_feasible_tokens===null&&t.feasible_tokens===null&&["query_cost_limit","search_limit","output_constraints"].includes(t.reason);default:return!1}}var V_="PmCliError";function TT(e){if(!Vt(e)||e.code!=="item_already_exists"||e.exitCode!==f.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 H_(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=f.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function q_(e){if(e==null)return{};if(!Object.hasOwn(e,"details"))return e;let t=Object.getOwnPropertyDescriptor(e,"details");if(!("value"in t))throw uc("unsupported_value","details");if(t.value===void 0)return e;let n=Bn(t.value);if(n.ok)return{...e,details:n.details};if(n.omission.reason==="byte_limit"){let{details:r,...o}=e;return{...o,details_omitted:n.omission}}throw uc(n.omission.reason,n.omission.path)}function uc(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 IT(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,H_(t.exitCode??f.USAGE),q_(t.context));return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Vt(e){try{if(!(e instanceof Error)||e.name!==V_)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 Q_}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64589e00-25ef-5d74-a94a-7d40455e1929")}catch{}})();var Wn=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,B_=new RegExp(`(?:\\b|(?<=_))(${Wn.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");function Yn(e,t,n){let r=t;for(;r>0&&e[r-1]==="\\";)r--;let o=n.length>1;if(o&&r===t)return;let i=o?(t-r)*2:t-r+1,s=1;for(;i%2===0;)s*=2,i/=2;let a=o?String.fromCharCode(Number.parseInt(n.slice(1),16)):n;return{index:r,end:t+n.length,identity:`${a}:${s}`,character:a,width:s}}function fc(e,t){let n=/["']|u(?:0022|0027)/gi;n.lastIndex=t.end;for(let r of e.matchAll(n)){let o=Yn(e,r.index,r[0]);if(o?.identity===t.identity)return o.end}return e.length}function W_(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 Y_(e,t){let n=[{character:t.character==="{"?"}":"]",width:t.width}],r=/["'{}[\]]|u(?:0022|0027|007b|007d|005b|005d)/gi;r.lastIndex=t.end;let o;for(;(o=r.exec(e))!==null;){let i=Yn(e,o.index,o[0]);if(!i)continue;let s=i.character;if(s==="{"||s==="["){n.push({character:s==="{"?"}":"]",width:i.width});continue}if(s==="}"||s==="]"){let a=W_(n,i,i.end,e.length);if(a!==void 0)return a;continue}r.lastIndex=fc(e,i)}return e.length}function G_(e,t,n){let r=/^(\\*)(["'{[]|u(?:0022|0027|007b|005b))/i.exec(e.slice(t)),o=r?Yn(e,t+r[1].length,r[2]):void 0;return o?.character==="{"||o?.character==="["?Y_(e,o):o?fc(e,o):n}function K_(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 mc="(?:\\s|\\\\+u(?:0009|000a|000d|0020))*",X_=new RegExp("^"+mc+"(?::|=|\\\\+u(?:003a|003d))"+mc,"iu");function J_(e,t,n){let r=K_(t);if(!Wn.test(r)&&!/\\u/iu.test(r))return;let o=e.slice(n),i=X_.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 Z_(e){let t=new Map,n=[];for(let r of e.matchAll(/["']|u(?:0022|0027)/gi)){let o=Yn(e,r.index,r[0]);if(!o)continue;let i=t.get(o.identity),s=o.end;if(t.set(o.identity,s),i===void 0)continue;let a=J_(e,e.slice(i,o.index),s);a&&n.push(a)}return n}function pc(e){let t=Z_(e);for(let o of e.matchAll(B_)){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=G_(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 wc=new Set(["1","true","yes","on"]);function bc(){return!!(wc.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||K().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}var eh=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,th=/file:\/\/\/?[^\s"'`),;]+/giu,nh=/\b[A-Za-z]:\\[^\s"'`),;]+/g,rh=/\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,oh=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i;var ih=["[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 _c(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&&oh.test(t)&&_c(e))return"[scrubbed_path]";let n=pc(Kt(e)).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(rh,"[scrubbed_ip]").replaceAll(th,"[scrubbed_path]").replaceAll(nh,"[scrubbed_path]").replaceAll(eh,(r,o)=>`${o}[scrubbed_path]`);return _c(n)?"[scrubbed_path]":n}function X(e){let t={};for(let[n,r]of Object.entries(e))Wn.test(n)||n.startsWith("sentry.message.parameter.")?t[n]="[scrubbed]":typeof r=="string"?t[n]=W(r,n):Array.isArray(r)?t[n]=r.map(o=>typeof o=="string"?W(o,n):o&&typeof o=="object"?X(o):o):r&&typeof r=="object"?t[n]=X(r):t[n]=r;return t}function sh(e){for(let n of["filename","absPath","abs_path","module"]){let r=e[n];typeof r=="string"&&(e[n]=W(r,n))}let t=e.context_line;typeof t=="string"&&(e.context_line=W(t,"context_line"));for(let n of["pre_context","post_context"]){let r=e[n];Array.isArray(r)&&(e[n]=r.map(o=>typeof o=="string"?W(o,n):o))}e.vars&&typeof e.vars=="object"&&(e.vars=X(e.vars)),e.data&&typeof e.data=="object"&&(e.data=X(e.data))}var ah=Q_(import.meta.url),ch=()=>ah("@sentry/node"),Gn,hc=!1,dh=ch,lh="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function $o(e){return/^\s*PmCliError:/.test(e)}function Fo(e){let t=e.trim().toLowerCase();return t.length===0?!1:ih.some(n=>t.includes(n))}function uh(e){return e.logger!=="console"?!1:typeof e.message=="string"&&Fo(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(t=>typeof t.value=="string"&&Fo(t.value))}function mh(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 fh(e,t){return t instanceof Error?Vt(t):!!(e.exception?.values?.some(n=>n.type==="PmCliError")||e.exception?.values?.some(n=>typeof n.value=="string"&&$o(n.value))||e.logger==="console"&&typeof e.message=="string"&&$o(e.message))}function Ec(e){return e.category==="console"&&typeof e.message=="string"&&$o(e.message)}function Sc(e){return e.category==="console"&&typeof e.message=="string"&&Fo(e.message)}function ph(){return pr(import.meta.url,["../../.."])??"0.0.0"}function _h(){let e=process.env.SENTRY_ENVIRONMENT?.trim();if(e&&e.length>0)return e;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";let t=Je().source_context;return t==="user"?"production":t}var yc=.2;function vc(){let e=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!e)return yc;let t=Number(e);return!Number.isFinite(t)||t<0||t>1?yc:t}function hh(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)sh(n)}}function Tc(e){if(e.breadcrumbs)for(let t of e.breadcrumbs)t.message&&(t.message=W(t.message)),t.data&&typeof t.data=="object"&&(t.data=X(t.data))}function Ic(e){if(e.contexts)for(let[t,n]of Object.entries(e.contexts))n&&typeof n=="object"&&(e.contexts[t]=X(n))}function gc(e,t){let n=e,r=n[t];r&&typeof r=="object"&&(n[t]=X(r))}function jo(e){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(e==="automation"||e==="test"||e==="dogfood"||e==="user"))return e==="user"?"production":e}function Cc(e){let t=jo(e.tags?.["pm.source_context"]);t&&(e.environment=t)}function Ac(e,t){let n=yh(e.extra);lc([e.contexts,e.extra,e.breadcrumbs]),gh(e.contexts,t),n!==void 0&&(e.extra.error_context=Ze(n))}function yh(e){if(!(typeof e!="object"||e===null||!Object.hasOwn(e,"error_context")))return e.error_context}function gh(e,t){if(typeof e!="object"||e===null||typeof t!="object"||t===null)return;let n=e,r=new Set(wh(t)),o=bh(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 wh(e){try{return[e.name,e.constructor?.name].filter(t=>typeof t=="string"&&t.length>0)}catch{return[]}}function bh(e){try{let t=Ze(e),n=Object.getOwnPropertyDescriptor(e,"context");return n!==void 0&&"value"in n&&(t.context=Ze(n.value)),t}catch{return}}var Eh=(e,t)=>{if(fh(e,t?.originalException)||uh(e))return null;Ac(e,t?.originalException),Cc(e),mh(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")),hh(e),Tc(e),gc(e,"extra"),Ic(e);for(let n of["request","user","tags"])gc(e,n);return e},Sh=e=>(Ac(e),Cc(e),e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(t=>!Ec(t)&&!Sc(t)),Tc(e)),Ic(e),e),vh=e=>X(e),Th=e=>{if(e.message=W(e.message),e.attributes){let t=jo(e.attributes["pm.source_context"]);t&&(e.attributes["sentry.environment"]=t),e.attributes=X(e.attributes)}return e};function Ih(e){let t=jo(e["pm.source_context"]?.value);t&&(e["sentry.environment"]={type:"string",value:t})}function Ch(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){Ih(r);for(let[o,i]of Object.entries(r)){let s=X({[o]:i.value})[o];typeof s=="string"&&(r[o]={type:"string",value:s})}}}}var Ah=e=>Ec(e)||Sc(e)?null:(e.message&&(e.message=W(e.message,"message")),e.data&&typeof e.data=="object"&&(e.data=X(e.data)),e);async function xc(){if(hc)return Gn;if(hc=!0,bc())return;let e=dh(),t=process.env.SENTRY_DSN?.trim()||lh,n=ph();e.init({dsn:t,release:`pm-cli@${n}`,environment:_h(),tracesSampleRate:vc(),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:Eh,beforeSendTransaction:Sh,beforeSendSpan:e.withStreamedSpan(vh),beforeSendLog:Th,beforeBreadcrumb:Ah});let r=e.getClient();if(!r)return;let o=Je();return e.setTags({"pm.version":n,"pm.source_context":o.source_context,"pm.source_context_source":o.source_context_source}),e.setAttribute("pm.source_context",o.source_context),r.on("beforeEnvelope",Ch),Gn=e,e}async function xh(e){if(e!==!0||!wc.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||vc()===0||bc())return!1;try{return await xc()!==void 0}catch{return Gn=void 0,!1}}function Oe(){return Gn}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e8ad404-2f8d-5d9b-9046-60178a70e5b2")}catch{}})();var Ht=class extends p{constructor(t,n,r){super(t,f.GENERIC_FAILURE,n),this.name="ExtensionCommandError",Object.defineProperty(this,"cause",{value:r,configurable:!0,writable:!0})}};function FT(e,t){let n=t.warnings[0]??"extension_command_handler_failed",r=t.errorMessage?.trim();return new Ht(`Command "${e}" failed in extension handler (${n}).${r?` ${r}`:""}`,{code:t.errorCode??"command_failed",nextSteps:t.remediation?[t.remediation]:void 0},t.cause)}function jT(e){return e instanceof p||e instanceof Error?e.message:"Unknown failure"}function Rh(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 kh(e){let t=Math.trunc(e);return t>f.SUCCESS?t:f.GENERIC_FAILURE}function zT(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function UT(e,t){if(e instanceof Error)return e;let n=new Error(t),r=Rh(e);return r!==void 0&&(n.exitCode=kh(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 Oh=new Set(["init","config","completion","completion-statuses","completion-tags","completion-types"]),Dh=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"]),Nh=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"]),Mh=new Set(["test","test-all","test-runs","test-verify","trace-test","test-ping"]),Lh=new Set(["health","validate","normalize","reindex","gc","telemetry","extension-doctor"]);function Ph(e){return e.trim().replaceAll(/\s+/g," ").toLowerCase()}function Rc(e){let t=e?.trim().toLowerCase();return t&&t.length>0?t:void 0}var $h=[{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")}],Fh=new Map([[f.USAGE,"invalid_command_usage"],[f.NOT_FOUND,"item_not_found"],[f.CONFLICT,"lock_conflict"],[f.DEPENDENCY_FAILED,"dependency_failed"]]);function De(e){let t=Ph(e),n=t.length>0?t.split(" "):["<unknown>"],r=n[0],o=n[n.length-1],i="other";return Oh.has(r)?i="setup":Dh.has(r)?i="query":Nh.has(r)?i="mutation":Mh.has(r)?i="testing":r==="extension"?i="extension":Lh.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 zo(e){if(e.ok)return;let t=Rc(e.errorCode);if(t)return t;let n=(e.errorMessage??"").trim().toLowerCase();for(let o of $h)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?Fh.get(r)??"command_failed":"command_failed"}function Qe(e){if(e.ok)return"success";let t=Rc(e.errorCode);return t==="unknown_command"?"nonexistent_command":t==="unknown_option"?"invalid_option":t==="missing_required_option"?"missing_required_option":t==="missing_required_argument"?"missing_required_argument":t==="health_findings"?"health_findings":t==="validation_findings"?"validation_findings":e.errorCategory==="usage"?"invalid_usage":e.errorCategory==="validation"?"validation_failed":e.errorCategory==="conflict"?"conflict":e.errorCategory==="runtime"?"runtime_failed":"unknown_failed"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="10325dfb-128f-5d83-9163-061d8d8b29b6")}catch{}})();var Ne;function ye(e,t,n){if(n===void 0)return;let r=e;typeof r.setAttribute=="function"&&r.setAttribute(t,n)}function et(e,t,n){typeof n=="string"&&n.trim().length>0&&e.setTag(t,n)}function jh(e,t,n){e.setTag("pm.ok",t),e.setTag("pm.command_ok",t),typeof n?.exit_code=="number"&&(e.setTag("pm.exit_code",String(n.exit_code)),e.setTag("pm.command_exit_code",String(n.exit_code))),et(e,"pm.error_code",n?.error_code),et(e,"pm.error_category",n?.error_category),et(e,"pm.command_resolution",n?.command_resolution),et(e,"pm.resolution_stage",n?.resolution_stage)}function zh(e,t,n,r){ye(e,"pm.ok",t),ye(e,"pm.command_ok",t),ye(e,"pm.exit_code",n),ye(e,"pm.command_exit_code",n),ye(e,"pm.error_code",r?.error_code),ye(e,"pm.error_category",r?.error_category),ye(e,"pm.command_resolution",r?.command_resolution),ye(e,"pm.resolution_stage",r?.resolution_stage)}function Uh(e,t,n,r){let o=Oe();if(!o)return;let i=De(e);o.setTag("pm.command",e),o.setTag("pm.command_root",i.command_root),o.setTag("pm.command_family",i.command_family),et(o,"pm.version",r?.pm_version),et(o,"pm.source_context_source",r?.source_context_source),o.setTag("pm.extension.name",r?.extension?.name),o.setTag("pm.extension.version",r?.extension?.version),o.setTag("pm.extension.layer",r?.extension?.layer),typeof r?.source_context=="string"&&r.source_context.trim().length>0&&(o.setTag("pm.source_context",r.source_context),o.setAttribute("pm.source_context",r.source_context));let s=t.map(()=>"[redacted]");o.setContext("pm.command",{name:e,root:i.command_root,leaf:i.command_leaf,family:i.command_family,args:s,option_keys:Object.keys(n).sort(),source_context:r?.source_context,source_context_source:r?.source_context_source}),o.addBreadcrumb({category:"pm.command",message:`pm ${e}`,level:"info",data:{args:s,command_root:i.command_root,command_family:i.command_family,source_context:r?.source_context}})}function Vh(e){let t=Oe();if(!t)return;let n=De(e);Ne=t.startInactiveSpan({op:"pm.command",name:`pm ${e}`,forceTransaction:!0,attributes:{"pm.command":e,"pm.command_root":n.command_root,"pm.command_family":n.command_family}})}function Hh(){Ne=void 0}function qh(e,t,n){if(!Ne)return;let r=e?"true":"false",o=typeof n?.exit_code=="number"?String(n.exit_code):void 0,i=Oe();i&&jh(i,r,n),zh(Ne,r,o,n),Ne.setStatus(e?{code:1}:{code:2,message:t??"command_failed"}),Ne.end(),Ne=void 0}var Bh="unclassified_runtime_error";function Wh(e){let t=typeof e=="object"&&e!==null?e:void 0,n=typeof t?.exitCode=="number",r=n?Math.trunc(t?.exitCode):f.GENERIC_FAILURE;return{error_code:typeof t?.code=="string"&&t.code.length>0&&n?t?.code:Bh,exit_code:r}}function Yh(e){let t=Wh(e);return{"pm.error_code":t.error_code,"pm.exit_code":String(t.exit_code)}}function Gh(e){if(!Xh(e))return;let t=Oe();if(!t)return;let n=Yh(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=Ze(e.context)),t.captureException(e,{extra:r,tags:n})}else t.captureException(new Error(String(e)),{tags:n})}function Kh(e){let t=Oe();if(!t)return;let n=e.command_resolution??Qe({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 Xh(e){if(e instanceof Ht)return!0;if(e instanceof p||Vt(e)||e instanceof Error&&e.name==="AbortError"&&/(?:ctrl\+[cd]|sigint|user[- ]initiated)/i.test(e.message))return!1;if(typeof e=="object"&&e!==null&&"exitCode"in e&&typeof e.exitCode=="number"){if(e instanceof Error&&e.name==="CommandError")return!1;let t=Math.trunc(e.exitCode);return!new Set([f.SUCCESS,f.USAGE,f.NOT_FOUND,f.CONFLICT]).has(t)}return!0}async function Jh(e=3e3){let t=Oe();if(t)try{await t.flush(e)}catch{}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="14a5d95f-9996-5e0a-a029-b53f3a2385e6")}catch{}})();var Me=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,R="[/\\\\]+",Zh="[\\p{L}\\p{N}._@-]+",Le=Zh+"(?:"+R+Me+")*",Kn="(?:(?:home|users)"+R+Le+"|root"+R+Le+")",Qh="[/\\\\]"+Kn,ey="[/\\\\]{2,}"+Kn,ty="/?[a-z]:"+R+"users"+R+Le,ny=Me+"(?: +"+Me+")*",Uo="(?:"+ny+R+")?users"+R+Le,ry="[/\\\\]{2,}"+Me+R+Uo,oy="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+Me+")",zc="[/\\\\]{2}[?.]"+R+"(?:unc"+R+Me+R+Uo+"|"+oy+R+"users"+R+Le+")",iy="file:(?:"+zc+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+R+")(?:"+Kn+"|[a-z]:"+R+"users"+R+Le+")|[/\\\\]{2}(?:[a-z]:"+R+"users"+R+Le+"|"+Me+R+"(?:"+Kn+"|"+Uo+")))",sy=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+Qh+"|"+ty+"|"+iy+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+ey+"|"+ry+"|"+zc+")","giu"),kc=4,ay=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,cy=new TextDecoder("utf-8");function dy(e){return e.replace(/(?:%[a-f0-9]{2})+/giu,t=>cy.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 ly(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 uy(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 my(e,t){for(let[n,r]of[["percent_decode",dy],["json_unescape",ly],["unicode_fold",uy]]){let o=r(e);o!==e&&!t.includes(n)&&t.push(n),e=o}return e}function*fy(e,t,n){let r=e,o=[];for(let i=0;i<kc;i+=1){let s=r;if(r=my(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===kc-1&&ay.test(r)&&(yield{index:0,normalizations:[...o],normalization_incomplete:!0})}}function*py(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 fy(r,t,o))yield{...i,index:n};n+=r.length+1}}var Oc="password|passphrase",Dc=/(?:(?!<|\$\{|\$\(|config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))[A-Za-z0-9!@#$%^&*._+\-=]{8,}|"(?!<|\$\{|\$\()[^"]{8,}"|'(?!<|\$\{|\$\()[^']{8,}')/,Nc="token|secret|password|passwd|api[_-]?key",Mc="(?<![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))",Lc=/(?:"(?=[^"\s]{8,}")|'(?=[^'\s]{8,}')|(?!["']))((?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.)+[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+)*|(?:[\w.-]+\/)+[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.)+[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+)*|(?:[\w.-]+\/)+[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+)*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.)+[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/)+[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}(?=[\s,;)}\]]|$)|(?<!["'])[\w$.]+\()(?:(?<=")[^\s"]{8,}|(?<=')[^\s']{8,}|(?<==)[A-Za-z0-9!@#$%^&*._+\-=/~?:|]{8,}|(?<!["'=])[A-Za-z0-9!@#$%^&*._+\-=/~]{8,}))/,Pc=/["']?([A-Za-z0-9+/=_-]{24,})/,Uc=[{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(?:${Oc})\s*[:=]\s*`+Dc.source,"gi"),structured:{keys:Oc,value:Dc.source,element:!0}},{name:"absolute-home-path",mutationRule:"absolute_home_path",regex:sy,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",regex:/\b[A-Za-z0-9._-]+@(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,excludeFiles:/^(?:tests\/|examples\/)/},{name:"high-entropy-assignment",mutationRule:"high_entropy_assignment",regex:new RegExp(String.raw`\b(?:${Nc})\s*[:=]\s*`+Pc.source,"gi"),structured:{keys:Nc,value:Pc.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(?:${Mc})\s*[:=]\s*`+Lc.source,"gi"),structured:{keys:Mc,value:Lc.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,rejectValue:/^(?:[\w.-]+\/)*id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(?:\.pub)?$/u,rejectStatementReference:/^[A-Z]+(?:_[A-Z]+)+$/u}];function*Vc(e,t){if(e.mutationRule==="absolute_home_path"){yield*py(t,e.regex);return}e.regex.lastIndex=0;for(let n of t.matchAll(e.regex))Vo(e,n)&&(yield{index:n.index});e.structured&&(yield*Ay(e,e.structured,t))}var $c=new Map,Fc=/[\r\n\u2028\u2029]/u;function _y(e){let t=`${e.keys}\0${e.value}\0${e.element===!0}`,n=$c.get(t);return n||(n={key:new RegExp(String.raw`\b(?:${e.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(e.value,"iy"),...e.element?{element:new RegExp(String.raw`<(?:${e.keys})(?:\s[^<>]*)?>([^<]*)<\/(?:${e.keys})\s*>`,"gi")}:{}},$c.set(t,n)),n}function Hc(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 hy(e,t){return Hc(e,t).end}function yy(e,t,n){return e.at(-1)==="}"?n:t}function gy(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&&yy(o,n,r)(s))return{found:!0,end:s};s=hy(e,s)-1;break;default:break}}return{found:!1,end:e.length}}var wy=/\\(?: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,by={n:`
|
|
108
|
-
`,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function jc(e,t){let n=e[0],r=e.slice(1,t?-1:void 0).replaceAll(wy,o=>{let i=o[1];if((i==="u"||i==="x")&&o.length>2)return String.fromCharCode(Number.parseInt(o.slice(2),16));if(/^[0-7]$/u.test(i))return String.fromCharCode(Number.parseInt(o.slice(1),8));if(i==="U"&&o.length===10){let s=Number.parseInt(o.slice(2),16);return s<=1114111?String.fromCodePoint(s):"\uFFFD"}return by[i]??i}).replaceAll(n,n==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," ");return`${n}${r}${t?n:""}`}var Ey=64;function Sy(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-Ey);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 vy(e,t,n){let r=(s,a)=>{t.lastIndex=a;let c=t.exec(s);return c!==null&&!Fc.test(c[0])&&Vo(e,c)?c:null},o=s=>{if(n[s]!=='"'&&n[s]!=="'")return;let{end:a,terminated:c}=Hc(n,s),d=n.slice(s,a);return d.includes("\\")?Fc.test(d)?[]:(n[s]==="'"?[jc(d,c),d]:[jc(d,c)]).map(l=>r(l,0)).filter(l=>l!==null):void 0},i=s=>{let a=o(s);if(a!==void 0)return a;let c=r(n,s);return c===null?[]:[c]};return{direct:s=>r(n,s)!==null,escaped:s=>(o(s)?.length??0)>0,accepts:s=>a=>i(a).some(c=>!(s&&/\s/u.test(c[0])))}}function*Ty(e,t,n){e.lastIndex=0;for(let r of t.matchAll(e)){let o=r[1].trim();(n?n(o):o.length>=8&&!o.startsWith("${")&&!o.startsWith("$("))&&(yield{index:r.index})}}function Iy(e,t,n){return t<e.exact||n&&t<e.compact}function Cy(e,t,n,r){return(n||e.escaped(r)&&!e.direct(r))&&t(r)}function*Ay(e,t,n){let r=_y(t),o=vy(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=Sy(n,a.index,c);if(d==="malformed")continue;let l=d==="prefixed",u=o.accepts(l),m=a.index+a[0].length,_=n[m];if(_==="["||_==="{"){if(Iy(s,m,l))continue;let y=gy(n,m,u,o.accepts(!0));s[l?"compact":"exact"]=y.end,y.found&&(yield{index:a.index})}else Cy(o,u,c,m)&&(yield{index:a.index})}r.element&&(yield*Ty(r.element,n,xy(e,t,r)))}function xy(e,t,n){if(t.elementValue)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,Vo(e,i))}}function Ry(e,t){let n=t.index+t[0].length,r=t.input[n-t[1].length-1];return/^[ \t]*;/u.test(t.input.slice(n,n+64))&&r!=='"'&&r!=="'"&&e.test(t[1])}function Vo(e,t){if(e.rejectValue?.test(t[1])===!0||e.rejectStatementReference&&Ry(e.rejectStatementReference,t))return!1;if(e.minimumEntropy===void 0)return!0;let n=[...t[1]],r=new Map;for(let i of n)r.set(i,(r.get(i)??0)+1);let o=0;for(let i of r.values()){let s=i/n.length;o-=s*Math.log2(s)}return o>=e.minimumEntropy}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6059407-bf03-5ae8-8b01-e3e7c5b28030")}catch{}})();var ky=[{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"}],qo=new Map(ky.map(e=>[e.action,e]));function Ho(e,t="$",n=new WeakSet){return typeof e=="string"?[{path:t,value:e}]:typeof e!="object"||e===null?[]:n.has(e)?[]:(n.add(e),Array.isArray(e)?e.flatMap((r,o)=>Ho(r,`${t}[${o}]`,n)):Object.entries(e).flatMap(([r,o])=>Ho(o,`${t}.${r}`,n)))}function Oy(e,t){let n=Vc(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 qc(e){let t=[];for(let n of Ho(e))for(let r of Uc){let o=Oy(r,n.value);if(o){let i={rule:r.mutationRule,path:n.path};o.normalizations&&(i.normalizations=o.normalizations),o.normalization_incomplete&&(i.normalization_incomplete=!0),t.push(i)}}return t.filter((n,r,o)=>o.findIndex(i=>i.rule===n.rule&&i.path===n.path)===r)}function Dy(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.",f.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=qc(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.`,f.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 Ny(e){return qo.has(e.trim().toLowerCase())}function My(){return[...qo.keys()].sort((e,t)=>e.localeCompare(t))}function rI(e){return qo.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 Ly=/\b([a-z][a-z0-9]*)-(\d+)(?:-[a-z0-9]+)*\b/giu,Py=/^(?:utf|iso|sha|tls|http|covid|match)$/iu;function Bo(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Wc(e){return[...new Set(Bo(e).match(/[\p{L}\p{N}]+/gu)??[])]}function Bc(e){let t=Bo(e);return{normalized:t,tokens:Wc(t),issueCodes:[...new Set([...e.matchAll(Ly)].filter(n=>{let r=n[1],o=n.index,i=e.slice(o+n[0].length);return!Py.test(r)&&(r===r.toUpperCase()||r.length<=2||o===0&&/^\s*(?::|—|–|\])/u.test(i))}).map(n=>n[0].toLowerCase()))]}}function $y(e,t){return Fy(Bc(e),Bc(t))}function Fy(e,t){if(e.normalized===t.normalized)return{score:1,reason:"exact_title"};let n=new Set(e.issueCodes);return t.issueCodes.some(r=>n.has(r))?{score:.99,reason:"issue_code"}:{score:Xt(e.tokens,t.tokens),reason:"title_token_jaccard"}}import jy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a7cd1d62-16fe-5e5b-b382-64335fc5e403")}catch{}})();function Xn(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function zy(e,t){return[e.updated_at,t].map(n=>({value:n,time:Date.parse(n??"")})).filter(n=>typeof n.value=="string"&&Number.isFinite(n.time)).sort((n,r)=>r.time-n.time)[0]?.value??e.updated_at}function Yc(e,t){let n=Math.max(1,Math.trunc(t.threshold_hours)),r=(t.now??new Date).getTime(),o=Xn(t.in_progress_status),i=[];for(let s of e){if(Xn(String(s.status))!==o||(s.assignee?.trim().length??0)>0)continue;let a=zy(s,t.last_history_activity?.(s)),c=Date.parse(a);if(!Number.isFinite(c))continue;let d=Math.max(0,Math.floor((r-c)/36e5));d>=n&&i.push({id:s.id,last_activity_at:a,age_hours:d})}return i.sort((s,a)=>a.age_hours-s.age_hours||s.id.localeCompare(a.id)),{threshold_hours:n,count:i.length,items:i,remediation:"Claim active work with `pm claim <id>` or return abandoned work to open with `pm update <id> --status open`."}}async function Uy(e,t,n){let r=new Map;return await Promise.all(t.filter(o=>Xn(String(o.status))===Xn(n.in_progress_status)&&(o.assignee?.trim().length??0)===0).map(async o=>{let i;try{i=await ft(jy.join(e,"history",`${o.id}.jsonl`),o.id)}catch{return}let s=i.map(a=>a.ts).filter(a=>Number.isFinite(Date.parse(a))).sort((a,c)=>Date.parse(c)-Date.parse(a))[0];s&&r.set(o.id,s)})),Yc(t,{...n,last_history_activity:o=>r.get(o.id)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab644545-f072-53c0-9ebf-72a62c237a2f")}catch{}})();var Vy=Object.freeze({"<":"<",">":">",""":'"',"'":"'","&":"&"}),Hy=/&(?:lt|gt|quot|#39|amp);/g;function qy(e){return typeof e!="string"||!e.includes("<")&&!e.includes(">")?e:e.replace(Hy,t=>Vy[t])}function By(e){return Wo(e,new WeakMap)}function Wo(e,t){if(typeof e=="string")return qy(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(Wo(r,t));return n}if(e!==null&&typeof e=="object"){if(!Wy(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:Wo(i,t),enumerable:!0,writable:!0,configurable:!0});return r}return e}function Wy(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 Yy(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 Gc(e){return e.split(/[\s,|]+/).map(t=>t.trim()).filter(t=>t.startsWith("--"))}function Gy(e){return Gc(e)[0]??null}function Ky(e,t){let n=Gy(t);if(n===null)return!1;let r=o=>o.slice(2).replaceAll("-","_");return Gc(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 Xy(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 Yo from"node:fs/promises";import Jn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12ee7de1-dff4-53f1-8d0d-d8b1c1ebea42")}catch{}})();function Jy(e){return"json_markdown"}function Kc(e,t){return Jn.relative(e,t).replaceAll("\\","/")}function Zy(e){return String(e).replaceAll(/[^a-zA-Z0-9._-]+/g,"_").slice(0,120)}async function Qy(e,t,n){e!==t&&ce(await Yo.readFile(t,"utf8"),{format:"json_markdown",requireSupportedFormat:!0,schema:n})}async function eg(e,t,n="item_format:migrate",r=ee,o){if(t!=="toon")throw new Error("Only toon item-format migration targets are supported. Markdown item files are legacy read-only input.");let i=new Set,s=new Set,a=[],c=0,d=Jy(t),l=Object.entries(r);for(let[u,m]of l){let _=Jn.join(e,m),y=[];try{y=await Yo.readdir(_)}catch{continue}let g=new Map;for(let w of y){let b=Jn.join(_,w),I=st(b);if(!I)continue;let A=Jn.extname(w),L=w.slice(0,w.length-A.length).trim();if(L.length===0)continue;let x=g.get(L)??{};x[I]=b,g.set(L,x)}let h=[...g.keys()].sort((w,b)=>w.localeCompare(b));for(let w of h){let b=g.get(w);c+=1;let I=b[d];if(!I)continue;let A=b[t]??I,L=A===b[t]?t:d;try{let x=await Yo.readFile(A,"utf8"),D=ce(x,{format:L,requireSupportedFormat:!0,schema:o,onWarning:Q=>a.push(`item_format_migration_parse_warning:${w}:${Q}`)});await Qy(A,I,o);let Z=$e(e,u,w,t,r),ae=mt(D,{format:t,schema:o});await C(Z)!==ae&&(await T(Z,ae),a.push(...await U({path:Z,scope:"project",op:n})),i.add(w)),await rt(I),s.add(Kc(e,I)),a.push(...await U({path:I,scope:"project",op:`${n}:remove`})),i.add(w)}catch(x){a.push(`item_format_migration_skipped:${Kc(e,A)}:${Zy(x)}`)}}}return{target_format:t,scanned:c,migrated:[...i].sort((u,m)=>u.localeCompare(m)),removed:[...s].sort((u,m)=>u.localeCompare(m)),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 tg=new Set(["completed","superseded"]);function ng(e){return e!==void 0&&tg.has(e)}function rg(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 og}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 ig=/^[a-z][a-z0-9_-]{0,63}$/u,sg=new Set(["constructor","prototype"]),Xc="settings:section:write",ag=240;function Zn(e){return`sha256:${og("sha256").update(Go(e)).digest("hex")}`}function Go(e){return Array.isArray(e)?`[${e.map(t=>Go(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Go(Object.getOwnPropertyDescriptor(e,t)?.value)}`).join(",")}}`:String(JSON.stringify(e))}function Zc(e){if(!ig.test(e)||sg.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.`,f.USAGE,{code:"settings_section_name_invalid",field:"section",required:"Name the section after the package, for example lint or jev."});if(Bi.includes(e))throw new p(`Settings section "${e}" is owned by core settings; extension sections must use another name.`,f.USAGE,{code:"settings_section_reserved",field:"section",value:e,required:"Read core settings with readSettings and change them with writeSettings or pm config."})}function Qc(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.",f.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 Ko(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,ag)}`,f.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 ed(e){return typeof Reflect.get(e,"toJSON")=="function"}function Xo(e){return e.length===0?"the value":e.join(".")}function td(e,t){return Object.values(Object.getOwnPropertyDescriptors(e)).every(n=>"value"in n&&(!t||n.enumerable===!0))}function cg(e){if(Object.getPrototypeOf(e)!==Array.prototype||!td(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&&!ed(e)}function dg(e){let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&td(e,!0)&&Object.getOwnPropertySymbols(e).length===0&&!ed(e)}function lg(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return null;let n=Xo(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 nd(e,t=[],n=new Set){if(typeof e!="object"||e===null)return lg(e,t);let r=Xo(t);if(n.has(e))return{detail:`${r} is a circular reference`,representable:!1};if(!(Array.isArray(e)?cg(e):dg(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=nd(i,[...t,o],n);if(s!==null)return s}return n.delete(e),null}function rd(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 Xo(o);let i=rd(r,o);if(i!==null)return i}return null}function Jc(e,t,n){return Ko(e,t,()=>{throw new Error(n)})}function ug(e,t){let n=nd(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 Jc(e,t,o)}let r=rd(t);return r!==null?Jc(e,t,`${r} is a reserved key that settings history cannot record`):JSON.parse(JSON.stringify(t))}function od(e,t){return Object.hasOwn(e,t)?e[t]:void 0}async function mg(e,t,n={}){Zc(t);let r=we(e);await Se({path:r,scope:"project"});let o=await C(r),i=o===null?void 0:od(Qc(o),t);if(i===void 0)return{section:t,source:"default",value:n.defaultValue,revision:null};let s=Zn(i);return{section:t,source:"stored",value:Ko(t,structuredClone(i),n.validate),revision:s}}async function fg(e,t,n,r={}){Zc(t);let o=n===void 0?void 0:ug(t,Ko(t,n,r.validate)),i=we(e),s=await Y(e);try{let a=await vr({pmRoot:e,filePath:i,op:Xc,author:dt(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.",f.NOT_FOUND,{code:"settings_section_document_missing",required:"Initialize the tracker with pm init, then retry."});let d=Qc(c),l=od(d,t),u=l===void 0?null:Zn(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.`,f.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 m={section:t,changed:!1,previous_revision:u,revision:o===void 0?null:Zn(o)};return nt(l,o)?{raw:c,result:m}:(o===void 0?delete d[t]:d[t]=o,{raw:`${JSON.stringify(d,null,2)}
|
|
110
|
-
`,result:{...m,changed:!0}})}});return a.changed&&await U({path:i,scope:"project",op:Xc}),a.result}finally{rn(e)}}import pg from"node:readline/promises";import{stdin as _g,stdout as id}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 hg="PM_TELEMETRY_PROMPT",sd=new Set(["0","false","no","off"]),yg=new Set(["init","completion","completion-statuses","completion-tags","completion-types"]);function gg(e){return typeof e!="string"?!1:sd.has(e.trim().toLowerCase())}function wg(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t.length===0?!1:!sd.has(t)}function bg(e,t){if(t.json===!0||t.quiet===!0||process.stdin.isTTY!==!0||process.stdout.isTTY!==!0||gg(process.env[hg])||wg(process.env.CI))return!0;let n=e.trim().toLowerCase();return n.length===0?!0:yg.has(n)}function Eg(e){let t=e.trim().toLowerCase();return!(t==="n"||t==="no")}async function Sg(e){let t=`pm telemetry helps improve reliability and usage diagnostics.
|
|
111
|
-
It is enabled by default and can be changed anytime via:
|
|
112
|
-
pm config global set telemetry-tracking --policy disabled
|
|
113
|
-
Enable telemetry now? [${e?"Y/n":"y/N"}] `,n=pg.createInterface({input:_g,output:id});try{let r=await n.question(t);return r.trim().length===0?e:Eg(r)}finally{n.close()}}async function vg(e,t){if(!(K().telemetry_disabled||bg(e,t)))try{let n=me(process.cwd()),r=await Y(n);if(r.telemetry.first_run_prompt_completed||yt(r))return;let o=await Sg(r.telemetry.enabled);r.telemetry.enabled=o,r.telemetry.first_run_prompt_completed=!0,await gt(n,r,"telemetry:first_run_prompt"),id.write(`Telemetry ${o?"enabled":"disabled"} for this CLI install. Update any time with pm config global set telemetry-tracking --policy ${o?"disabled":"enabled"}.
|
|
114
|
-
`)}catch{}}import J from"node:crypto";import{spawn as Cg}from"node:child_process";import{mkdirSync as Jo,rmSync as Ag,statSync as gd}from"node:fs";import{mkdir as Zo,readdir as xg,rm as ii,stat as wd}from"node:fs/promises";import{request as Rg}from"node:http";import{request as kg}from"node:https";import si from"node:os";import O from"node:path";import Tg 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 ad(e,t,n,r=process.env,o=Date.now()){if(!n||!zn.has(t))return 1;if(r.PM_TELEMETRY_READ_SAMPLE_RATE!==void 0)return Za(t,!0,r);try{let i=Tg.join(e,"runtime","telemetry","read-sampling.json"),s=Math.floor(o/6e4),a=Ig(await C(i),s),c=Math.min(Number.MAX_SAFE_INTEGER,(a[t]??0)+1);return a[t]=c,await T(i,`${JSON.stringify({minute:s,counts:a})}
|
|
115
|
-
`),Math.min(1,(10/c)**2)}catch{return 1}}function Ig(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))zn.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 Og=O.join("runtime","telemetry","events.jsonl"),Dg=O.join("runtime","telemetry","state.json"),Ng=O.join("runtime","telemetry","otel-spans.jsonl"),Mg=8,cd=500,nr=1,dd=1,Lg=100,Pg=36e5,$g=3e4,ld=2e4,Fg=1e3,jg=25e3,ai=250,zg=864e5,rr=65536,bd=6,Ed=20,Sd=15,Ug=8192,vd=[25,50,100,200],Vg=3600*1e3,Hg=1440*60*1e3,Td=6e4,qg=6e4,Bg="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",Wg="OTEL_EXPORTER_OTLP_ENDPOINT",Yg="OTEL_SERVICE_NAME",Gg="PM_TELEMETRY_OTEL_DISABLED",Kg=new Set(["1","true","yes","on"]),Xg="PM_TELEMETRY_INLINE_FLUSH",ue="PM_TELEMETRY_FLUSH_CHILD",Jg="PM_TELEMETRY_HTTP_TIMEOUT_MS",Zg=globalThis.fetch,ud=!1,Qo=Promise.resolve(),md=Promise.resolve(),Qn=new WeakMap;var Qg=new Set(["1","true","yes","on"]),ew=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]),or=J.randomUUID(),tw=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],nw=new Set(["literal","literals","regex","regexes","replacement","replacements","setjson","set_json","update"]),Id="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",rw=new RegExp(`\\b(${Id})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),ow=new RegExp(`(--${Id})(=|\\s+)([^\\s,;]+)`,"giu"),iw=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,sw=/bearer\s+[a-z0-9._=-]+/giu,aw=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function qt(e,t=z().endpoint){return O.join(O.dirname(O.join(e,Og)),Ut("events.jsonl",t))}function Bt(e){return O.join(e,Ng)}function cw(e){return O.dirname(qt(e,null))}function Cd(e,t=z().endpoint){return O.join(O.dirname(O.join(e,Dg)),Ut("state.json",t))}function ci(e){return O.join(e,"runtime","telemetry","flush.lock")}function Ad(e){return O.join(e,"runtime","telemetry","flush.spawn.lock")}function dw(){return O.join(ct(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function lw(){return se(process.env[Xg])||se(process.env[ue])?!0:jn()}async function uw(e,t=z().endpoint){let n=await C(Cd(e,t));if(!n||n.trim().length===0)return{};try{let r=JSON.parse(n);return typeof r!="object"||r===null||Array.isArray(r)?{}:r}catch{return{}}}async function er(e,t,n=z().endpoint){try{await ge(async()=>{let r={...await uw(e,n),...t},o=Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0).sort((i,s)=>i[0].localeCompare(s[0])));await T(Cd(e,n),`${JSON.stringify(o,null,2)}
|
|
116
|
-
`,{createParentDirectories:!se(process.env[ue])})},e)}catch{}}function ti(e){let t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),n=t.split("_").filter(r=>r.length>0);return nw.has(t)||tw.some(r=>t===r||t.endsWith(`_${r}`)||n.includes(r))}function xd(e){return e.replaceAll(rw,(t,n,r)=>`${n}${r}[redacted]`).replaceAll(ow,(t,n,r)=>`${n}${r}[redacted]`)}function Rd(e){return e.replaceAll(iw,(t,n)=>`${n}[redacted_path]`)}function kd(e){let t=e>=65&&e<=90,n=e>=97&&e<=122,r=e>=48&&e<=57;return t||n||r}function Od(e){if(!e)return!1;let t=e.charCodeAt(0);return kd(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function Dd(e){if(!e)return!1;let t=e.charCodeAt(0);return kd(t)?!0:e==="."||e==="-"}function mw(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(!Od(i))return!1;for(let i of r)if(!Dd(i))return!1;return!0}function fw(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&&Od(e[o]);)o-=1;o+=1;let i=r+1;for(;i<e.length&&Dd(e[i]);)i+=1;let s=e.slice(o,i);if(mw(s)){t+=e.slice(n,o),t+="[redacted_email]",n=i;continue}t+=e.slice(n,r+1),n=r+1}return t}function Nd(e){return fw(Kt(e)).replaceAll(sw,"bearer [redacted_token]").replaceAll(aw,"[redacted_ip]")}function pw(e){let t=Nd(e),n=xd(t),r=Rd(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>512?`${r.slice(0,509)}...`:r}function _w(e){let t=Nd(e),n=xd(t),r=Rd(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"?_w(e):pw(e)}function Pe(e,t,n="redacted",r=0){if(t&&ti(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>=bd)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,Ed).map(o=>Pe(o,void 0,n,r+1));if(typeof e=="object"){let o=e,i={};for(let[s,a]of Object.entries(o))i[s]=Pe(a,s,n,r+1);return i}return String(e)}function Md(e,t="redacted"){let n=[],r=!1;for(let o of e){let i=k(Ri(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);ti(c)?n.push(`--${c}=[redacted]`):n.push(`--${c}=${k(d,t)}`);continue}if(ti(s)){n.push(`--${s}`),r=!0;continue}}n.push(i)}return n}function hw(e){let t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function se(e){return Qg.has((e??"").trim().toLowerCase())}function fd(){let e=process.env[Jg]?.trim();if(!e)return ld;let t=Number(e);return Number.isFinite(t)?Math.min(jg,Math.max(Fg,Math.trunc(t))):ld}async function Ld(e,t,n){let r=new URL(e);if(globalThis.fetch!==Zg){let i=new AbortController,s,a=new Promise((c,d)=>{s=setTimeout(()=>{i.abort(),d(new Error("telemetry_http_timeout"))},fd())});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:"?kg:r.protocol==="http:"?Rg:void 0;if(!o)throw new Error(`telemetry_http_protocol_unsupported_${r.protocol}`);return new Promise((i,s)=>{let a=fd(),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 Pd(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function di(e){let t=e?.trim();return t&&t.length>0?t:void 0}function li(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function $d(e){if(!e.ok)return typeof e.errorCategory=="string"&&e.errorCategory.trim().length>0?e.errorCategory:typeof e.errorCode=="string"&&e.errorCode.trim().length>0?Yt(e.errorCode):"unknown"}function Fd(e){let t=Je(e);return t.source_context_source==="env_override_rejected"&&!ud&&!e.quiet&&(ud=!0,process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${Fn.join("|")}; ignoring override.
|
|
117
|
-
`)),t}function F(e,t){return J.createHash("sha256").update(`${e}:${t}`).digest("hex")}function ui(e,t){let n=(hr()??"").trim(),r=Pi({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?ew.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 ni(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=bd)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,Ed).map(n=>ni(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]=ni(n[i],t+1);return r}return String(e)}function ri(e,t){return F(e,JSON.stringify(ni(t)))}function jd(e,t){return{hashes:t.map(n=>F(e,n)),digest:F(e,t.join("\0"))}}function zd(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 yw(){if(Kg.has((process.env[Gg]??"").trim().toLowerCase()))return null;let e=(process.env[Bg]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}let t=(process.env[Wg]??"").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 pd(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 gw(e,t){return{key:e,value:{boolValue:t}}}function _d(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function ww(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[Yg]??"").trim()),a=s.length>0?s:"pm-cli",c=li(t.exit_code,t.ok),d=di(t.error_code),l=$d({ok:t.ok,errorCode:d,errorCategory:t.error_category}),u=[V("pm.command",k(e.command)),V("pm.version",e.pm_version),V("pm.source_context",e.source_context),V("pm.source_context_source",e.source_context_source),V("pm.installation_id",e.installation_id),V("pm.session_id",or),V("pm.pm_root_hash",e.pm_root_hash),V("pm.cwd_hash",e.cwd_hash),gw("pm.ok",t.ok),_d("pm.exit_code",c),_d("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 m={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:pd(e.started_at),endTimeUnixNano:pd(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:m}}function bw(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:k(e,t)};if(typeof e=="number"||typeof e=="boolean")return{type:typeof e,value:e};if(Array.isArray(e))return{type:"array",length:e.length,sample:e.slice(0,5).map(n=>Pe(n,void 0,t))};if(typeof e=="object"){let n=e,r=Object.keys(n).filter(s=>s!=="tests").sort((s,a)=>s.localeCompare(a)),o={},i=0;for(let s of r.slice(0,25)){let a=Pe(n[s],s,t);if(a===void 0)continue;let c=JSON.stringify(a).length;if(i+c>Ug){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 Ew(e){let{captureLevel:t,context:n,pmVersion:r,sourceContext:o,pmRootHash:i,cwdHash:s,installationId:a}=e,c=De(n.command),d=jd(a,n.args),l=F(a,`${n.command}\0${n.args.join("\0")}`),u=ri(a,n.options),m=ri(a,n.global),_=ui(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:m,..._}:{pm_version:r,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,..._,command_args:Md(n.args,t),command_args_hashes:d.hashes,command_args_digest:d.digest,command_invocation_digest:l,command_options:Pe(n.options,void 0,t),command_options_digest:u,global_options:Pe(n.global,void 0,t),global_options_digest:m,pm_root_hash:i,cwd_hash:s,capture_level:t,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:F(a,si.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function Sw(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:m,commandResolution:_,resolutionStage:y}=e,g=o.ok===!1?zd(c,a,u,o.error):void 0,h=ui(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:m,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:m,error:o.error?k(o.error,t):void 0,error_fingerprint:g,duration_ms:i,started_at:s,result_summary:bw(o.result,t)}}function vw(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:m,errorCode:_,errorMessage:y,errorCategory:g,exitCode:h}=e,w=jd(m,c),b=F(m,o),I=ri(m,d),A=zd(m,o,_,y),L=ui(t,m);return t==="minimal"?{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,attempted_command_digest:b,attempted_args_digest:w.digest,attempted_options_digest:I,error_code:_,error_category:g,exit_code:h,error:k(y,"redacted"),error_fingerprint:A,...L}:{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,...L,attempted_command:k(o,t),attempted_command_digest:b,attempted_args:Md(c,t),attempted_args_hashes:w.hashes,attempted_args_digest:w.digest,attempted_options:Pe(d,void 0,t),attempted_options_digest:I,error_code:_,error_category:g,exit_code:h,error:k(y,t),error_fingerprint:A,pm_root_hash:l,cwd_hash:u,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:F(m,si.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function mi(e){let t=await Y(e);if(!t.telemetry.enabled||K().telemetry_disabled)return null;if(t.telemetry.installation_id.trim().length===0){if(Ir(e)||yt(t))return null;t.telemetry.installation_id=J.randomUUID(),await gt(e,t,"telemetry:install_id")}return{installationId:t.telemetry.installation_id,endpoint:t.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(t.telemetry.retention_days)),captureLevel:hw(t.telemetry.capture_level)}}async function tr(e,t){let n=JSON.stringify({client_schema_version:dd,event:t,attempts:0});if(n.length>rr){let r={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:n.length}}};n=JSON.stringify({client_schema_version:dd,event:r,attempts:0})}await dr(qt(e),n)}function Ud(e){let t=[];for(let n of e.split(`
|
|
118
|
-
`)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);o&&typeof o=="object"&&o.event&&typeof o.event=="object"&&typeof o.attempts=="number"&&(o.client_schema_version===void 0||typeof o.client_schema_version=="number"&&Number.isFinite(o.client_schema_version))&&t.push(o)}catch{}}return t}function Vd(e){let t=Math.min($g*2**Math.max(e-1,0),Pg);return new Date(Date.now()+t).toISOString()}function fi(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 Hd(e){return fi(e.next_attempt_after)}function qd(e){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*zg}function Tw(e,t){let n=e.event?.occurred_at;if(typeof n!="string"||n.trim().length===0)return!1;let r=Date.parse(n);return Number.isNaN(r)?!1:r<t}function ir(e,t){let n=qd(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>rr||Tw(i,n)||i.attempts>=Sd){o+=1;continue}r.push(i)}return{entries:r,prunedCount:o}}async function Bd(e,t,n=z().endpoint){let r=t.map(i=>JSON.stringify(i)).join(`
|
|
119
|
-
`),o=r.length>0?`${r}
|
|
120
|
-
`:"";for(let i=0;;i+=1)try{await T(qt(e,n),o,{createParentDirectories:!se(process.env[ue])});return}catch(s){let a=vd[i];if(a===void 0||!Wd(s))throw s;await Yd(a)}}function Wd(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function Yd(e){return new Promise(t=>{setTimeout(t,e)})}async function Iw(e,t){let n={id:J.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:$(),attempts:0},r=JSON.stringify(n);r.length>rr||await dr(Bt(e),r)}function Cw(e){let t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return J.createHash("sha256").update(t).digest("hex").slice(0,32)}function pi(e){let t=[];for(let n of e.split(`
|
|
121
|
-
`)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);o&&typeof o=="object"&&typeof o.endpoint=="string"&&o.endpoint.trim().length>0&&"payload"in o&&typeof o.attempts=="number"&&Number.isFinite(o.attempts)&&((typeof o.id!="string"||o.id.length===0)&&(o.id=Cw(o)),t.push(o))}catch{}}return t}function Aw(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 _i(e,t){let n=qd(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>rr||Aw(i,n)||i.attempts>=Sd){o+=1;continue}r.push(i)}if(r.length>cd){let i=r.length-cd;return o+=i,{entries:r.slice(i),prunedCount:o}}return{entries:r,prunedCount:o}}async function xw(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
|
|
122
|
-
`),r=n.length>0?`${n}
|
|
123
|
-
`:"";for(let o=0;;o+=1)try{await T(Bt(e),r,{createParentDirectories:!se(process.env[ue])});return}catch(i){let s=vd[o];if(s===void 0||!Wd(i))throw i;await Yd(s)}}async function hd(e,t,n,r){return ge(async()=>{let o=await C(Bt(e)),i=o===null?[]:pi(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}=_i(s,t);return await xw(e,a),a.length},e)}async function Rw(e,t){let n=await C(Bt(e));if(n===null||n.trim().length===0){await er(e,{pending_otel_spans:0},null);return}let r=pi(n),{entries:o,prunedCount:i}=_i(r,t),s=o.filter(y=>fi(y.next_attempt_after)).slice(0,Mg);if(s.length===0){let y=i>0?await hd(e,t,new Set,new Map):o.length;await er(e,{pending_otel_spans:y},null);return}let a=$(),c=new Set,d=new Map,l=0,u;await Promise.all(s.map(async y=>{try{let g=await Ld(y.endpoint,{"content-type":"application/json"},JSON.stringify(y.payload));if(g<200||g>=300)throw new Error(`local_otel_export_http_${g}`);c.add(y.id),l+=1}catch(g){u=g instanceof Error?k(Vn(g.message),"redacted"):"local_otel_export_failed";let h=y.attempts+1;d.set(y.id,{attempts:h,next_attempt_after:Vd(h)})}}));let m=await hd(e,t,c,d),_={pending_otel_spans:m,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):m===0&&(_.last_otel_failure_at=void 0,_.last_otel_failure_error=void 0),await er(e,_,null)}async function Gd(e,t,n){try{await Nw(e,t,n)}catch{}try{await Rw(e,n)}catch{}}async function kw(e,t=Vg,n=z().endpoint){try{let r=cw(e),o=await xg(r,{withFileTypes:!0}),i=Date.now(),s=new Set([Ut("events.jsonl",n),Ut("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-Hg: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 wd(l)).mtimeMs<d&&await ii(l,{force:!0})}))}catch{}}async function ge(e,t=me(process.cwd()),n=5e3){let r=md.catch(()=>{}).then(()=>$i(async()=>{let o=await Ee(t,"telemetry-queue",60,"telemetry",!1,!1,n,{createParentDirectories:!se(process.env[ue])});try{return rn(t),await e()}finally{await o()}}));return md=r.catch(()=>{}),r}async function sr(e,t=z().endpoint){let n=await C(qt(e,t));return n===null||n.trim().length===0?[]:Ud(n)}async function ei(e,t,n,r=z().endpoint){return ge(async()=>{let o=await sr(e,r),{entries:i}=ir(o,n),s=i.filter(a=>!t.has(a.event.event_id));return await Bd(e,s,r),s},e)}async function Ow(e,t,n,r,o=z().endpoint){return ge(async()=>{let i=await sr(e,o),{entries:s}=ir(i,r),a=s.map(c=>{if(!t.has(c.event.event_id))return c;let d=c.attempts+1;return{...c,attempts:d,last_attempt_at:n,next_attempt_after:Vd(d)}});return await Bd(e,a,o),a},e)}function Dw(e,t){return t===null?e:Un(e)}async function Nw(e,t,n){let r=z().endpoint;await kw(e,void 0,r);let o=(r??t).trim(),i=Dw(o,r),s=h=>er(e,h,r);if(o.length===0)return;let a=await C(qt(e,r));if(a===null||a.trim().length===0){await s({endpoint:i,queue_entries:0});return}let c=Ud(a);if(c.length===0){await s({endpoint:i,queue_entries:0});return}let{entries:d,prunedCount:l}=ir(c,n);if(d.length===0){let h=await ei(e,new Set,n,r);await s({endpoint:i,queue_entries:h.length});return}let u=d.filter(h=>Hd(h)).slice(0,Lg);if(u.length===0){let h=l>0?await ei(e,new Set,n,r):d;await s({endpoint:i,queue_entries:h.length});return}let m=new Set(u.map(h=>h.event.event_id)),_=$(),y={"content-type":"application/json"},g=process.env.PM_TELEMETRY_INGEST_KEY?.trim();g&&(y["x-pm-telemetry-key"]=g);try{let h=await Ld(o,y,JSON.stringify({schema_version:nr,events:u.map(w=>w.event)}));if(h<200||h>=300)throw new Error(`telemetry_flush_http_${h}`)}catch(h){let w=await Ow(e,m,_,n,r),b=h instanceof Error?k(Vn(h.message),"redacted"):"telemetry_flush_failed";await s({endpoint:i,queue_entries:w.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:b});return}try{let h=await ei(e,m,n,r);await s({endpoint:i,queue_entries:h.length,last_attempted_flush_at:_,last_successful_flush_at:_,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(h){let w=h instanceof Error?k(Vn(h.message),"redacted"):"telemetry_flush_failed",b=await sr(e,r).catch(()=>d);await s({endpoint:i,queue_entries:b.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:w})}}async function Mw(e){let t=ci(e);se(process.env[ue])||await Zo(O.dirname(t),{recursive:!0});try{return await Zo(t),!0}catch(n){if(typeof n!="object"||n===null||!("code"in n)||n.code!=="EEXIST")throw n}try{let n=await wd(t);return Date.now()-n.mtimeMs<Td?!1:(await ii(t,{recursive:!0,force:!0}),await Zo(t),!0)}catch{return!1}}function Lw(e,t){try{return Date.now()-gd(e).mtimeMs<t}catch{return!1}}function Kd(e){try{Ag(e,{recursive:!0,force:!0})}catch{}}function Pw(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function $w(e){try{return Jo(e),!0}catch(t){if(Pw(t)==="EEXIST"||!P(t))return!1}try{return Jo(O.dirname(e),{recursive:!0}),Jo(e),!0}catch{return!1}}function Fw(e){if(Lw(ci(e),Td))return!1;let t=Ad(e);try{if(Date.now()-gd(t).mtimeMs<qg)return!1;Kd(t)}catch(n){if(!P(n))return!1}return $w(t)}function oi(e){Kd(Ad(e))}async function jw(e,t,n){let r=await Mw(e);if(oi(e),!r)return!1;try{await Gd(e,t,n)}finally{try{await ii(ci(e),{recursive:!0,force:!0})}catch{}}return!0}async function yd(e,t){let n=new Set;try{let{entries:r}=ir(await sr(e),t);for(let o of r.filter(Hd))n.add(`event:${o.event.event_id}`)}catch{}try{let r=await C(Bt(e));if(r!==null)for(let o of _i(pi(r),t).entries)fi(o.next_attempt_after)&&n.add(`span:${o.id}`)}catch{}return n}function hi(e,t,n){if(!Ir(e)){if(lw())return Qo=Qo.then(()=>Gd(e,t,n)),Qo;try{if(!Fw(e))return;let r=Cg(process.execPath,[dw()],{detached:!0,stdio:"ignore",cwd:si.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[ue]:"1"}});r.on("error",()=>{oi(e)}),r.unref()}catch{oi(e)}}}async function yC(e=me(process.cwd())){if(!K().telemetry_disabled)try{await Tr(e,async()=>{let t=se(process.env[ue]),n=!0;for(;n;){if(!(await Y(e)).telemetry.enabled)return;let r=await ge(()=>mi(e),e);if(!r)return;let o=t?await yd(e,r.retentionDays):new Set;if(!await jw(e,r.endpoint,r.retentionDays)||!t)return;let i=await yd(e,r.retentionDays);n=i.size>0&&(i.size!==o.size||[...i].some(s=>!o.has(s)))}},()=>se(process.env[ue]))}catch{}}async function zw(e){if(K().telemetry_disabled||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=me(process.cwd());if(!(await Y(t)).telemetry.enabled)return null;let n=e.global.noExtensions===!0||Fi(e.command),r=await ge(async()=>{let o=await mi(t);if(!o)return null;let{installationId:i,endpoint:s,retentionDays:a,captureLevel:c}=o,d=Pd(e.pm_version),l=Fd(e.global),u=F(i,e.pm_root),m=F(i,process.cwd()),_=yw(),y=$(),g={schema_version:nr,event_id:J.randomUUID(),event_type:"command_start",occurred_at:y,installation_id:i,session_id:or,command:e.command,payload:Ew({captureLevel:c,context:e,pmVersion:d,sourceContext:l,pmRootHash:u,cwdHash:m,installationId:i})},h=await ad(t,e.command,n);h===1&&await tr(t,g);let w=De(e.command),b={...h<1?{sample_rate:h}:{},started_at:y,started_at_ms:Date.now(),command:e.command,command_taxonomy:w,pm_version:d,source_context:l.source_context,source_context_source:l.source_context_source,installation_id:i,pm_root_hash:u,cwd_hash:m,endpoint:s,retention_days:a,global_pm_root:t,capture_level:c,otel_traces_endpoint:_??void 0,otel_trace_id:_?J.randomBytes(16).toString("hex"):void 0,otel_span_id:_?J.randomBytes(8).toString("hex"):void 0};return h<1&&Qn.set(b,g),b},t,ai);return r&&r.sample_rate===void 0&&hi(t,r.endpoint,r.retention_days),r}catch{return null}}async function Uw(e,t){if(!(!e||K().telemetry_disabled))try{if(!await ge(async()=>{let n=await Y(e.global_pm_root);if(K().telemetry_disabled||!n.telemetry.enabled||n.telemetry.installation_id!==e.installation_id)return Qn.delete(e),!1;let r=Qn.get(e),o=t.ok?e.sample_rate??1:1;if(r){if(Qn.delete(e),J.randomBytes(6).readUIntBE(0,6)/281474976710656>=o)return!1;r.payload.sample_rate=o,await tr(e.global_pm_root,r)}let i=$(),s=Math.max(0,Date.now()-e.started_at_ms),a=di(zo({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),c=$d({ok:t.ok,errorCode:a,errorCategory:t.error_category}),d=li(t.exit_code,t.ok),l=t.command_resolution??Qe({ok:t.ok,errorCode:a,errorCategory:c}),u=t.resolution_stage??"execute",m={schema_version:nr,event_id:J.randomUUID(),event_type:"command_finish",occurred_at:i,installation_id:e.installation_id,session_id:or,command:e.command,payload:{...r?{sample_rate:o}:{},...Sw({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:s,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:d,errorCode:a,errorCategory:c,commandResolution:l,resolutionStage:u})}};await tr(e.global_pm_root,m);let _=ww(e,{...t,exit_code:d,error_code:a,error_category:c},i,s,o);return _&&await Iw(e.global_pm_root,_),!0},e.global_pm_root,ai))return;await hi(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function Vw(e){if(!K().telemetry_disabled)try{let t=me(process.cwd());if(!(await Y(t)).telemetry.enabled)return;let n=await ge(async()=>{let r=await mi(t);if(!r)return null;let{installationId:o,captureLevel:i}=r,s=Pd(e.pm_version),a=Fd(e.global),c=F(o,e.pm_root),d=F(o,process.cwd()),l=$(),u=di(zo({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),m=e.error_category??Yt(u),_=li(e.exit_code,!1),y=e.command.trim().length>0?e.command:"<unknown>",g=De(y),h=e.command_resolution??Qe({ok:!1,errorCode:u,errorCategory:m}),w=e.resolution_stage??"unknown",b={schema_version:nr,event_id:J.randomUUID(),event_type:"command_error",occurred_at:l,installation_id:o,session_id:or,command:k(y,"redacted"),payload:vw({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:m,exitCode:_,errorMessage:e.error_message})};return await tr(t,b),r},t,ai);n&&await hi(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]="6b1f17f6-0bde-5194-9b7d-ac71988e5886")}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 qR(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function BR(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}export{tl as a,xr as b,Xi as c,nl as d,Yw as e,Gi as f,an as g,es as h,ts as i,rl as j,ol as k,il as l,sl as m,Zw as n,Dr as o,fl as p,Qw as q,pl as r,eb as s,Et as t,hl as u,St as v,tb as w,yl as x,cn as y,nb as z,Ue as A,wl as B,bl as C,cb as D,Mr as E,db as F,lb as G,vt as H,ub as I,cs as J,kl as K,Cb as L,Dl as M,Ml as N,Pl as O,$l as P,Ob as Q,jl as R,dn as S,Tt as T,ql as U,Gl as V,$b as W,eu as X,jb as Y,tu as Z,nu as _,zb as $,Pr as aa,ws as ba,au as ca,$r as da,cu as ea,un as fa,Es as ga,hu as ha,vs as ia,Ve as ja,le as ka,Eu as la,gE as ma,vu as na,Is as oa,Tu as pa,Iu as qa,Au as ra,xu as sa,Ru as ta,RE as ua,Du as va,LE as wa,Pu as xa,Fu as ya,ju as za,zu as Aa,Uu as Ba,zr as Ca,qu as Da,qE as Ea,BE as Fa,WE as Ga,YE as Ha,GE as Ia,KE as Ja,XE as Ka,Gu as La,Ku as Ma,Xu as Na,Ju as Oa,Zu as Pa,Qu as Qa,He as Ra,Hs as Sa,xm as Ta,yS as Ua,It as Va,$m as Wa,Xs as Xa,qr as Ya,Js as Za,CS as _a,jm as $a,Um as ab,Vm as bb,Hm as cb,qm as db,Br as eb,HS as fb,QS as gb,e0 as hb,t0 as ib,n0 as jb,r0 as kb,o0 as lb,i0 as mb,s0 as nb,Jm as ob,Zm as pb,Qm as qb,a0 as rb,sf as sb,c0 as tb,d0 as ub,Qr as vb,to as wb,Y0 as xb,y0 as yb,g0 as zb,w0 as Ab,_a as Bb,bf as Cb,lo as Db,D0 as Eb,uo as Fb,Mt as Gb,Ye as Hb,Lt as Ib,ip as Jb,Aa as Kb,sp as Lb,Cv as Mb,po as Nb,xa as Ob,pp as Pb,Av as Qb,_p as Rb,hp as Sb,Nv as Tb,Rn as Ub,La as Vb,yo as Wb,Rp as Xb,kp as Yb,Pv as Zb,Pa as _b,Ge as $b,go as ac,bo as bc,Mn as cc,Gv as dc,xo as ec,Pn as fc,Ha as gc,$n as hc,Ro as ic,ko as jc,Oo as kc,Do as lc,Ka as mc,Xa as nc,Ba as oc,C_ as pc,Fn as qc,Je as rc,Ut as sc,R_ as tc,Un as uc,hT as vc,K as wc,ke as xc,L_ as yc,sc as zc,ac as Ac,cc as Bc,F_ as Cc,vT as Dc,V_ as Ec,TT as Fc,IT as Gc,Vt as Hc,xc as Ic,xh as Jc,Ht as Kc,FT as Lc,jT as Mc,Rh as Nc,kh as Oc,zT as Pc,UT as Qc,Qe as Rc,Uh as Sc,Vh as Tc,Hh as Uc,qh as Vc,Gh as Wc,Kh as Xc,Jh as Yc,ky as Zc,qc as _c,Dy as $c,Ny as ad,My as bd,rI as cd,Bo as dd,Wc as ed,Bc as fd,$y as gd,Fy as hd,Yc as id,Uy as jd,By as kd,Yy as ld,Ky as md,Xy as nd,eg as od,ng as pd,rg as qd,Zn as rd,mg as sd,fg as td,vg as ud,nr as vd,Sd as wd,ge as xd,yC as yd,zw as zd,Uw as Ad,Vw as Bd,qR as Cd,BR as Dd};
|
|
124
|
-
//# sourceMappingURL=chunk-NAX554KY.js.map
|