@unbrained/pm-cli 2026.11.8 → 2026.11.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +15 -0
  3. package/dist/cli/main.js +1 -1
  4. package/dist/cli/runtime/projection-retry.js +1 -1
  5. package/dist/cli/runtime/read-output-mutation-retry.js +2 -0
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/{chunk-NH7QX2M2.js → chunk-3BMIAI4P.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-RC6SSFOF.js → chunk-5VRJPPUC.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-XBUZENP4.js → chunk-6V4PGJBZ.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-YUTFMHSG.js → chunk-ASJZMYKM.js} +33 -33
  11. package/dist/cli-bundle/chunks/chunk-BLUCQ4T4.js +2 -0
  12. package/dist/cli-bundle/chunks/{chunk-4BMPGUTG.js → chunk-ELNWRSGZ.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-7GC6WIDR.js → chunk-EZRLW4R6.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-NKO42JMT.js → chunk-G6Q4VQSI.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-3A5DJZCC.js → chunk-GCPP37N6.js} +48 -48
  16. package/dist/cli-bundle/chunks/{chunk-C4MQFWCM.js → chunk-GDQ2T2OR.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-L5BU5FYN.js → chunk-GZVOOHTO.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-LI2HP5OX.js → chunk-IGT252ES.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-CP43BHX3.js → chunk-JK7O7MFO.js} +29 -29
  20. package/dist/cli-bundle/chunks/{chunk-AFZS6WFV.js → chunk-JYQXIC6C.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-PE6CZ3PE.js → chunk-LVDFPGD7.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-Z3LWNF7C.js → chunk-MSJ7IHMJ.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-MKW5LGVQ.js → chunk-O2M3TNFY.js} +6 -6
  24. package/dist/cli-bundle/chunks/chunk-UFIM5ZC5.js +6 -0
  25. package/dist/cli-bundle/chunks/{chunk-YGUUJHSR.js → chunk-VATZTJE3.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-DOHZKPPC.js → chunk-XKY4LUXN.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-7V6I6X4G.js → chunk-YK5GAWOT.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-S4IZIMAO.js → chunk-YV5ALMG2.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-HESIRIVX.js → chunk-Z3QEEOAM.js} +2 -2
  30. package/dist/cli-bundle/chunks/item-revision-Y5CE3EIN.js +2 -0
  31. package/dist/cli-bundle/chunks/item-transaction-XBIN4KYM.js +2 -0
  32. package/dist/cli-bundle/chunks/{mutation-admission-FJ3D66PV.js → mutation-admission-TAQN2AKK.js} +2 -2
  33. package/dist/cli-bundle/chunks/{register-list-query-GXP77CX7.js → register-list-query-XMQYFUFI.js} +2 -2
  34. package/dist/cli-bundle/chunks/{register-mutation-XJ2DROUM.js → register-mutation-OBVCFLDK.js} +2 -2
  35. package/dist/cli-bundle/chunks/{register-operations-O5LERXM7.js → register-operations-CGNFZ6DR.js} +2 -2
  36. package/dist/cli-bundle/chunks/{register-setup-4VOTYLL2.js → register-setup-LFB5ERXH.js} +2 -2
  37. package/dist/cli-bundle/chunks/{stage-ZDJL3FGL.js → stage-NQHF6JPC.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-Z2QWZRSL.js → chunk-2SQUWQP3.js} +18 -18
  39. package/dist/cli-bundle/focused-chunks/chunk-4FWMXQN3.js +12 -0
  40. package/dist/cli-bundle/focused-chunks/{chunk-4UOXVFJZ.js → chunk-AH5IST3V.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-6U5HP6L3.js → chunk-ALLOWZSH.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-KNF2QTEZ.js → chunk-C3DO4ZGZ.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-LTPT5TE7.js → chunk-CUGJ2DY2.js} +20 -20
  44. package/dist/cli-bundle/focused-chunks/{chunk-2A3QZELL.js → chunk-HLQOGAWG.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-P4EHEH4C.js → chunk-HNFY3XLC.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/chunk-IB6TCE7N.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-5YPX3QKU.js → chunk-IS5FLEZW.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-ULTSMJYF.js → chunk-J7PWHKZK.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-P6TG33FV.js → chunk-JU62TKJP.js} +26 -26
  50. package/dist/cli-bundle/focused-chunks/{chunk-TSHRBPTI.js → chunk-LDMBNTOG.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-UUVRYIKA.js → chunk-LWMPQRJT.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-MYBKRV5R.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-KBRSA4OK.js → chunk-NUFO3OR6.js} +25 -25
  54. package/dist/cli-bundle/focused-chunks/{chunk-DIEBSC76.js → chunk-NZQYHPUN.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-3HFENALW.js → chunk-Q45LDP7P.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-O7K3X4LH.js → chunk-QWUWNFQO.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-SZ2BKK3M.js → chunk-RNZUORGI.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-WPXMPGTY.js → chunk-UIKLNSW3.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-I4YUZW3J.js → chunk-XLSTFUXM.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/item-revision-M6FOLME2.js +2 -0
  61. package/dist/cli-bundle/focused-chunks/{item-transaction-Q2Z7DDCR.js → item-transaction-H6VA5JGB.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{mutation-admission-QWC6MLTZ.js → mutation-admission-PRTQWQK6.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{stage-NKH5SKSZ.js → stage-7T77PSJD.js} +2 -2
  64. package/dist/cli-bundle/main.js +26 -26
  65. package/dist/cli-bundle/sdk-authoring.js +1 -1
  66. package/dist/cli-bundle/sdk-contracts.js +4 -4
  67. package/dist/cli-bundle/sdk-core.js +1 -1
  68. package/dist/cli-bundle/sdk-governance.js +1 -1
  69. package/dist/cli-bundle/sdk-graph.js +1 -1
  70. package/dist/cli-bundle/sdk-merge.js +57 -57
  71. package/dist/cli-bundle/sdk-query.js +1 -1
  72. package/dist/cli-bundle/sdk-runtime.js +1 -1
  73. package/dist/cli-bundle/sdk-testing.js +1 -1
  74. package/dist/cli-bundle/sdk.js +9 -9
  75. package/dist/core/item/item-format.d.ts +9 -1
  76. package/dist/core/item/item-format.js +1 -1
  77. package/dist/core/output/output.d.ts +9 -2
  78. package/dist/core/output/output.js +4 -4
  79. package/dist/core/search/corpus.js +1 -1
  80. package/dist/mcp/tool-definitions.js +1 -1
  81. package/dist/sdk/annotations.js +1 -1
  82. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  83. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  84. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  85. package/dist/sdk/lifecycle/item-revision.d.ts +6 -0
  86. package/dist/sdk/lifecycle/item-revision.js +1 -1
  87. package/dist/sdk/public-surface.json +1 -1
  88. package/dist/sdk/query/get-facet-roots.js +2 -0
  89. package/dist/sdk/query/get.js +1 -1
  90. package/dist/sdk/read-output/positional-rows.js +2 -0
  91. package/dist/sdk/read-output-contracts.d.ts +4 -0
  92. package/dist/sdk/read-output-contracts.js +1 -1
  93. package/dist/sdk/runtime/actions.js +1 -1
  94. package/docs/AGENT_OUTPUT_ENCODINGS.md +16 -0
  95. package/docs/README.md +1 -1
  96. package/docs/READ_OUTPUT_CONTRACTS.md +21 -0
  97. package/docs/RELEASING.md +27 -5
  98. package/marketplace.json +1 -1
  99. package/package.json +2 -1
  100. package/packages/pm-beads/package.json +1 -1
  101. package/packages/pm-calendar/package.json +1 -1
  102. package/packages/pm-command-kit/package.json +1 -1
  103. package/packages/pm-digital-twin/package.json +1 -1
  104. package/packages/pm-governance-audit/package.json +1 -1
  105. package/packages/pm-guide-shell/package.json +1 -1
  106. package/packages/pm-kanban/package.json +1 -1
  107. package/packages/pm-lifecycle-hooks/package.json +1 -1
  108. package/packages/pm-linked-test-adapters/package.json +1 -1
  109. package/packages/pm-search-advanced/package.json +1 -1
  110. package/packages/pm-templates/package.json +1 -1
  111. package/packages/pm-todos/package.json +1 -1
  112. package/packages/pm-vcs/package.json +1 -1
  113. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  114. package/plugins/pm-claude/package.json +1 -1
  115. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  116. package/plugins/pm-codex/package.json +1 -1
  117. package/plugins/pm-codex/plugin.json +1 -1
  118. package/runtime-dependencies.json +1 -1
  119. package/dist/cli-bundle/chunks/chunk-JAE5MWLX.js +0 -2
  120. package/dist/cli-bundle/chunks/chunk-LLTRUVKK.js +0 -6
  121. package/dist/cli-bundle/chunks/item-revision-TUGZYYXX.js +0 -2
  122. package/dist/cli-bundle/chunks/item-transaction-2RRBAQN3.js +0 -2
  123. package/dist/cli-bundle/focused-chunks/chunk-PL6EO4GJ.js +0 -2
  124. package/dist/cli-bundle/focused-chunks/chunk-PSLDGAEY.js +0 -12
  125. package/dist/cli-bundle/focused-chunks/chunk-UNNLBJRI.js +0 -2
  126. package/dist/cli-bundle/focused-chunks/item-revision-XNSRDTFB.js +0 -2
  127. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +0 -274
@@ -1,15 +1,15 @@
1
- import{a as Fa}from"./chunks/chunk-RC6SSFOF.js";import"./chunks/chunk-DEZPZOQ7.js";import{A as Nn,C as ir,D as ar,F as rr,G as Fn,a as On,d as P,e as F,f as T,g as L,h as k,i as Ta,n as Be,o as Oa,p as La,t as ja,u as Za,v as Qa,w as er,x as tr,y as nr,z as or}from"./chunks/chunk-7GC6WIDR.js";import{Ua as Xa,f as Ea,k as Sa}from"./chunks/chunk-MKW5LGVQ.js";import"./chunks/chunk-AFZS6WFV.js";import"./chunks/chunk-LLTRUVKK.js";import{A as Rt,D as za,E as Wa,F as Z,Fc as Ka,G as Ba,Hd as Ya,aa as Va,i as Da,n as $n,o as Dn,p as Ua,q as qa,r as Ha,s as Mn,t as St,u as Je,w as Ga,y as At}from"./chunks/chunk-CP43BHX3.js";import"./chunks/chunk-UJMQP2HP.js";import"./chunks/chunk-YGUUJHSR.js";import{ha as Ja,j as Aa}from"./chunks/chunk-HESIRIVX.js";import"./chunks/chunk-7V6I6X4G.js";import"./chunks/chunk-DOHZKPPC.js";import"./chunks/chunk-XBUZENP4.js";import{C as xt,Cc as G,D as me,Qc as Na,jb as Ra,kb as V,mb as Ia,n as bt,nb as Pa,p as We,pb as $a,q as Ct,sc as kt,tc as Et,uc as In,vc as Ve,wc as E,xc as Ma,yc as Pn}from"./chunks/chunk-4BMPGUTG.js";import{A as xa,B as Tn,C as ka,n as An,p as ba,u as Rn,w as Ca}from"./chunks/chunk-JAE5MWLX.js";import"./chunks/chunk-NKO42JMT.js";import"./chunks/chunk-IB7UB5TE.js";import{$c as ha,Ac as ra,Ad as wa,Cc as sa,Gb as vt,Gc as la,Hb as oa,Hc as ca,Ic as vn,J as bi,Kc as da,Lc as de,Mc as wn,Nc as bn,Oc as Cn,Pc as xn,Qc as wt,Rc as kn,Sc as ma,Tc as pa,Uc as ua,Vc as En,Wc as fa,Xc as Se,_c as ga,gb as Qi,hb as ea,ib as ta,jb as na,kd as ze,nd as ya,qc as _n,td as _a,wc as ia,yd as Sn,zc as aa,zd as va}from"./chunks/chunk-YUTFMHSG.js";import{$c as Ri,Ca as on,Eh as X,Fa as se,Fd as cn,G as Le,Gd as ht,Ha as _i,Hd as Ni,Ia as pt,Ic as Ei,Id as Fi,Ii as _t,Kc as Si,La as an,Lg as Hi,Lh as Ki,Li as Yi,Ma as vi,Mg as Gi,Mh as oe,Mi as Xi,Na as O,Ng as zi,Ob as ut,Og as Wi,Oh as yn,Pa as wi,Pg as Bi,Ph as b,Pi as Ee,Qa as Y,Qi as N,Rb as sn,Ri as Zi,Xc as Ai,Yc as He,Zd as dn,_c as Ge,ba as yi,cc as Ci,dc as xi,gb as _,ib as xe,id as Ti,jb as je,jd as Oi,jf as Li,kd as Ii,kf as ji,ld as Pi,mb as Ue,md as ne,nd as $i,ng as mn,nh as Vi,od as ln,og as pn,pd as le,pg as Ui,qd as Di,qg as qi,r as M,rb as qe,rd as ft,rh as Ji,sf as yt,sg as un,t as W,tg as fn,u as q,ud as ke,ug as gn,vc as ki,vd as ce,w as J,wg as hn,x as nn,xb as rn,y as B,yd as Mi,z as hi,zd as gt}from"./chunks/chunk-3A5DJZCC.js";import"./chunks/chunk-SPPHDVZE.js";import"./chunks/chunk-RSAN2YUU.js";import"./chunks/chunk-VS565KBX.js";import{A as g,B as mt,C as R,E as K}from"./chunks/chunk-O4ZLEN4T.js";import"./chunks/chunk-XAWE4EAK.js";import{AsyncLocalStorage as xl}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e47421c-706d-5e31-a466-6152cdeba30f")}catch{}})();var Ae=new xl;function sr(e){let t=Ae.getStore();return t===void 0?e:t!==null}function pe(e,t=`warning:${e}`){let n=Ae.getStore();n?(!n.has(e)||t!==`warning:${e}`)&&n.set(e,t):b(t)}function Ke(e){let t=Ae.getStore();if(!t?.size)return e;let n=Reflect.get(e,"warnings"),o=[...t].filter(([r,s])=>s!==`warning:${r}`).map(([r,s])=>({code:r,message:s})),i=Reflect.get(e,"warning_details"),a={...e,warnings:[...Array.isArray(n)?n:[],...t.keys()],...o.length>0?{warning_details:[...Array.isArray(i)?i:[],...o]}:{}};return t.clear(),a}function Ln(e){if(!Ae.getStore()?.size)return e;let{token_accounting:t,...n}=Ke(JSON.parse(e));return JSON.stringify(t===void 0?n:X(n,o=>`${JSON.stringify(o,null,2)}
2
- `),null,2)}async function lr(e,t){if(!e){await Ae.run(null,t);return}let n=new Map;await Ae.run(n,async()=>{await t(),n.size>0&&oe(`${JSON.stringify(Ke({type:"warning"}))}
3
- `)})}import{AsyncLocalStorage as kl}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad9cd4bc-07aa-5641-a1c4-b2aea5d4700c")}catch{}})();var jn=new kl,cr=new WeakMap;function El(e){let t=e.outputFormat!==void 0?["--output-format",e.outputFormat]:e.json===!0?["--json"]:[];return{scopeArgs:xe(e),outputArgs:t}}var dr=new WeakMap;function Sl(e,t){let n=e.registeredArguments.findIndex(o=>o.name()==="id");if(!(n===-1||e.name()==="plan"&&t[0]==="create"))return t[n]}function Un(e,t){return t.some(n=>n.path!==e.path||n.args.length!==e.args.length||n.args.some((o,i)=>o!==e.args[i]))}async function qn(e){if(e.expectHash===void 0)return;let t=An(e.expectHash),n=e.commandPath.trim().toLowerCase();if(Tn(n,e.commandOptions),e.rewritten===!0)throw Rn();let o=jn.getStore();if(o===void 0)throw new TypeError("--expect-hash was parsed outside an invocation revision scope");let i=await ba(e.pmRoot,t,Sl(e.command,e.commandArgs));ta(o,e.pmRoot,i),dr.set(o,n),e.globalOptions!==void 0&&cr.set(o,El(e.globalOptions))}function Hn(e,t,n){let o=jn.getStore(),i=o===void 0?void 0:dr.get(o);if(i!==void 0){if(Un(e,[t]))throw Rn();Tn(i,n)}}function mr(e,t){if(t!==void 0)throw An(t),ka(e)}function Al(e){for(let t of na(e).unchecked)pe(xa(t))}async function Rl(e,t){return e.pmRoot===void 0?t:Ca(t,e.pmRoot,cr.get(e))}async function pr(e){let t=Qi();try{await e(n=>jn.run(t,()=>ea(t,n)))}catch(n){throw await Rl(t,n)}Al(t)}import{Command as ai,CommanderError as zs}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="50318c14-8c1c-50f3-95d0-fd9ea3f0bb69")}catch{}})();function z(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function ue(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return z(t)}function Q(e){let t=new Set,n=[];for(let o of e){let i=ue(o);i&&(t.has(i)||n.push(i),t.add(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]="0b95b409-ef2c-59da-a628-16a2cb4f0ea6")}catch{}})();var Gn=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),Tt=new Set(["--full","--brief","--compact"]);function Tl(e,t){return!!(e.flag==="--pm-path"||e.value_name||e.list||e.value_type==="number"||e.value_type==="string"||t.has(e.flag))}function Ol(e){let t=V(k([...e])),n=new Set([...Ia,...Pa,...$a].flatMap(r=>r.keys.map(s=>`--${s.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`)}`))),o=new Map([...me,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,r.flag]))),i=new Map([...me,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,Tl(r,n)])));for(let r of Gn)i.set(r,!0);for(let r of Tt)i.set(r,!1);let a=new Map;for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="--")break;if(!s.startsWith("-"))continue;let c=s.split("=")[0];if(!i.has(c)&&!s.includes("="))return;a.set(r,o.get(c)??c),i.get(c)&&!s.includes("=")&&(r+=1)}return a}function ur(e,t,n){let o=new Set;for(let[i,a]of t)n.has(a)&&(o.add(i),Gn.has(a)&&!e[i].includes("=")&&o.add(i+1));return e.filter((i,a)=>!o.has(a))}function Il(e,t){let n=t.find(i=>Tt.has(i));if(n===void 0)return;let o=[...new Set(e.values())].filter(i=>Tt.has(i));return o.length===1?o[0]:n}function fr(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,i={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return i;let a=Ol(e);if(!a)return i;let r;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return i;let c=[...a].find(([l,d])=>d==="--fields")?.[0]??-1;if(c<0)return i;r=ur(e,a,new Set(["--fields"])),r.splice(c,0,"--fields",o[s+1])}else{let s=Il(a,o);if(s===void 0||![...a.values()].includes(s))return i;let c=new Set([...Gn,...Tt].filter(l=>l!==s));r=ur(e,a,c)}return{...n,suggested_retry:_(r),suggested_retry_args: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]="c470fd86-4218-5aed-a681-58557d759b28")}catch{}})();var Pl="project_schema_field_requires_declared_flag";function $l(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o.startsWith("--field=")?t.push({index:n,width:1,assignment:o.slice(8)}):o==="--field"&&n+1<e.length&&(t.push({index:n,width:2,assignment:e[n+1]}),n+=1)}return t}function gr(e,t,n,o){let i=o?.suggested_flags?.[0];if(t!==Pl||n===void 0||i===void 0)return o;let a=$l(e).filter(({assignment:d})=>d.split("=",1)[0].trim()===n&&d.includes("="));if(a.length!==1)return o;let[r]=a,s=r.assignment.trim(),c=s.slice(s.indexOf("=")+1),l=[...e.slice(0,r.index),i,c,...e.slice(r.index+r.width)];return{...o,suggested_retry:_(l),suggested_retry_args: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]="f8935dde-8de2-508e-b910-2a603a763c48")}catch{}})();var zn=Da;function Dl(e,t,n,o,i){let a=[],r=e.indexOf(n,t);if(r<0||e.slice(t,r).some(s=>s.startsWith("-")))return a;for(let s=r+1;s<e.length;s+=1){let c=e[s];if(c==="--")break;c===`${o}=${i}`?a.push({index:s,width:1}):c===o&&e[s+1]===i&&(a.push({index:s,width:2}),s+=1)}return a}function hr(e,t,n,o,i=[]){let a=o?.suggested_flags?.[0];if(t!==zn||n===void 0||a===void 0||o.suggested_retry_args===void 0)return o;let r={...o,suggested_retry:void 0,suggested_retry_args:void 0},s=L([...e]);if(s===void 0||i===null)return r;let c=o.suggested_retry_args,l=Dl(e,s,c[0],n,a);if(l.length!==1)return r;let{index:d,width:m}=l[0],p=[...e.slice(0,d),a,...e.slice(d+m)];if(!Ml(p,d,n,a,c))return r;let u=[...i,...p];return{...o,suggested_retry:_(u),suggested_retry_args:u}}function Ml(e,t,n,o,i){let a=i.lastIndexOf(o);return a<0||i.slice(a).some((r,s)=>e[t+s]!==r)?!1:!e.some((r,s)=>s!==t&&(r===n||r.startsWith(`${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]="bed9cdab-5e06-5035-8d76-d9943a8e7e5f")}catch{}})();var Wn="close_validation_missing_fields";function Nl(e,t,n,o){let i=e.slice(t+1);if(!i.includes("--"))return[...e,...o];if(!i.some(a=>n.has(a.split("=",1)[0])))return[...e.slice(0,t+1),...o,...i]}function Fl(e,t){let n=e.slice(0,e.length-2*t),o=n.length;for(;o>0&&n[o-1].startsWith("--expect-hash=");)o-=1;return n.slice(o)}function yr(e,t,n,o=[]){let i=n?.missing;if(t!==Wn||i===void 0||i.length===0)return n;let a=n.suggested_retry_args;if(a===void 0)return n;let r={...n,suggested_retry:void 0,suggested_retry_args:void 0},s=L([...e]);if(s===void 0||o===null)return r;let c=V(e[s].trim().toLowerCase()),l=i.map(f=>c.find(h=>h.flag===f||h.aliases?.includes(f)===!0));if(l.some(f=>f===void 0))return r;let d=new Set(l.flatMap(f=>[f.flag,...f.aliases??[]])),m=Fl(a,i.length),p=Nl(e,s,d,[...i.flatMap(f=>[f,"<value>"]),...m]);if(p===void 0)return r;let u=[...o,...p];return{...n,suggested_retry:_(u),suggested_retry_args:u}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afa4a7a0-d9de-529d-92dd-3e9704ea00d2")}catch{}})();async function _r(e,t){await va(e,{ok:t.ok,error:t.error,result:ce(),exit_code:t.exit_code,error_code:t.error_code,error_category:t.error_category,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage})}async function vr(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await Vi({pmRoot:e.pmRoot,result:ce()})}catch(o){t=o}let n=await N(e.pmRoot);if(await Ji({pmRoot:e.pmRoot,author:yt(e.author,n.author_default),itemIds:e.itemIds,intent:e.intent}),t!==void 0)throw 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]="dacf3952-3ae1-57fa-840a-c8a43cf855a5")}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]="9490326e-507d-5b3e-9958-08c12afbc5ff")}catch{}})();var wr=new WeakMap;function Ot(e,t){wr.set(e,t)}function fe(e){return wr.get(e)}function br(e){return e.length>0?[e[0]]:[]}function Ll(e){let t=["","Intent:",` ${e.why}`],n=br(e.examples);return n.length>0&&(t.push("","Example:"),t.push(` ${n[0]}`)),t.push("","Need deeper rationale and more examples?"),t.push(" Re-run with --explain."),t.join(`
4
- `)}function jl(e){let t=["","Why use this command:",` ${e.why}`,"","Examples:",...e.examples.map(n=>` ${n}`)];return e.tips&&e.tips.length>0&&(t.push("","Tips:"),t.push(...e.tips.map(n=>` - ${n}`))),t.join(`
5
- `)}function Cr(e,t){return t==="detailed"?jl(e):Ll(e)}function j(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var Ul={cal:"calendar",ctx:"context"};function ql(e,t){return e.commands.find(n=>n.name()===t)??null}function Hl(e,t){let n=e;for(let o of t){let i=ql(n,o);if(!i)return null;n=i}return n}function Bn(e,t,n,o){let i=Hl(e,t.split(" ").filter(a=>a.length>0));i&&i.addHelpText("after",Cr(n,o))}function Vn(e){return e.includes("--explain")?"detailed":"compact"}function ie(e){return e.includes("--all")||e.includes("--explain")}var ge={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm package install ./my-package --project","pm package install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm package install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm package upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm package install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm package install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm package install ./my-extension --project","pm package --install --project ./my-extension","pm package doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list --all --limit 50","pm list --all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status in_progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list --blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm package install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspect recorded mutations.",examples:["pm history pm-a1b2 --order oldest_first","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:["pm claim pm-a1b2 --start",'pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of M){let n=ge[e];n&&(ge[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var Re={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},xr=J.filter(e=>e.lifecycle==="deprecated");for(let e of xr){let t=ge[e.alias];ge[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[Re,...Object.values(ge)])e.examples=e.examples.map(t=>{for(let n of xr){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Gl(e){let t=j(e??"");return t?Ul[t]??t:""}function Jn(e){let t=Gl(e);return t?ge[t]??Re:Re}function kr(e,t){let n=Jn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:br(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function zl(){let e=J.filter(({lifecycle:n})=>n==="permanent"),t=J.filter(({lifecycle:n})=>n==="deprecated");return["","Command aliases:",...e.map(({alias:n,canonical_argv:o})=>` ${n} -> pm ${o.join(" ")}`),"","Deprecated aliases:",...t.map(n=>` ${n.alias} -> pm ${n.canonical_argv.join(" ")} (${hi(n)})`)].join(`
6
- `)}function Wl(e,t,n,o){let i=new Set(za);e.configureHelp({visibleCommands(r){let s=t.visibleCommands(r);return n?s.filter(c=>(fe(c)??Z(c.name()))!=="internal"):r!==e?s:s.filter(c=>o.has(c))},visibleOptions(r){let s=t.visibleOptions(r);return r!==e||n?s:s.filter(c=>i.has(c.flags))}});let a=e.options.filter(r=>r.long==="--output-cursor");for(let r of e.commands.flatMap(s=>[s,...s.commands]))["list","search","context"].includes(r.name())&&r.configureHelp({visibleOptions:s=>[...t.visibleOptions(s),...a]})}function Bl(e,t,n,o){let i=new Set(Ba("core")),a=e.createHelp();a.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let r=()=>`${a.formatHelp(e,a)}${o}
7
- `,s=t.visibleCommands(e);for(let c of s)fe(c)===void 0&&(c.name()==="help"||i.has(c.name()))&&n.add(c);for(let c of s)fe(c)==="core"&&(n.add(c),Wa(r()).within_budget||n.delete(c))}function Er(e,t=process.argv.slice(2)){let n=e.createHelp(),o=ie(t),i=new Set;Wl(e,n,o,i);let a=Vn(t),r=Cr(Re,a);e.addHelpText("after",r),o&&e.addHelpText("after",zl()),Bl(e,n,i,r);for(let[d,m]of Object.entries(ge))Bn(e,d,m,a);let s=j(T(t).commandPathTokens.join(" ")),c=We(s);if(c){Bn(e,c.parent,{why:c.description,examples:[c.example],tips:[`Action path: pm ${c.command}`,Ct(c.accepted_flags)]},a);return}let l=bt.filter(({parent:d})=>d===s);l.length>0&&Bn(e,s,{why:`Dispatches one declared positional action: ${l.map(({action:d})=>d).join("|")}.`,examples:l.map(({example:d})=>d),tips:[`Inspect one action directly with pm ${s} <action> --help --json.`]},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]="2efeb172-b440-5df6-ad48-4c54087835e0")}catch{}})();function Kn(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:i}of M){if(t&&!M.some(l=>l.canonical.startsWith(`${o} `)))continue;let a=e.commands.findIndex(l=>l.name()===n);if(a<0)continue;let r=e.commands[a],s=e;for(let l of i.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===l)??s.command(l).description(`Discover ${l} operations.`);let c=i[i.length-1];if(s.commands.some(l=>l.name()===c))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(a,1),r.name(c),Ot(r,Z(o)),s.enablePositionalOptions(),s.addCommand(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]="cfefc733-0def-51b4-9aa3-33d7d8e6fca5")}catch{}})();function Pt(e){let{title:t,...n}=e;fn(n.why)&&delete n.why,un(n.required)&&delete n.required;let o=gn(n.examples);o.length>0?n.examples=o:delete n.examples;let i=hn(n.recovery);return i===void 0?delete n.recovery:n.recovery=i,n}var Vl=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Jl(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Vl.has(e.code)}function $r(e){return`urn:pm-cli:error:${e}`}function C(e){return{...e,type:$r(e.code)}}var Te={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Sr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Ar={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},It={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Kl={guide:Te,shell:Te,completion:Te,"completion-statuses":Te,"completion-tags":Te,"completion-types":Te,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Sr,cal:Sr,reindex:Ar,"search-advanced":Ar,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":It,"dedupe-audit":It,"dedupe-merge":It,normalize:It};function Yl(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Kl[t]}function Qn(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Xl(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function Zl(e){if(!Array.isArray(e))return;let t=e.map(n=>({source:typeof n?.source=="string"?n.source.trim():"",command:typeof n?.command=="string"?n.command.trim():"",reason:typeof n?.reason=="string"?n.reason.trim():""})).filter(n=>n.source.length>0&&n.command.length>0&&n.reason.length>0);return t.length>0?t:void 0}function Yn(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function Dr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")?[...e]:void 0}function ee(e,t,n){if(t==="normalized_args"||t==="suggested_retry_args"){let i=Dr(n);i&&(e[t]=i);return}if(t==="parsed_positionals"){if(!Array.isArray(n))return;let i=n.map(a=>({role:typeof a?.role=="string"?a.role.trim():"",value:typeof a?.value=="string"?a.value.trim():""})).filter(a=>a.role.length>0&&a.value.length>0);i.length>0&&(e.parsed_positionals=i);return}let o=Xl(n);o&&(e[t]=o)}function Ql(e,t){if(!sa(t))return;let{requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:a,basis:r,reason:s}=t;e.token_budget={requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:a,basis:r,reason:s}}var Mr=["retry_after_ms","waited_ms","owner_handoffs"];function ec(e,t){for(let n of Mr)typeof t[n]=="number"&&e.push(` ${n}: ${t[n]}`)}function tc(e,t){for(let n of Mr){let o=t[n];typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&(e[n]=o)}}function _e(e){if(!e||typeof e!="object")return;let t={};Ql(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Yn(t,"attempted_command",e.attempted_command),ee(t,"normalized_args",e.normalized_args),ee(t,"parsed_positionals",e.parsed_positionals),ee(t,"provided_fields",e.provided_fields),ee(t,"missing",e.missing),ee(t,"missing_required_fields",e.missing_required_fields),ee(t,"suggested_flags",e.suggested_flags),ee(t,"allowed_values",e.allowed_values),ee(t,"candidate_commands",e.candidate_commands),typeof e.candidate_commands_total=="number"&&Number.isSafeInteger(e.candidate_commands_total)&&e.candidate_commands_total>=0&&(t.candidate_commands_total=e.candidate_commands_total),e.candidate_commands_truncated===!0&&(t.candidate_commands_truncated=!0),(e.option_scope==="declared_on_path"||e.option_scope==="declared_elsewhere"||e.option_scope==="declared_nowhere")&&(t.option_scope=e.option_scope),Yn(t,"suggested_retry",e.suggested_retry),ee(t,"suggested_retry_args",e.suggested_retry_args),tc(t,e);let n=Zl(e.fallback_candidates);return n&&(t.fallback_candidates=n),Yn(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Xn(e,t,n){n&&e.push(` ${t}: ${n}`)}function he(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function nc(e){let t=_e(e);if(!t)return[];let n=["Recovery bundle:"];if(t.token_budget){let o=t.token_budget;n.push(` requested_token_budget: ${o.requested_tokens}`,` feasible_token_budget: ${o.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${o.minimum_feasible_tokens??"not established"}`)}if(Xn(n,"suggested_retry",t.suggested_retry),Xn(n,"attempted_command",t.attempted_command),he(n,"normalized_args",t.attempted_command?void 0:t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(he(n,"provided_fields",t.provided_fields,", "),he(n,"missing",t.missing,", "),he(n,"missing_required_fields",t.missing_required_fields,", "),he(n,"suggested_flags",t.suggested_flags,", "),he(n,"allowed_values",t.allowed_values,", "),he(n,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&n.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&n.push(" candidate_commands_truncated: true"),t.option_scope!==void 0&&n.push(` option_scope: ${t.option_scope}`),ec(n,t),Xn(n,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){n.push(" fallback_candidates:");for(let o of t.fallback_candidates)n.push(` - ${o.source}: ${o.command} (${o.reason})`)}return n}var Rr=120;function oc(e){if(e.claimedBy===void 0)return;let t=e.claimedAt?` since ${e.claimedAt}`:"",n=Array.from(e.claimedBy);return`Held by: ${n.length>Rr?`${n.slice(0,Rr).join("")}...`:e.claimedBy} (${e.claimSource??"unknown"}${t})`}function ic(e,t){let n=[`Error: ${e.title}`];(!t||!un(e.required))&&n.push("","What is required:",` ${e.required}`),e.nextSteps&&e.nextSteps.length>0&&(n.push(""),n.push(...Qn("Next steps:",e.nextSteps))),e.happened!==e.title&&n.push("","What happened:",` ${e.happened}`);let o=oc(e);return o!==void 0&&n.push("",o),n}function ac(e,t){let n=[];e.why&&!(t&&fn(e.why))&&n.push("","Why:",` ${e.why}`);let o=t?gn(e.examples):e.examples??[];o.length>0&&n.push("",...Qn("Examples:",o));let i=e.verificationErrors??[];return i.length>0&&n.push("",...Qn("Verification errors:",i)),n.push(...rc(e)),n}function rc(e){if(e.details!==void 0&&Object.keys(e.details).length>0)return["","Details:",...JSON.stringify(e.details,null,2).split(`
8
- `).map(o=>` ${o}`)];let t=e.detailsOmitted;if(t===void 0)return[];let n=t.path===void 0?` (over ${t.byte_limit} bytes)`:` at ${t.path}`;return["",`Details omitted: ${t.reason}${n}`]}function Tr(e,t={}){let n=t.lean===!0,o=[...ic(e,n),...ac(e,n)],i=nc(n?hn(e.recovery):e.recovery);return i.length>0&&(o.push(""),o.push(...i)),o.join(`
9
- `)}var sc="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for the full recovery envelope.",lc=400,Or=320;function cc(e){let t=_e(e);if(!t)return;let n={};t.suggested_retry&&Buffer.byteLength(t.suggested_retry,"utf8")<=lc&&(n.suggested_retry=t.suggested_retry);for(let o of["missing","missing_required_fields","allowed_values"]){let i=t[o];i&&i.length>0&&(n[o]=i.slice(0,3))}return t.next_best_command&&(n.next_best_command=t.next_best_command),Object.keys(n).length>0?n:void 0}function dc(e,t={}){let n=Tr(e,t),o=pn("error").default_max_estimated_tokens_by_format.text,i=d=>mn(Buffer.byteLength(d,"utf8"))<=o;if(i(n))return n;let a={...e,why:void 0},r={...a,details:void 0,examples:e.examples?.slice(0,1),nextSteps:e.nextSteps?.slice(0,1),verificationErrors:e.verificationErrors?.slice(0,3)},s={...r,recovery:cc(e.recovery)},c=Array.from(e.happened),l={...s,examples:void 0,happened:c.length>Or?`${c.slice(0,Or).join("")}...`:e.happened};for(let d of[a,r,s,l]){let m=`${Tr(d,t)}
1
+ import{a as qa}from"./chunks/chunk-5VRJPPUC.js";import"./chunks/chunk-DEZPZOQ7.js";import{A as Fn,C as lr,D as cr,F as dr,G as Ln,a as In,d as I,e as L,f as O,g as $,h as k,i as $a,n as Ve,o as Da,p as Ha,t as Ga,u as nr,v as or,w as ir,x as ar,y as rr,z as sr}from"./chunks/chunk-EZRLW4R6.js";import{Ua as tr,f as Oa,k as Ia}from"./chunks/chunk-O2M3TNFY.js";import"./chunks/chunk-JYQXIC6C.js";import"./chunks/chunk-UFIM5ZC5.js";import{A as Tt,D as Ja,E as Ka,F as Z,Fc as Qa,G as Ya,Hd as er,aa as Xa,b as Ae,l as La,q as Dn,r as Mn,s as za,t as Wa,u as Ba,v as Nn,w as Rt,x as Ke,z as Va}from"./chunks/chunk-JK7O7MFO.js";import"./chunks/chunk-UJMQP2HP.js";import"./chunks/chunk-VATZTJE3.js";import{ha as Za,j as Pa}from"./chunks/chunk-Z3QEEOAM.js";import"./chunks/chunk-YK5GAWOT.js";import"./chunks/chunk-XKY4LUXN.js";import"./chunks/chunk-6V4PGJBZ.js";import{C as kt,Cc as z,D as me,Qc as Ua,jb as Et,kb as H,mb as Ma,n as Ct,nb as Na,p as Be,pb as Fa,q as xt,sc as St,tc as At,uc as Pn,vc as Je,wc as E,xc as ja,yc as $n}from"./chunks/chunk-ELNWRSGZ.js";import{A as Aa,B as Ra,C as On,D as Ta,n as Rn,p as Ea,u as Tn,w as Sa}from"./chunks/chunk-BLUCQ4T4.js";import"./chunks/chunk-G6Q4VQSI.js";import"./chunks/chunk-IB7UB5TE.js";import{$c as wa,Ac as da,Ad as ka,Cc as ma,Gb as wt,Gc as pa,Hb as sa,Hc as ua,Ic as wn,J as xi,Kc as fa,Lc as de,Mc as bn,Nc as Cn,Oc as xn,Pc as kn,Qc as bt,Rc as En,Sc as ga,Tc as ha,Uc as ya,Vc as Sn,Wc as _a,Xc as Se,_c as va,gb as oa,hb as ia,ib as aa,jb as ra,kd as We,nd as ba,qc as vn,td as Ca,wc as la,yd as An,zc as ca,zd as xa}from"./chunks/chunk-ASJZMYKM.js";import{$c as Oi,Ca as an,Fa as se,Fd as dn,G as je,Gd as yt,Gh as X,Ha as wi,Hd as Li,Ia as ut,Ic as Ai,Id as ji,Kc as Ri,La as rn,Lg as zi,Ma as bi,Mg as Wi,Mi as vt,Na as T,Ng as Bi,Ob as ft,Og as Vi,Pa as Ci,Pg as Ji,Ph as Qi,Pi as ea,Qa as Y,Qg as Ki,Qh as oe,Qi as ta,Rb as ln,Rg as Yi,Sh as _n,Th as b,Ti as Ee,Ui as F,Vi as na,Xc as Ti,Yc as Ge,Zd as mn,_c as ze,ba as vi,cc as ki,dc as Ei,gb as _,ib as xe,id as Ii,jb as Ue,jd as Pi,jf as Ui,kd as $i,kf as qi,ld as Di,mb as qe,md as ne,nd as Mi,ng as pn,od as cn,og as un,pd as le,pg as Hi,ph as Xi,qd as Ni,qg as Gi,r as N,rb as He,rd as gt,sf as _t,sg as fn,t as B,tg as gn,th as Zi,u as q,ud as ke,ug as hn,vc as Si,vd as ce,w as J,wg as yn,x as on,xb as sn,y as V,yd as Fi,z as _i,zd as ht}from"./chunks/chunk-GCPP37N6.js";import"./chunks/chunk-SPPHDVZE.js";import"./chunks/chunk-RSAN2YUU.js";import"./chunks/chunk-VS565KBX.js";import{A as g,B as pt,C as R,E as K}from"./chunks/chunk-O4ZLEN4T.js";import"./chunks/chunk-XAWE4EAK.js";import{AsyncLocalStorage as Tl}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e47421c-706d-5e31-a466-6152cdeba30f")}catch{}})();var Re=new Tl;function mr(e){let t=Re.getStore();return t===void 0?e:t!==null}function pe(e,t=`warning:${e}`){let n=Re.getStore();n?(!n.has(e)||t!==`warning:${e}`)&&n.set(e,t):b(t)}function Ye(e){let t=Re.getStore();if(!t?.size)return e;let n=Reflect.get(e,"warnings"),o=[...t].filter(([r,s])=>s!==`warning:${r}`).map(([r,s])=>({code:r,message:s})),i=Reflect.get(e,"warning_details"),a={...e,warnings:[...Array.isArray(n)?n:[],...t.keys()],...o.length>0?{warning_details:[...Array.isArray(i)?i:[],...o]}:{}};return t.clear(),a}function jn(e){if(!Re.getStore()?.size)return e;let{token_accounting:t,...n}=Ye(JSON.parse(e));return JSON.stringify(t===void 0?n:X(n,o=>`${JSON.stringify(o,null,2)}
2
+ `),null,2)}async function pr(e,t){if(!e){await Re.run(null,t);return}let n=new Map;await Re.run(n,async()=>{await t(),n.size>0&&oe(`${JSON.stringify(Ye({type:"warning"}))}
3
+ `)})}import{AsyncLocalStorage as Ol}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad9cd4bc-07aa-5641-a1c4-b2aea5d4700c")}catch{}})();var Un=new Ol,ur=new WeakMap;function Il(e){let t=e.outputFormat!==void 0?["--output-format",e.outputFormat]:e.json===!0?["--json"]:[];return{scopeArgs:xe(e),outputArgs:t}}var fr=new WeakMap;function Pl(e,t){let n=e.registeredArguments.findIndex(o=>o.name()==="id");if(!(n===-1||e.name()==="plan"&&t[0]==="create"))return t[n]}function qn(e,t){return t.some(n=>n.path!==e.path||n.args.length!==e.args.length||n.args.some((o,i)=>o!==e.args[i]))}async function Hn(e){if(e.expectHash===void 0)return;let t=Rn(e.expectHash),n=e.commandPath.trim().toLowerCase();if(On(n,e.commandOptions),e.rewritten===!0)throw Tn();let o=Un.getStore();if(o===void 0)throw new TypeError("--expect-hash was parsed outside an invocation revision scope");let i=await Ea(e.pmRoot,t,Pl(e.command,e.commandArgs));aa(o,e.pmRoot,i),fr.set(o,n),e.globalOptions!==void 0&&ur.set(o,Il(e.globalOptions))}function Gn(e,t,n){let o=Un.getStore(),i=o===void 0?void 0:fr.get(o);if(i!==void 0){if(qn(e,[t]))throw Tn();On(i,n)}}function gr(e,t){if(t!==void 0)throw Rn(t),Ta(e)}function $l(e){for(let t of ra(e).unchecked)pe(Ra(t))}async function Dl(e,t){return e.pmRoot===void 0?t:Sa(t,e.pmRoot,ur.get(e))}async function hr(e){let t=oa();try{await e(n=>Un.run(t,()=>ia(t,n)))}catch(n){throw await Dl(t,n)}$l(t)}import{Command as si,CommanderError as Ys}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="50318c14-8c1c-50f3-95d0-fd9ea3f0bb69")}catch{}})();function W(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function ue(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return W(t)}function Q(e){let t=new Set,n=[];for(let o of e){let i=ue(o);i&&(t.has(i)||n.push(i),t.add(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]="ceab696e-18da-519f-8df1-ae9d92e5245f")}catch{}})();var zn=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),Ot=new Set(["--full","--brief","--compact"]);function Ml(e,t){return!!(e.flag==="--pm-path"||e.value_name||e.list||e.value_type==="number"||e.value_type==="string"||t.has(e.flag))}function Wn(e,t=k([...e])){let n=H(t),o=new Set([...Ma,...Na,...Fa].flatMap(s=>s.keys.map(c=>`--${c.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),i=new Map([...me,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,s.flag]))),a=new Map([...me,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,Ml(s,o)])));for(let s of zn)a.set(s,!0);for(let s of Ot)a.set(s,!1);let r=new Map;for(let s=0;s<e.length;s+=1){let c=e[s];if(c==="--")break;if(!c.startsWith("-"))continue;let l=c.split("=")[0];if(!a.has(l)&&!c.includes("="))return;let d=a.get(l)===!0&&!c.includes("=");r.set(s,{flag:i.get(l)??l,consumesValue:d}),d&&(s+=1)}return r}function Nl(e){let t=Wn(e);return t===void 0?void 0:new Map([...t].map(([n,{flag:o}])=>[n,o]))}function yr(e,t,n){let o=new Set;for(let[i,a]of t)n.has(a)&&(o.add(i),zn.has(a)&&!e[i].includes("=")&&o.add(i+1));return e.filter((i,a)=>!o.has(a))}function Fl(e,t){let n=t.find(i=>Ot.has(i));if(n===void 0)return;let o=[...new Set(e.values())].filter(i=>Ot.has(i));return o.length===1?o[0]:n}function _r(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,i={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return i;let a=Nl(e);if(!a)return i;let r;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return i;let c=[...a].find(([l,d])=>d==="--fields")?.[0]??-1;if(c<0)return i;r=yr(e,a,new Set(["--fields"])),r.splice(c,0,"--fields",o[s+1])}else{let s=Fl(a,o);if(s===void 0||![...a.values()].includes(s))return i;let c=new Set([...zn,...Ot].filter(l=>l!==s));r=yr(e,a,c)}return{...n,suggested_retry:_(r),suggested_retry_args: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]="df0b3527-6272-570d-8f41-6bcfa3bfd75d")}catch{}})();var vr=new Set(Vi);function Ll(e){return e.includes("@")&&e.includes(":")}function jl(e){let t=$([...e]);if(t===void 0)return;let n=e[t+1],o=n===void 0||n.startsWith("-")?void 0:`${e[t]} ${n}`;return o!==void 0&&Et(o)?o:e[t]}function Ul(e){let t=Ae(e??"",H(e));return new Set(t.filter(n=>n.takes_value).flatMap(n=>[n.flag,...n.aliases??[]]))}function wr(e,t,n,o=[],i=()=>!1){if(t!==Bi)return n;let a=n===void 0?void 0:{...n,suggested_retry:void 0,suggested_retry_args:void 0},r=jl(e),s=Wn(e,r);if(s===void 0||o===null||e.some(Ll)||i())return a;let c=ql(e,s,Ul(r));if(c===void 0||c.size===0)return a;let l=[...o,...e.filter((d,m)=>!c.has(m))];return{...n,suggested_retry:_(l),suggested_retry_args:l}}function ql(e,t,n){let o=new Set;for(let[i,{flag:a,consumesValue:r}]of t){if(!vr.has(a))continue;let s=e[i-1];if(s!==void 0&&!s.includes("=")&&n.has(s)||r&&e[i+1]?.startsWith("-")===!0)return;o.add(i),r&&o.add(i+1)}return e.some((i,a)=>!o.has(a)&&vr.has(i.split("=",1)[0]))?void 0: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]="c470fd86-4218-5aed-a681-58557d759b28")}catch{}})();var Hl="project_schema_field_requires_declared_flag";function Gl(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o.startsWith("--field=")?t.push({index:n,width:1,assignment:o.slice(8)}):o==="--field"&&n+1<e.length&&(t.push({index:n,width:2,assignment:e[n+1]}),n+=1)}return t}function br(e,t,n,o){let i=o?.suggested_flags?.[0];if(t!==Hl||n===void 0||i===void 0)return o;let a=Gl(e).filter(({assignment:d})=>d.split("=",1)[0].trim()===n&&d.includes("="));if(a.length!==1)return o;let[r]=a,s=r.assignment.trim(),c=s.slice(s.indexOf("=")+1),l=[...e.slice(0,r.index),i,c,...e.slice(r.index+r.width)];return{...o,suggested_retry:_(l),suggested_retry_args: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]="f8935dde-8de2-508e-b910-2a603a763c48")}catch{}})();var Bn=La;function zl(e,t,n,o,i){let a=[],r=e.indexOf(n,t);if(r<0||e.slice(t,r).some(s=>s.startsWith("-")))return a;for(let s=r+1;s<e.length;s+=1){let c=e[s];if(c==="--")break;c===`${o}=${i}`?a.push({index:s,width:1}):c===o&&e[s+1]===i&&(a.push({index:s,width:2}),s+=1)}return a}function Cr(e,t,n,o,i=[]){let a=o?.suggested_flags?.[0];if(t!==Bn||n===void 0||a===void 0||o.suggested_retry_args===void 0)return o;let r={...o,suggested_retry:void 0,suggested_retry_args:void 0},s=$([...e]);if(s===void 0||i===null)return r;let c=o.suggested_retry_args,l=zl(e,s,c[0],n,a);if(l.length!==1)return r;let{index:d,width:m}=l[0],p=[...e.slice(0,d),a,...e.slice(d+m)];if(!Wl(p,d,n,a,c))return r;let u=[...i,...p];return{...o,suggested_retry:_(u),suggested_retry_args:u}}function Wl(e,t,n,o,i){let a=i.lastIndexOf(o);return a<0||i.slice(a).some((r,s)=>e[t+s]!==r)?!1:!e.some((r,s)=>s!==t&&(r===n||r.startsWith(`${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]="bed9cdab-5e06-5035-8d76-d9943a8e7e5f")}catch{}})();var Vn="close_validation_missing_fields";function Bl(e,t,n,o){let i=e.slice(t+1);if(!i.includes("--"))return[...e,...o];if(!i.some(a=>n.has(a.split("=",1)[0])))return[...e.slice(0,t+1),...o,...i]}function Vl(e,t){let n=e.slice(0,e.length-2*t),o=n.length;for(;o>0&&n[o-1].startsWith("--expect-hash=");)o-=1;return n.slice(o)}function xr(e,t,n,o=[]){let i=n?.missing;if(t!==Vn||i===void 0||i.length===0)return n;let a=n.suggested_retry_args;if(a===void 0)return n;let r={...n,suggested_retry:void 0,suggested_retry_args:void 0},s=$([...e]);if(s===void 0||o===null)return r;let c=H(e[s].trim().toLowerCase()),l=i.map(f=>c.find(h=>h.flag===f||h.aliases?.includes(f)===!0));if(l.some(f=>f===void 0))return r;let d=new Set(l.flatMap(f=>[f.flag,...f.aliases??[]])),m=Vl(a,i.length),p=Bl(e,s,d,[...i.flatMap(f=>[f,"<value>"]),...m]);if(p===void 0)return r;let u=[...o,...p];return{...n,suggested_retry:_(u),suggested_retry_args:u}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afa4a7a0-d9de-529d-92dd-3e9704ea00d2")}catch{}})();async function kr(e,t){await xa(e,{ok:t.ok,error:t.error,result:ce(),exit_code:t.exit_code,error_code:t.error_code,error_category:t.error_category,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage})}async function Er(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await Xi({pmRoot:e.pmRoot,result:ce()})}catch(o){t=o}let n=await F(e.pmRoot);if(await Zi({pmRoot:e.pmRoot,author:_t(e.author,n.author_default),itemIds:e.itemIds,intent:e.intent}),t!==void 0)throw 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]="dacf3952-3ae1-57fa-840a-c8a43cf855a5")}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]="9490326e-507d-5b3e-9958-08c12afbc5ff")}catch{}})();var Sr=new WeakMap;function It(e,t){Sr.set(e,t)}function fe(e){return Sr.get(e)}function Ar(e){return e.length>0?[e[0]]:[]}function Jl(e){let t=["","Intent:",` ${e.why}`],n=Ar(e.examples);return n.length>0&&(t.push("","Example:"),t.push(` ${n[0]}`)),t.push("","Need deeper rationale and more examples?"),t.push(" Re-run with --explain."),t.join(`
4
+ `)}function Kl(e){let t=["","Why use this command:",` ${e.why}`,"","Examples:",...e.examples.map(n=>` ${n}`)];return e.tips&&e.tips.length>0&&(t.push("","Tips:"),t.push(...e.tips.map(n=>` - ${n}`))),t.join(`
5
+ `)}function Rr(e,t){return t==="detailed"?Kl(e):Jl(e)}function j(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var Yl={cal:"calendar",ctx:"context"};function Xl(e,t){return e.commands.find(n=>n.name()===t)??null}function Zl(e,t){let n=e;for(let o of t){let i=Xl(n,o);if(!i)return null;n=i}return n}function Jn(e,t,n,o){let i=Zl(e,t.split(" ").filter(a=>a.length>0));i&&i.addHelpText("after",Rr(n,o))}function Kn(e){return e.includes("--explain")?"detailed":"compact"}function ie(e){return e.includes("--all")||e.includes("--explain")}var ge={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm package install ./my-package --project","pm package install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm package install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm package upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm package install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm package install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm package install ./my-extension --project","pm package --install --project ./my-extension","pm package doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list --all --limit 50","pm list --all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status in_progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list --blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm package install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspect recorded mutations.",examples:["pm history pm-a1b2 --order oldest_first","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:["pm claim pm-a1b2 --start",'pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of N){let n=ge[e];n&&(ge[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var Te={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},Tr=J.filter(e=>e.lifecycle==="deprecated");for(let e of Tr){let t=ge[e.alias];ge[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[Te,...Object.values(ge)])e.examples=e.examples.map(t=>{for(let n of Tr){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Ql(e){let t=j(e??"");return t?Yl[t]??t:""}function Yn(e){let t=Ql(e);return t?ge[t]??Te:Te}function Or(e,t){let n=Yn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Ar(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function ec(){let e=J.filter(({lifecycle:n})=>n==="permanent"),t=J.filter(({lifecycle:n})=>n==="deprecated");return["","Command aliases:",...e.map(({alias:n,canonical_argv:o})=>` ${n} -> pm ${o.join(" ")}`),"","Deprecated aliases:",...t.map(n=>` ${n.alias} -> pm ${n.canonical_argv.join(" ")} (${_i(n)})`)].join(`
6
+ `)}function tc(e,t,n,o){let i=new Set(Ja);e.configureHelp({visibleCommands(r){let s=t.visibleCommands(r);return n?s.filter(c=>(fe(c)??Z(c.name()))!=="internal"):r!==e?s:s.filter(c=>o.has(c))},visibleOptions(r){let s=t.visibleOptions(r);return r!==e||n?s:s.filter(c=>i.has(c.flags))}});let a=e.options.filter(r=>r.long==="--output-cursor");for(let r of e.commands.flatMap(s=>[s,...s.commands]))["list","search","context"].includes(r.name())&&r.configureHelp({visibleOptions:s=>[...t.visibleOptions(s),...a]})}function nc(e,t,n,o){let i=new Set(Ya("core")),a=e.createHelp();a.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let r=()=>`${a.formatHelp(e,a)}${o}
7
+ `,s=t.visibleCommands(e);for(let c of s)fe(c)===void 0&&(c.name()==="help"||i.has(c.name()))&&n.add(c);for(let c of s)fe(c)==="core"&&(n.add(c),Ka(r()).within_budget||n.delete(c))}function Ir(e,t=process.argv.slice(2)){let n=e.createHelp(),o=ie(t),i=new Set;tc(e,n,o,i);let a=Kn(t),r=Rr(Te,a);e.addHelpText("after",r),o&&e.addHelpText("after",ec()),nc(e,n,i,r);for(let[d,m]of Object.entries(ge))Jn(e,d,m,a);let s=j(O(t).commandPathTokens.join(" ")),c=Be(s);if(c){Jn(e,c.parent,{why:c.description,examples:[c.example],tips:[`Action path: pm ${c.command}`,xt(c.accepted_flags)]},a);return}let l=Ct.filter(({parent:d})=>d===s);l.length>0&&Jn(e,s,{why:`Dispatches one declared positional action: ${l.map(({action:d})=>d).join("|")}.`,examples:l.map(({example:d})=>d),tips:[`Inspect one action directly with pm ${s} <action> --help --json.`]},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]="2efeb172-b440-5df6-ad48-4c54087835e0")}catch{}})();function Xn(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:i}of N){if(t&&!N.some(l=>l.canonical.startsWith(`${o} `)))continue;let a=e.commands.findIndex(l=>l.name()===n);if(a<0)continue;let r=e.commands[a],s=e;for(let l of i.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===l)??s.command(l).description(`Discover ${l} operations.`);let c=i[i.length-1];if(s.commands.some(l=>l.name()===c))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(a,1),r.name(c),It(r,Z(o)),s.enablePositionalOptions(),s.addCommand(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]="cfefc733-0def-51b4-9aa3-33d7d8e6fca5")}catch{}})();function $t(e){let{title:t,...n}=e;gn(n.why)&&delete n.why,fn(n.required)&&delete n.required;let o=hn(n.examples);o.length>0?n.examples=o:delete n.examples;let i=yn(n.recovery);return i===void 0?delete n.recovery:n.recovery=i,n}var oc=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function ic(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!oc.has(e.code)}function jr(e){return`urn:pm-cli:error:${e}`}function C(e){return{...e,type:jr(e.code)}}var Oe={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Pr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},$r={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},Pt={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},ac={guide:Oe,shell:Oe,completion:Oe,"completion-statuses":Oe,"completion-tags":Oe,"completion-types":Oe,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Pr,cal:Pr,reindex:$r,"search-advanced":$r,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":Pt,"dedupe-audit":Pt,"dedupe-merge":Pt,normalize:Pt};function rc(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return ac[t]}function to(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function sc(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function lc(e){if(!Array.isArray(e))return;let t=e.map(n=>({source:typeof n?.source=="string"?n.source.trim():"",command:typeof n?.command=="string"?n.command.trim():"",reason:typeof n?.reason=="string"?n.reason.trim():""})).filter(n=>n.source.length>0&&n.command.length>0&&n.reason.length>0);return t.length>0?t:void 0}function Zn(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function Ur(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")?[...e]:void 0}function ee(e,t,n){if(t==="normalized_args"||t==="suggested_retry_args"){let i=Ur(n);i&&(e[t]=i);return}if(t==="parsed_positionals"){if(!Array.isArray(n))return;let i=n.map(a=>({role:typeof a?.role=="string"?a.role.trim():"",value:typeof a?.value=="string"?a.value.trim():""})).filter(a=>a.role.length>0&&a.value.length>0);i.length>0&&(e.parsed_positionals=i);return}let o=sc(n);o&&(e[t]=o)}function cc(e,t){if(!ma(t))return;let{requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:a,basis:r,reason:s}=t;e.token_budget={requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:a,basis:r,reason:s}}var qr=["retry_after_ms","waited_ms","owner_handoffs"];function dc(e,t){for(let n of qr)typeof t[n]=="number"&&e.push(` ${n}: ${t[n]}`)}function mc(e,t){for(let n of qr){let o=t[n];typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&(e[n]=o)}}function _e(e){if(!e||typeof e!="object")return;let t={};cc(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Zn(t,"attempted_command",e.attempted_command),ee(t,"normalized_args",e.normalized_args),ee(t,"parsed_positionals",e.parsed_positionals),ee(t,"provided_fields",e.provided_fields),ee(t,"missing",e.missing),ee(t,"missing_required_fields",e.missing_required_fields),ee(t,"suggested_flags",e.suggested_flags),ee(t,"allowed_values",e.allowed_values),ee(t,"candidate_commands",e.candidate_commands),typeof e.candidate_commands_total=="number"&&Number.isSafeInteger(e.candidate_commands_total)&&e.candidate_commands_total>=0&&(t.candidate_commands_total=e.candidate_commands_total),e.candidate_commands_truncated===!0&&(t.candidate_commands_truncated=!0),(e.option_scope==="declared_on_path"||e.option_scope==="declared_elsewhere"||e.option_scope==="declared_nowhere")&&(t.option_scope=e.option_scope),Zn(t,"suggested_retry",e.suggested_retry),ee(t,"suggested_retry_args",e.suggested_retry_args),mc(t,e);let n=lc(e.fallback_candidates);return n&&(t.fallback_candidates=n),Zn(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Qn(e,t,n){n&&e.push(` ${t}: ${n}`)}function he(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function pc(e){let t=_e(e);if(!t)return[];let n=["Recovery bundle:"];if(t.token_budget){let o=t.token_budget;n.push(` requested_token_budget: ${o.requested_tokens}`,` feasible_token_budget: ${o.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${o.minimum_feasible_tokens??"not established"}`)}if(Qn(n,"suggested_retry",t.suggested_retry),Qn(n,"attempted_command",t.attempted_command),he(n,"normalized_args",t.attempted_command?void 0:t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(he(n,"provided_fields",t.provided_fields,", "),he(n,"missing",t.missing,", "),he(n,"missing_required_fields",t.missing_required_fields,", "),he(n,"suggested_flags",t.suggested_flags,", "),he(n,"allowed_values",t.allowed_values,", "),he(n,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&n.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&n.push(" candidate_commands_truncated: true"),t.option_scope!==void 0&&n.push(` option_scope: ${t.option_scope}`),dc(n,t),Qn(n,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){n.push(" fallback_candidates:");for(let o of t.fallback_candidates)n.push(` - ${o.source}: ${o.command} (${o.reason})`)}return n}var Dr=120;function uc(e){if(e.claimedBy===void 0)return;let t=e.claimedAt?` since ${e.claimedAt}`:"",n=Array.from(e.claimedBy);return`Held by: ${n.length>Dr?`${n.slice(0,Dr).join("")}...`:e.claimedBy} (${e.claimSource??"unknown"}${t})`}function fc(e,t){let n=[`Error: ${e.title}`];(!t||!fn(e.required))&&n.push("","What is required:",` ${e.required}`),e.nextSteps&&e.nextSteps.length>0&&(n.push(""),n.push(...to("Next steps:",e.nextSteps))),e.happened!==e.title&&n.push("","What happened:",` ${e.happened}`);let o=uc(e);return o!==void 0&&n.push("",o),n}function gc(e,t){let n=[];e.why&&!(t&&gn(e.why))&&n.push("","Why:",` ${e.why}`);let o=t?hn(e.examples):e.examples??[];o.length>0&&n.push("",...to("Examples:",o));let i=e.verificationErrors??[];return i.length>0&&n.push("",...to("Verification errors:",i)),n.push(...hc(e)),n}function hc(e){if(e.details!==void 0&&Object.keys(e.details).length>0)return["","Details:",...JSON.stringify(e.details,null,2).split(`
8
+ `).map(o=>` ${o}`)];let t=e.detailsOmitted;if(t===void 0)return[];let n=t.path===void 0?` (over ${t.byte_limit} bytes)`:` at ${t.path}`;return["",`Details omitted: ${t.reason}${n}`]}function Mr(e,t={}){let n=t.lean===!0,o=[...fc(e,n),...gc(e,n)],i=pc(n?yn(e.recovery):e.recovery);return i.length>0&&(o.push(""),o.push(...i)),o.join(`
9
+ `)}var yc="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for the full recovery envelope.",_c=400,Nr=320;function vc(e){let t=_e(e);if(!t)return;let n={};t.suggested_retry&&Buffer.byteLength(t.suggested_retry,"utf8")<=_c&&(n.suggested_retry=t.suggested_retry);for(let o of["missing","missing_required_fields","allowed_values"]){let i=t[o];i&&i.length>0&&(n[o]=i.slice(0,3))}return t.next_best_command&&(n.next_best_command=t.next_best_command),Object.keys(n).length>0?n:void 0}function wc(e,t={}){let n=Mr(e,t),o=un("error").default_max_estimated_tokens_by_format.text,i=d=>pn(Buffer.byteLength(d,"utf8"))<=o;if(i(n))return n;let a={...e,why:void 0},r={...a,details:void 0,examples:e.examples?.slice(0,1),nextSteps:e.nextSteps?.slice(0,1),verificationErrors:e.verificationErrors?.slice(0,3)},s={...r,recovery:vc(e.recovery)},c=Array.from(e.happened),l={...s,examples:void 0,happened:c.length>Nr?`${c.slice(0,Nr).join("")}...`:e.happened};for(let d of[a,r,s,l]){let m=`${Mr(d,t)}
10
10
 
11
- ${sc}`;if(i(m))return m}return n}function mc(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId),t.claimedBy!==void 0&&(e.claimed_by=t.claimedBy,e.claimed_at=t.claimedAt??null,e.claim_source=t.claimSource??"unknown",e.item_id=t.itemId),t.currentRevision!==void 0&&(e.expected_revision=t.expectedRevision??null,e.current_revision=t.currentRevision,t.itemId!==void 0&&(e.item_id=t.itemId))}function Nr(e,t){return t.sideEffects!==void 0&&(e.side_effects=t.sideEffects),t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),mc(e,t),Jl(t)&&(e.why=t.why),t.examples&&t.examples.length>0&&(e.examples=t.examples),t.nextSteps&&t.nextSteps.length>0&&(e.next_steps=t.nextSteps),t.verificationErrors&&t.verificationErrors.length>0&&(e.verification_errors=t.verificationErrors),t.flag!==void 0&&(e.flag=t.flag),t.value!==void 0&&(e.value=t.value),t.unmatchedSelectors!==void 0&&(e.unmatched_selectors=t.unmatchedSelectors),t.availableDependencies!==void 0&&(e.available_dependencies=t.availableDependencies),t.recovery&&(e.recovery=t.recovery),e}function pc(e,t){if(e.flag)return e.flag;let n=o=>{let i=o.split("=",1)[0];return F([i]).length>0&&!["--help","--no-changed-fields","--version"].includes(i)&&t.some(a=>a===i||a.startsWith(`${i}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(o=>o[0]).find(o=>n(o))}function uc(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(a=>a===n||a.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let i=t.indexOf(n);return t[i+1]}}function fc(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=F(e.recovery?.normalized_args??[]),o=W(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,a=pc(e,i),r=uc(e,i,a);return{surface:a??e.recovery?.missing?.[0]??Nn(i)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function gc(e,t){let n=Nr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:fc(e,t),...e.changed===!1?{changed:!1}:{}},e);return e.details!==void 0&&(n.details=e.details),e.detailsOmitted!==void 0&&(n.details_omitted=e.detailsOmitted),n}function eo(e,t){let n=e.recovery,o=n?.suggested_retry||n?.suggested_retry_args?.length||n?.allowed_values?.length||n?.candidate_commands?.length||e.nextSteps?.length?"recovery_bundle":"error";return Ui(hc(gc(e,t),o),{diagnosticClass:o})}function hc(e,t){if(e.details===void 0)return e;let n=pn(t).default_max_estimated_tokens_by_format.json;if(mn(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))<=n)return e;let{details:o,...i}=e;return{...i,details_omitted:{reason:"diagnostic_budget",byte_limit:ia.max_bytes}}}function to(e){return Nr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function $t(e){return e.replace(/\(outputHelp\)/g,"").trim()}function yc(e){let t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function ye(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function Ir(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function _c(e){return Nn(e?.normalized_args)}function vc(e){let t=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return t?t[1].split(/[|,]/).map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_.-]+$/.test(n)):[]}function wc(e,t){let n=e?.normalized_args,o=e?.provided_fields,i=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!i))for(let a of o){let r=n.findIndex(s=>s===a);if(r>=0&&r<n.length-1&&!n[r+1]?.startsWith("-")){let s=[...n];return s[r+1]=i,_(s)}}}function bc(e){let t=e.split(/\r?\n/)[0].trim();if(t.length===0)return;let n=Array.from(t);return n.length<=120?t:`${n.slice(0,117).join("")}...`}function Ye(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function Cc(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function xc(e,t,n,o){let i=e.code==="command_failed"||e.code==="invalid_argument_value"&&t!==e.code;return(n.code&&i?bc(o):void 0)??e.title}function kc(e){let t=ra(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}function ae(e,t,n){if(!n)return e;let o=$t(t),i=Ye(n.code,e.code),a=Ye(n.type,$r(i)),r=ye(n.examples)??e.examples,s=ye(n.nextSteps)??e.nextSteps,c=ye(n.verification_errors)??e.verificationErrors,l=_e(n.recovery),d=l&&e.recovery?_e({...e.recovery,...l}):l??e.recovery;return{...e,code:i,changed:n.changed,sideEffects:n.side_effects,type:a,title:xc(e,i,n,o),happened:o.length>0?o:e.happened,required:Ye(n.required,e.required),why:Ye(n.why,e.why),examples:r,nextSteps:s,verificationErrors:c,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:Cc(n,d)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,claimedBy:n.claimed_by,claimedAt:n.claimed_at,claimSource:n.claim_source,expectedRevision:n.expected_revision,currentRevision:n.current_revision,availableDependencies:n.available_dependencies,recovery:d,...kc(n)}}function Ec(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let i=o[1],a=vi(process.cwd(),i);return ae(C(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${i}, but found a tracker at ${a}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${a} <command>`,`PM_PATH=${a} pm <command>`],nextSteps:[`Re-run with "--pm-path ${a}" or export PM_PATH=${a}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function Sc(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let i=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(i),r=a?`The item ID "${i}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${i}" exists in the active tracker scope.`;return ae(C({code:"item_not_found",title:"Item ID not found",flag:"id",value:i,happened:r,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:a?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function Ac(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ae(C({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function Rc(e,t,n){if(!t.includes("is locked"))return null;let o=Dr(n?.recovery?.normalized_args),i=o?_(o):void 0,a=ae(C({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:i?[i]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(a.recovery={...a.recovery,suggested_retry:i,suggested_retry_args:[...o]}),a}function Tc(e,t,n){let o=t.match(/^Missing required option /),i=t.match(/^Missing required options /);if(!o&&!i)return null;let a=!!i,r=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=r??"",c=r?`Pass ${r} with a valid value before running the command.`:"Provide the required option for this command invocation.";return ae(C({code:"missing_required_option",title:a?"Missing required options":`Missing required option ${s}`,happened:t,required:a?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function Oc(e,t,n){return t.startsWith("No update flags provided")?ae(C({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function Ic(e,t){if(e.startsWith("Invalid "))return!0;if(!e.includes(" must be ")&&!e.includes(" requires "))return!1;let n=Ye(t?.code,void 0);return n===void 0||n==="invalid_argument_value"||t?.allowed!==void 0}function Pc(e,t,n){if(!Ic(t,n))return null;let o=_e(n?.recovery),i=_c(o),a=i?`pm ${i} --help`:"pm <command> --help",r=n?.allowed??vc(t),s=_e({...o,allowed_values:o?.allowed_values??r}),c=wc(o,r),l=c?[c,a]:[a,"pm contracts --command <command> --flags-only --json"],d=r.length>0?[`Allowed values: ${r.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return ae(C({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:l,nextSteps:d,recovery:s}),e,n)}function no(e,t){let n=$t(e);return(Ec(e,n,t)??Sc(e,n,t)??Ac(e,n,t)??Rc(e,n,t)??Tc(e,n,t)??Oc(e,n,t)??Pc(e,n,t))||ae(C({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function $c(e,t,n){return e==="create"&&t.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${n.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function Dc(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Mc(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function oo(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function H(e,t={}){let n=oo(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Mc(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return _e({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:a,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Zn(e,t){return!t||e.includes(t)?e:[...e,t]}var Nc=new Set(["--add","--add-json","--remove"]),Fc=new Set(["command","cmd","path"]);function Lc(e){if(Array.isArray(e))for(let t of e){if(!t.startsWith("--"))continue;let n=t.indexOf("="),o=n>=0?t.slice(0,n):t;if(Nc.has(o))return o}}function jc(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let i=e[o];if(i!=="--add"&&i!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!Fc.has(a))return;let r=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;r.push(d)}if(r.length<2)return;let s=`${a}=${r.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+r.length)];return _(c)}}function Uc(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let a=Dc(i[1]),r=a.startsWith("--type"),s=o?.suggestedRetryCommand,c=oo(o?.providedOptionFlags),l=[a],d=$c(t,a,n),m=s?Zn(d,s):d,p=r?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Zn(p,`Replay with preserved arguments: ${s}`):p,f=c&&c.length>0?Zn(u,`Already provided options: ${c.join(", ")}`):u;return C({code:"missing_required_option",title:`Missing required option ${a}`,happened:`Commander rejected the command because ${a} was not provided.`,required:`Pass ${a} with a valid value before running the command.`,why:r?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:H(o,{missing:l})})}function qc(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let i=o[1];return C({code:"missing_required_argument",title:`Missing required argument ${i}`,happened:`Command invocation omitted positional argument ${i}.`,required:`Provide ${i} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:H(n,{missing:[i]})})}function Hc(e,t,n){return C({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:H(t,{suggested_flags:n})})}var Gc={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function zc(e){let t=ye(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Wc(e,t,n,o,i){let a=o.otherCommands.slice(0,3),r=o.candidateTotal-a.length,s=r>0?` and ${String(r)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i?void 0:Bc(e,t),a.length?`${e} is accepted by ${a.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,Lr(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,i?`Replay with suggested correction: ${i}`:void 0].filter(c=>typeof c=="string")}var Fr=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function Bc(e,t){if(t===void 0||!Fr.includes(e.split("=",1)[0]))return;let n=Qa(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${er(n)}.`}function Vc(e,t,n){let o=tr(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:_(o),suggestedRetryArgs:o}:[...Fr,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function Lr(e){return/\s/u.test(e)}function Jc(e,t){let n=e?.indexOf(t)??-1;if(e===void 0||n<0||e.includes("--")||e.lastIndexOf(t)!==n)return{};if(e.slice(n+1).some(i=>!i.startsWith("-")))return{};let o=[...F(e.filter((i,a)=>a!==n)),"--",t];return{retryCommand:_(o),suggestedRetryArgs:o}}function Kc(e,t,n){if(Lr(t))return Jc(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=Vc(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(nr(t))return{};let i=e.normalizedInvocationArgs;if(i===void 0)return{};if(i.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let a=i.findIndex(s=>s===t||s.startsWith(`${t}=`));if(a<0||i.includes("--")||!i[a]?.includes("=")&&a!==i.length-1&&i[a+1]?.startsWith("-")!==!0)return{};let r=F(i.filter((s,c)=>c!==a));return{retryCommand:_(r),suggestedRetryArgs:r}}function Yc(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},a=o[1],r=oo(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:c}=Kc(i,a,t);if(t==="update"&&(a==="--file"||a==="--doc"))return Hc(a,n,r);let l=zc(i),d=Wc(a,t,r,l,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(a.split("=",1)[0])&&d.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${B(t)?.canonical??t} --help`:"pm --help --all"].filter(p=>typeof p=="string");return C({code:"unknown_option",title:`Unknown option ${a}`,happened:`Commander does not recognize option ${a} for this command path.`,required:Gc[l.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:a,value:a,examples:m,nextSteps:d,recovery:H(n,{suggested_flags:r.length>0?r:void 0,suggested_retry:s,suggested_retry_args:c,candidate_commands:l.otherCommands,candidate_commands_total:l.candidateTotal||void 0,candidate_commands_truncated:i.unknownOptionOtherCommandsTruncated,option_scope:l.optionScope})})}function Xc(e,t,n,o,i){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,r=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return C({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:Ir([t.installCommand,...n]),nextSteps:Ir([a,...r]),recovery:H(i)})}function Zc(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=ye(t?.unknownCommandExamples),a=ye(t?.unknownCommandNextSteps),r=Yl(o),s=i??["pm --help"],c=a??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=r?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return r&&(!d||!l.has(d))?Xc(o,r,s,c,t):C({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:H(t)})}function Qc(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ye(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let i=e?.suggestedRetryCommand;return C({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...i?[i]:[],`pm ${B(t)?.canonical??t} --help`],nextSteps:i?[`Retry with the declared hyphenated action: ${i}`]:["Choose one value from recovery.allowed_values."],recovery:H(e,{allowed_values:o,suggested_retry:i})})}function ed(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=Lc(o);if(!i)return null;let a=jc(o);return C({code:"linked_test_value_not_quoted",title:`Linked-test ${i} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${i} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${i} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...a?[a]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...a?[`Replay with the value re-joined into one argument: ${a}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:H(n,a?{suggested_retry:a}:{})})}var td=new Set(["comments","docs","files","learnings","notes","test"]);function nd(e,t,n){if(!/too many arguments/i.test(e))return null;let o=bi(t,n?.normalizedInvocationArgs??[]);if(!o)return null;let i=o.retryArgs?_(o.retryArgs):void 0,a=_(o.templateArgs??["test",o.itemId,"--add",`command=<actual command>,${o.value}`]);return C({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:i?`Retry the explicit collection mutation: ${i}`:`Supply the actual command and its metadata together, for example ${a}.`,examples:[i??a],recovery:H(n,{suggested_retry:i,suggested_retry_args:o.retryArgs})})}function od(e,t,n){if(!/too many arguments/i.test(e)||!td.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>l===t),a=o[i+1],r=o[i+2],s=n?.verifiedCollectionItemId?.trim();if(a?.toLowerCase()!=="add"||!r||r.startsWith("-")||!s||s.toLowerCase()!==r.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return C({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:H(n,{parsed_positionals:[{role:"transposed_subcommand",value:a},{role:"item_id",value:s}],suggested_retry:c})})}var id=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),Pr=new Set(["context","ctx"]);function ad(e,t,n){if(!/too many arguments/i.test(e)||!Pr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>Pr.has(l)),a=i===-1?1:i+1,r=e.match(/got \d+:\s*(\S+)/i),s=r?r[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(a)){if(l){l=!1;continue}let m=d.split("=")[0];if(id.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return C({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:H(n,{suggested_retry:c})})}function io(e,t,n,o){let i=$t(e);return(Uc(i,t,n,o)??qc(i,t,o)??Yc(i,t,o)??Zc(i,o)??Qc(o)??od(i,t,o)??ed(i,t,o)??nd(i,t,o)??ad(i,t,o))||C({code:"invalid_command_usage",title:"Invalid command usage",happened:i,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:H(o)})}function jr(e,t,n={}){let o=no(e,t);return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&o.title==="Tracker is not initialized"&&o.recovery?.suggested_retry_args?[`Error: ${o.title}`,`Run: ${_(o.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
12
- `):Ur(o,n)}function Ur(e,t){let n=a=>qi(dc(e,a),e.required).output,o=n(t);if(t.lean!==!0)return o;let i=n({});return Buffer.byteLength(i,"utf8")<Buffer.byteLength(o,"utf8")?i:o}function qr(e,t){return to(no(e,t))}function ao(e,t,n){return eo(no(e,n),t)}function Hr(e,t,n,o,i={}){let a=io(e,t,n,o);return Ur(a,i)}function ro(e,t,n,o){return to(io(e,t,n,o))}function Dt(e,t,n,o,i){return eo(io(e,t,n,i),o)}function Gr(e,t){let n=zr(e);return eo(n,t)}function zr(e){let t=$t(e);return yc(t)?C({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):C({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function Wr(e){return to(zr(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]="4647d40c-70a2-5ffe-a91f-d43e9c522114")}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]="e860a827-39e1-5d6c-b76e-0d77365ba202")}catch{}})();var Xe=yi.join("|"),rd={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},sd={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}},Br=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function ld(e,t){let n=sd[e];if(!n)return[];let o=z(t);for(let[i,a]of Object.entries(n))if(z(i)===o)return a;return[]}function so(e,t,n){if(n.length===0)return e;if(t){let r=n.find(d=>d.declared_command_match===!0),{token_accounting:s,...c}=JSON.parse(e),l={...c,...r?{extension_command_failure:{code:"extension_command_activation_failed",extension:r.name,layer:r.layer,error:r.error,recovery_commands:r.recovery_commands??[]}}:{},failed_extensions:n};return JSON.stringify(s===void 0?l:X(l,d=>`${JSON.stringify(d,null,2)}
11
+ ${yc}`;if(i(m))return m}return n}function bc(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId),t.claimedBy!==void 0&&(e.claimed_by=t.claimedBy,e.claimed_at=t.claimedAt??null,e.claim_source=t.claimSource??"unknown",e.item_id=t.itemId),t.currentRevision!==void 0&&(e.expected_revision=t.expectedRevision??null,e.current_revision=t.currentRevision,t.itemId!==void 0&&(e.item_id=t.itemId))}function Hr(e,t){return t.sideEffects!==void 0&&(e.side_effects=t.sideEffects),t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),bc(e,t),ic(t)&&(e.why=t.why),t.examples&&t.examples.length>0&&(e.examples=t.examples),t.nextSteps&&t.nextSteps.length>0&&(e.next_steps=t.nextSteps),t.verificationErrors&&t.verificationErrors.length>0&&(e.verification_errors=t.verificationErrors),t.flag!==void 0&&(e.flag=t.flag),t.value!==void 0&&(e.value=t.value),t.unmatchedSelectors!==void 0&&(e.unmatched_selectors=t.unmatchedSelectors),t.availableDependencies!==void 0&&(e.available_dependencies=t.availableDependencies),t.recovery&&(e.recovery=t.recovery),e}function Cc(e,t){if(e.flag)return e.flag;let n=o=>{let i=o.split("=",1)[0];return L([i]).length>0&&!["--help","--no-changed-fields","--version"].includes(i)&&t.some(a=>a===i||a.startsWith(`${i}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(o=>o[0]).find(o=>n(o))}function xc(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(a=>a===n||a.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let i=t.indexOf(n);return t[i+1]}}function kc(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=L(e.recovery?.normalized_args??[]),o=B(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,a=Cc(e,i),r=xc(e,i,a);return{surface:a??e.recovery?.missing?.[0]??Fn(i)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Ec(e,t){let n=Hr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:kc(e,t),...e.changed===!1?{changed:!1}:{}},e);return e.details!==void 0&&(n.details=e.details),e.detailsOmitted!==void 0&&(n.details_omitted=e.detailsOmitted),n}function no(e,t){let n=e.recovery,o=n?.suggested_retry||n?.suggested_retry_args?.length||n?.allowed_values?.length||n?.candidate_commands?.length||e.nextSteps?.length?"recovery_bundle":"error";return Hi(Sc(Ec(e,t),o),{diagnosticClass:o})}function Sc(e,t){if(e.details===void 0)return e;let n=un(t).default_max_estimated_tokens_by_format.json;if(pn(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))<=n)return e;let{details:o,...i}=e;return{...i,details_omitted:{reason:"diagnostic_budget",byte_limit:la.max_bytes}}}function oo(e){return Hr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function Dt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Ac(e){let t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function ye(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function Fr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Rc(e){return Fn(e?.normalized_args)}function Tc(e){let t=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return t?t[1].split(/[|,]/).map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_.-]+$/.test(n)):[]}function Oc(e,t){let n=e?.normalized_args,o=e?.provided_fields,i=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!i))for(let a of o){let r=n.findIndex(s=>s===a);if(r>=0&&r<n.length-1&&!n[r+1]?.startsWith("-")){let s=[...n];return s[r+1]=i,_(s)}}}function Ic(e){let t=e.split(/\r?\n/)[0].trim();if(t.length===0)return;let n=Array.from(t);return n.length<=120?t:`${n.slice(0,117).join("")}...`}function Xe(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function Pc(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function $c(e,t,n,o){let i=e.code==="command_failed"||e.code==="invalid_argument_value"&&t!==e.code;return(n.code&&i?Ic(o):void 0)??e.title}function Dc(e){let t=da(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}function ae(e,t,n){if(!n)return e;let o=Dt(t),i=Xe(n.code,e.code),a=Xe(n.type,jr(i)),r=ye(n.examples)??e.examples,s=ye(n.nextSteps)??e.nextSteps,c=ye(n.verification_errors)??e.verificationErrors,l=_e(n.recovery),d=l&&e.recovery?_e({...e.recovery,...l}):l??e.recovery;return{...e,code:i,changed:n.changed,sideEffects:n.side_effects,type:a,title:$c(e,i,n,o),happened:o.length>0?o:e.happened,required:Xe(n.required,e.required),why:Xe(n.why,e.why),examples:r,nextSteps:s,verificationErrors:c,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:Pc(n,d)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,claimedBy:n.claimed_by,claimedAt:n.claimed_at,claimSource:n.claim_source,expectedRevision:n.expected_revision,currentRevision:n.current_revision,availableDependencies:n.available_dependencies,recovery:d,...Dc(n)}}function Mc(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let i=o[1],a=bi(process.cwd(),i);return ae(C(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${i}, but found a tracker at ${a}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${a} <command>`,`PM_PATH=${a} pm <command>`],nextSteps:[`Re-run with "--pm-path ${a}" or export PM_PATH=${a}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function Nc(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let i=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(i),r=a?`The item ID "${i}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${i}" exists in the active tracker scope.`;return ae(C({code:"item_not_found",title:"Item ID not found",flag:"id",value:i,happened:r,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:a?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function Fc(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ae(C({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function Lc(e,t,n){if(!t.includes("is locked"))return null;let o=Ur(n?.recovery?.normalized_args),i=o?_(o):void 0,a=ae(C({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:i?[i]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(a.recovery={...a.recovery,suggested_retry:i,suggested_retry_args:[...o]}),a}function jc(e,t,n){let o=t.match(/^Missing required option /),i=t.match(/^Missing required options /);if(!o&&!i)return null;let a=!!i,r=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=r??"",c=r?`Pass ${r} with a valid value before running the command.`:"Provide the required option for this command invocation.";return ae(C({code:"missing_required_option",title:a?"Missing required options":`Missing required option ${s}`,happened:t,required:a?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function Uc(e,t,n){return t.startsWith("No update flags provided")?ae(C({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function qc(e,t){if(e.startsWith("Invalid "))return!0;if(!e.includes(" must be ")&&!e.includes(" requires "))return!1;let n=Xe(t?.code,void 0);return n===void 0||n==="invalid_argument_value"||t?.allowed!==void 0}function Hc(e,t,n){if(!qc(t,n))return null;let o=_e(n?.recovery),i=Rc(o),a=i?`pm ${i} --help`:"pm <command> --help",r=n?.allowed??Tc(t),s=_e({...o,allowed_values:o?.allowed_values??r}),c=Oc(o,r),l=c?[c,a]:[a,"pm contracts --command <command> --flags-only --json"],d=r.length>0?[`Allowed values: ${r.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return ae(C({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:l,nextSteps:d,recovery:s}),e,n)}function io(e,t){let n=Dt(e);return(Mc(e,n,t)??Nc(e,n,t)??Fc(e,n,t)??Lc(e,n,t)??jc(e,n,t)??Uc(e,n,t)??Hc(e,n,t))||ae(C({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function Gc(e,t,n){return e==="create"&&t.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${n.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function zc(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Wc(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function ao(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function G(e,t={}){let n=ao(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Wc(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return _e({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:a,suggested_retry_args:e?.suggestedRetryArgs,...t})}function eo(e,t){return!t||e.includes(t)?e:[...e,t]}var Bc=new Set(["--add","--add-json","--remove"]),Vc=new Set(["command","cmd","path"]);function Jc(e){if(Array.isArray(e))for(let t of e){if(!t.startsWith("--"))continue;let n=t.indexOf("="),o=n>=0?t.slice(0,n):t;if(Bc.has(o))return o}}function Kc(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let i=e[o];if(i!=="--add"&&i!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!Vc.has(a))return;let r=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;r.push(d)}if(r.length<2)return;let s=`${a}=${r.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+r.length)];return _(c)}}function Yc(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let a=zc(i[1]),r=a.startsWith("--type"),s=o?.suggestedRetryCommand,c=ao(o?.providedOptionFlags),l=[a],d=Gc(t,a,n),m=s?eo(d,s):d,p=r?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?eo(p,`Replay with preserved arguments: ${s}`):p,f=c&&c.length>0?eo(u,`Already provided options: ${c.join(", ")}`):u;return C({code:"missing_required_option",title:`Missing required option ${a}`,happened:`Commander rejected the command because ${a} was not provided.`,required:`Pass ${a} with a valid value before running the command.`,why:r?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:G(o,{missing:l})})}function Xc(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let i=o[1];return C({code:"missing_required_argument",title:`Missing required argument ${i}`,happened:`Command invocation omitted positional argument ${i}.`,required:`Provide ${i} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:G(n,{missing:[i]})})}function Zc(e,t,n){return C({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:G(t,{suggested_flags:n})})}var Qc={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function ed(e){let t=ye(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function td(e,t,n,o,i){let a=o.otherCommands.slice(0,3),r=o.candidateTotal-a.length,s=r>0?` and ${String(r)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i?void 0:nd(e,t),a.length?`${e} is accepted by ${a.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,zr(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,i?`Replay with suggested correction: ${i}`:void 0].filter(c=>typeof c=="string")}var Gr=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function nd(e,t){if(t===void 0||!Gr.includes(e.split("=",1)[0]))return;let n=or(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${ir(n)}.`}function od(e,t,n){let o=ar(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:_(o),suggestedRetryArgs:o}:[...Gr,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function zr(e){return/\s/u.test(e)}function id(e,t){let n=e?.indexOf(t)??-1;if(e===void 0||n<0||e.includes("--")||e.lastIndexOf(t)!==n)return{};if(e.slice(n+1).some(i=>!i.startsWith("-")))return{};let o=[...L(e.filter((i,a)=>a!==n)),"--",t];return{retryCommand:_(o),suggestedRetryArgs:o}}function ad(e,t,n){if(zr(t))return id(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=od(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(rr(t))return{};let i=e.normalizedInvocationArgs;if(i===void 0)return{};if(i.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let a=i.findIndex(s=>s===t||s.startsWith(`${t}=`));if(a<0||i.includes("--")||!i[a]?.includes("=")&&a!==i.length-1&&i[a+1]?.startsWith("-")!==!0)return{};let r=L(i.filter((s,c)=>c!==a));return{retryCommand:_(r),suggestedRetryArgs:r}}function rd(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},a=o[1],r=ao(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:c}=ad(i,a,t);if(t==="update"&&(a==="--file"||a==="--doc"))return Zc(a,n,r);let l=ed(i),d=td(a,t,r,l,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(a.split("=",1)[0])&&d.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${V(t)?.canonical??t} --help`:"pm --help --all"].filter(p=>typeof p=="string");return C({code:"unknown_option",title:`Unknown option ${a}`,happened:`Commander does not recognize option ${a} for this command path.`,required:Qc[l.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:a,value:a,examples:m,nextSteps:d,recovery:G(n,{suggested_flags:r.length>0?r:void 0,suggested_retry:s,suggested_retry_args:c,candidate_commands:l.otherCommands,candidate_commands_total:l.candidateTotal||void 0,candidate_commands_truncated:i.unknownOptionOtherCommandsTruncated,option_scope:l.optionScope})})}function sd(e,t,n,o,i){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,r=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return C({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:Fr([t.installCommand,...n]),nextSteps:Fr([a,...r]),recovery:G(i)})}function ld(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=ye(t?.unknownCommandExamples),a=ye(t?.unknownCommandNextSteps),r=rc(o),s=i??["pm --help"],c=a??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=r?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return r&&(!d||!l.has(d))?sd(o,r,s,c,t):C({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:G(t)})}function cd(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ye(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let i=e?.suggestedRetryCommand;return C({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...i?[i]:[],`pm ${V(t)?.canonical??t} --help`],nextSteps:i?[`Retry with the declared hyphenated action: ${i}`]:["Choose one value from recovery.allowed_values."],recovery:G(e,{allowed_values:o,suggested_retry:i})})}function dd(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=Jc(o);if(!i)return null;let a=Kc(o);return C({code:"linked_test_value_not_quoted",title:`Linked-test ${i} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${i} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${i} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...a?[a]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...a?[`Replay with the value re-joined into one argument: ${a}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:G(n,a?{suggested_retry:a}:{})})}var md=new Set(["comments","docs","files","learnings","notes","test"]);function pd(e,t,n){if(!/too many arguments/i.test(e))return null;let o=xi(t,n?.normalizedInvocationArgs??[]);if(!o)return null;let i=o.retryArgs?_(o.retryArgs):void 0,a=_(o.templateArgs??["test",o.itemId,"--add",`command=<actual command>,${o.value}`]);return C({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:i?`Retry the explicit collection mutation: ${i}`:`Supply the actual command and its metadata together, for example ${a}.`,examples:[i??a],recovery:G(n,{suggested_retry:i,suggested_retry_args:o.retryArgs})})}function ud(e,t,n){if(!/too many arguments/i.test(e)||!md.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>l===t),a=o[i+1],r=o[i+2],s=n?.verifiedCollectionItemId?.trim();if(a?.toLowerCase()!=="add"||!r||r.startsWith("-")||!s||s.toLowerCase()!==r.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return C({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:G(n,{parsed_positionals:[{role:"transposed_subcommand",value:a},{role:"item_id",value:s}],suggested_retry:c})})}var fd=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),Lr=new Set(["context","ctx"]);function gd(e,t,n){if(!/too many arguments/i.test(e)||!Lr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>Lr.has(l)),a=i===-1?1:i+1,r=e.match(/got \d+:\s*(\S+)/i),s=r?r[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(a)){if(l){l=!1;continue}let m=d.split("=")[0];if(fd.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return C({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:G(n,{suggested_retry:c})})}function ro(e,t,n,o){let i=Dt(e);return(Yc(i,t,n,o)??Xc(i,t,o)??rd(i,t,o)??ld(i,o)??cd(o)??ud(i,t,o)??dd(i,t,o)??pd(i,t,o)??gd(i,t,o))||C({code:"invalid_command_usage",title:"Invalid command usage",happened:i,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:G(o)})}function Wr(e,t,n={}){let o=io(e,t);return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&o.title==="Tracker is not initialized"&&o.recovery?.suggested_retry_args?[`Error: ${o.title}`,`Run: ${_(o.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
12
+ `):Br(o,n)}function Br(e,t){let n=a=>Gi(wc(e,a),e.required).output,o=n(t);if(t.lean!==!0)return o;let i=n({});return Buffer.byteLength(i,"utf8")<Buffer.byteLength(o,"utf8")?i:o}function Vr(e,t){return oo(io(e,t))}function so(e,t,n){return no(io(e,n),t)}function Jr(e,t,n,o,i={}){let a=ro(e,t,n,o);return Br(a,i)}function lo(e,t,n,o){return oo(ro(e,t,n,o))}function Mt(e,t,n,o,i){return no(ro(e,t,n,i),o)}function Kr(e,t){let n=Yr(e);return no(n,t)}function Yr(e){let t=Dt(e);return Ac(t)?C({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):C({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function Xr(e){return oo(Yr(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]="4647d40c-70a2-5ffe-a91f-d43e9c522114")}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]="e860a827-39e1-5d6c-b76e-0d77365ba202")}catch{}})();var Ze=vi.join("|"),hd={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},yd={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}},Zr=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function _d(e,t){let n=yd[e];if(!n)return[];let o=W(t);for(let[i,a]of Object.entries(n))if(W(i)===o)return a;return[]}function co(e,t,n){if(n.length===0)return e;if(t){let r=n.find(d=>d.declared_command_match===!0),{token_accounting:s,...c}=JSON.parse(e),l={...c,...r?{extension_command_failure:{code:"extension_command_activation_failed",extension:r.name,layer:r.layer,error:r.error,recovery_commands:r.recovery_commands??[]}}:{},failed_extensions:n};return JSON.stringify(s===void 0?l:X(l,d=>`${JSON.stringify(d,null,2)}
13
13
  `),null,2)}let o=n.map(r=>`- ${r.layer}:${r.name}: ${r.error}`).join(`
14
14
  `),i=n.find(r=>r.declared_command_match===!0);if(!i)return`${e}
15
15
  Extension activation failures:
@@ -21,24 +21,24 @@ ${a}`:""}
21
21
 
22
22
  ${e}
23
23
  Extension activation failures:
24
- ${o}`}function lo(e){return T(e).commandPathTokens[0]??k(e)??"<command>"}function Xr(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let i=o.shift();if(!i)continue;let a=j(E(i)),r=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!r&&n.add(a),o.push(...i.commands)}for(let i of t.keys()){let a=j(i),r=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!r&&n.add(a)}return[...n].sort((i,a)=>i.localeCompare(a))}function Vr(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" ");if(n===o)return 0;if(i.includes(o))return 1;if(i.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let a=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let s of i){let c=sn(s,o,a);c!==null&&(r=Math.min(r,c))}return Number.isFinite(r)?4+r:Number.POSITIVE_INFINITY}function Jr(e){return z(e).slice(2).replace(/-/g,"")}function co(e){return _(e)}function cd(e){let t=B(e)?.canonical??nn[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=rd[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function Kr(e){let t=Ja(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function dd(e,t){let n=Kr(e);if(n.length===0)return[];let o=[];for(let i of t.values()){let a=new Set,r=i.source;if(r)for(let s of[r.name,r.package]){let c=Kr(s??"");c.length>0&&a.add(c)}a.size!==0&&[...a].some(s=>s===n||s.includes(n)||n.includes(s))&&o.push(i.command)}return[...new Set(o)].sort((i,a)=>i.localeCompare(a))}function Ze(e,t){let n=new Set,o=t??V(e);for(let i of o){i.flag.startsWith("--")&&n.add(z(i.flag));for(let a of i.aliases??[])a.startsWith("--")&&n.add(z(a))}return[...n].sort((i,a)=>i.localeCompare(a))}function md(e,t){if(!e.startsWith("--"))return[];let n=Jr(e);if(n.length===0)return[];let o=n.length>=8?2:1,i=[];for(let a of t){let r=Jr(a);if(r===n)continue;if(n.length>=3&&r.startsWith(n)){i.push({flag:a,rank:0,distance:r.length-n.length});continue}let s=sn(n,r,o);s===null||s<=0||i.push({flag:a,rank:1,distance:s})}return i.sort((a,r)=>a.rank!==r.rank?a.rank-r.rank:a.distance!==r.distance?a.distance-r.distance:a.flag.localeCompare(r.flag)).map(a=>a.flag).slice(0,3)}var Mt,pd=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function ud(){if(Mt)return Mt;let e=new Map;for(let t of Le)if(!pd.has(t))for(let n of Ze(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return Mt=e,Mt}function fd(e,t){if(!e.startsWith("--"))return[];let n=ud().get(z(e));if(!n)return[];let o=t?.trim().toLowerCase(),i=new Set(Ze(o));return[...new Set(n.filter(a=>a!==o).map(a=>({command:a,sharedFlagCount:Ze(a).filter(r=>i.has(r)).length})).sort((a,r)=>a.sharedFlagCount!==r.sharedFlagCount?r.sharedFlagCount-a.sharedFlagCount:a.command.localeCompare(r.command)).map(({command:a})=>B(a)?.canonical??a))]}function gd(e,t,n){for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--"))continue;let a=i.indexOf("="),r=a>=0?i.slice(0,a):i;if(z(r)!==z(t))continue;let s=[...e];return s[o]=a>=0?`${n}${i.slice(a)}`:n,s}}function hd(e){let t=new Set(e.commandPaths),n=a=>Math.min(Vr(a,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Vr(a,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,i=(a,r)=>{if(!Number.isFinite(r)||!t.has(a))return;let s=o.get(a);(s===void 0||r<s)&&o.set(a,r)};for(let a of e.commandPaths)i(a,n(a));for(let[a,r]of Object.entries(nn))a!=="read"&&i(r,n(a));return[...o.entries()].sort(([a,r],[s,c])=>r!==c?r-c:a.localeCompare(s)).map(([a])=>a)}function yd(e){let t=B(e.normalizedUnknown),n=rr(e.commandPaths,e.primaryToken),o=hd(e),i=dd(e.primaryToken,e.extensionDescriptors).filter(a=>e.commandPaths.includes(a));return Fn([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...i],e.commandPaths,e.primaryToken).filter(a=>!e.normalizedUnknown.includes(" ")||a!==e.normalizedUnknown)}function _d(e){return[...new Set(e.map(t=>t.split(" ")[0]).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function vd(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help --all"])]:[...new Set(["pm --help --all",...n])]}function wd(e,t,n){let o=L([...t]),i=[];for(;o!==void 0;){if(i.push(t[o]),t[o]===e)return i.join(" ");if(!n.includes(i.join(" ")))return e;let a=L(t.slice(o+1));o=a===void 0?void 0:o+1+a}return e}function Yr(e,t){if(!e)return;let n=P([...t]);return[...xe(n),...e.split(" "),"--help"]}function mo(e,t,n,o=[]){let i=e.match(/unknown command '([^']+)'/i);if(!i||typeof i[1]!="string")return;let a=Xr(t,n),r=wd(i[1],o,a),s=j(r);if(s.length===0||a.length===0)return;let c=Za(s,a);if(c){let x=Yr("update",o),S=x.slice(0,-2);return{suggestedRetryCommand:_(x),suggestedRetryArgs:x,unknownCommandExamples:[_(x),...c.examples.map(I=>_([...S,...I]))],unknownCommandNextSteps:c.nextSteps}}let l=cd(s);if(l&&!a.includes(l.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[l.installCommand,`pm ${l.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${l.packageAlias}" package. Install it with: ${l.installCommand}. Command after installation: pm ${l.canonicalPath}.`],suggestedRetryCommand:l.installCommand};let d=s.split(" ")[0],m=yd({commandPaths:a,normalizedUnknown:s,primaryToken:d,extensionDescriptors:n}),p=_d(a),u=ar(s,a),f=Yr(u,o),h=[...new Set([...u?[u]:[],...m.length>0?m:Fn(p,a)])].slice(0,3),y=vd(h,m.length>0),D=m.length>0?`Did you mean: ${h.join(", ")}?`:null;return{...f?{suggestedRetryCommand:_(f),suggestedRetryArgs:f}:{},unknownCommandExamples:f?[_(f),...y.slice(1)]:y,unknownCommandNextSteps:[...D?[D]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...D?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function bd(e){return Array.from(new Set(e))}function Cd(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
25
- `||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function xd(e){let t=e.length;for(;t>0;){let n=e[t-1];if(n!==","&&n!==":"&&n!==";")break;t-=1}return e.slice(0,t)}function kd(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(i=>i.trim().toLowerCase()===n))}function Oe(e,t){if(t.length===0)return!0;let n=e;for(let[o,i]of t.entries()){let a=kd(n,i);if(!a){let r=n.registeredArguments;return r.length>0&&(n.commands.length===0||r[0]?.required===!0)&&(r.at(-1)?.variadic===!0||t.length-o<=r.length)}n=a}return!0}async function Ed(e,t,n,o){try{let i=O(process.cwd(),e.path);if(!await K(Y(i)))return{allowedTypes:Xe};let a=await N(i),r=e.noExtensions?void 0:le(),s=se(a,r),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let l=n.findIndex(m=>m===o),d=n[l+2];if(n[l+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{c=(await vt(i,d,a.id_prefix,a.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Xe,pmRoot:i,settings:a,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:Xe}}}function Sd(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?bd([...ld(t,n[1]),...md(n[1],Ze(t))]).filter(r=>or(n[1],r)):void 0,i=n?fd(n[1],t):[],a=n!==null&&Ze(t).includes(z(n[1]));return{match:n,suggestions:o,otherCommands:i,scope:a?"declared_on_path":i.length>0?"declared_elsewhere":"declared_nowhere"}}function Ad(e,t,n){if(!t||!n||n.length===0)return;let o=gd(e,t[1],n[0]);return o?co(o):void 0}function Rd(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?xd(Cd(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let i=k(t);if(i)return ir(t,i,[o])}function Td(e,t){if(!/too many arguments/i.test(e))return;let n=L(t),o=W(t.slice(n));if(o?.alias!=="schema")return;let i=n+o.canonical_argv.length-1,a=t[i+1]?.trim().toLowerCase(),r=t[i+2]?.trim().toLowerCase();if(!a||!r)return;let s=`${a}-${r}`;if(!Br.includes(s))return;let c=[...t.slice(0,i+1),s,...t.slice(i+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${a} ${r}`,unknownSubcommandAllowedValues:[...Br],suggestedRetryCommand:co(c)}}function Od(e,t,n,o){let i=L(t),a=W(t.slice(i))?.alias??k(t);if(!/unknown option /i.test(e)||a===void 0)return a;let r=B(a)?.canonical??a;return Le.some(s=>s===a)||Xr(n,o).includes(r)?a:void 0}async function Qe(e,t,n,o={},i=process.argv.slice(2)){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",r=Be([...i]).argv,s=P(r),c=Od(a,r,t,n),l=co(r),d=Q(r),m=await Ed(s,a,r,c),p=m.allowedTypes,u=mo(a,t,n,r),f=Sd(a,c),h=Td(a,r),y=h?.suggestedRetryCommand??Ad(r,f.match,f.suggestions)??Rd(a,r);return{message:a,commandName:c,allowedTypes:p,attemptedCommand:l,normalizedInvocationArgs:[...r],providedOptionFlags:d,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,unknownOptionScope:f.scope,suggestedRetryCommand:y,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function po(e,t,n,o={},i=process.argv.slice(2)){let a=await Qe(e,t,n,o,i),{message:r,commandName:s,allowedTypes:c,...l}=a,d=P(a.normalizedInvocationArgs).lean,m=Hr(r,s,c,l,{lean:d}),p=await Fi("help_format",{message:m,command:s,allowed_types:c});return p.handled&&typeof p.result=="string"?p.result:m}async function uo(e,t,n,o=!1,i={},a=process.argv.slice(2)){let r=await Qe(e,t,n,i,a),s=Dt(r.message,r.commandName,r.allowedTypes,g.USAGE,r),c=o?Pt(s):s,l=P(r.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(l?X(c,d=>`${JSON.stringify(d,null,2)}
26
- `):c,null,2)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e57ce782-5c73-5c74-a929-0971a990a355")}catch{}})();async function Zr(e,t,n,o){if(n)return null;let i=e.some(r=>r==="--for"||r.startsWith("--for=")),a=k(e)==="contracts"&&e.includes("--full");return i||a?await o(t):null}import{Option as Id}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c1ac468b-d5b1-5b12-9e4c-3dad7fafd585")}catch{}})();function w(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function es(e,t){let n=new Map;for(let o of e){let i=w(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let r=w(a.command),s=r.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&i===d){n.set(i,r);break}}}return n}function fo(e,t,n,o){if(!t||!n)return;let i,a=0;for(let[s,c]of e.entries()){if(c!==t)continue;let l=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>a&&p.every((u,f)=>l[f]===u)&&(i=m,a=p.length)}}let r=i?.flags.find(s=>s.long===n||s.short===n);if(r)return Pd(r).takesValue}function Ft(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Nt(e){return typeof e=="boolean"?e:void 0}function Pd(e){let t=ut(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function $d(e){let t=Ue(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=go(e);return n?`${n} ${ho(e)}`:null}function ts(e){let t=[...new Set(e.map($d).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
24
+ ${o}`}function mo(e){return O(e).commandPathTokens[0]??k(e)??"<command>"}function os(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let i=o.shift();if(!i)continue;let a=j(E(i)),r=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!r&&n.add(a),o.push(...i.commands)}for(let i of t.keys()){let a=j(i),r=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!r&&n.add(a)}return[...n].sort((i,a)=>i.localeCompare(a))}function Qr(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" ");if(n===o)return 0;if(i.includes(o))return 1;if(i.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let a=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let s of i){let c=ln(s,o,a);c!==null&&(r=Math.min(r,c))}return Number.isFinite(r)?4+r:Number.POSITIVE_INFINITY}function es(e){return W(e).slice(2).replace(/-/g,"")}function po(e){return _(e)}function vd(e){let t=V(e)?.canonical??on[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=hd[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function ts(e){let t=Za(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function wd(e,t){let n=ts(e);if(n.length===0)return[];let o=[];for(let i of t.values()){let a=new Set,r=i.source;if(r)for(let s of[r.name,r.package]){let c=ts(s??"");c.length>0&&a.add(c)}a.size!==0&&[...a].some(s=>s===n||s.includes(n)||n.includes(s))&&o.push(i.command)}return[...new Set(o)].sort((i,a)=>i.localeCompare(a))}function Qe(e,t){let n=new Set,o=t??H(e);for(let i of o){i.flag.startsWith("--")&&n.add(W(i.flag));for(let a of i.aliases??[])a.startsWith("--")&&n.add(W(a))}return[...n].sort((i,a)=>i.localeCompare(a))}function bd(e,t){if(!e.startsWith("--"))return[];let n=es(e);if(n.length===0)return[];let o=n.length>=8?2:1,i=[];for(let a of t){let r=es(a);if(r===n)continue;if(n.length>=3&&r.startsWith(n)){i.push({flag:a,rank:0,distance:r.length-n.length});continue}let s=ln(n,r,o);s===null||s<=0||i.push({flag:a,rank:1,distance:s})}return i.sort((a,r)=>a.rank!==r.rank?a.rank-r.rank:a.distance!==r.distance?a.distance-r.distance:a.flag.localeCompare(r.flag)).map(a=>a.flag).slice(0,3)}var Nt,Cd=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function xd(){if(Nt)return Nt;let e=new Map;for(let t of je)if(!Cd.has(t))for(let n of Qe(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return Nt=e,Nt}function kd(e,t){if(!e.startsWith("--"))return[];let n=xd().get(W(e));if(!n)return[];let o=t?.trim().toLowerCase(),i=new Set(Qe(o));return[...new Set(n.filter(a=>a!==o).map(a=>({command:a,sharedFlagCount:Qe(a).filter(r=>i.has(r)).length})).sort((a,r)=>a.sharedFlagCount!==r.sharedFlagCount?r.sharedFlagCount-a.sharedFlagCount:a.command.localeCompare(r.command)).map(({command:a})=>V(a)?.canonical??a))]}function Ed(e,t,n){for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--"))continue;let a=i.indexOf("="),r=a>=0?i.slice(0,a):i;if(W(r)!==W(t))continue;let s=[...e];return s[o]=a>=0?`${n}${i.slice(a)}`:n,s}}function Sd(e){let t=new Set(e.commandPaths),n=a=>Math.min(Qr(a,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Qr(a,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,i=(a,r)=>{if(!Number.isFinite(r)||!t.has(a))return;let s=o.get(a);(s===void 0||r<s)&&o.set(a,r)};for(let a of e.commandPaths)i(a,n(a));for(let[a,r]of Object.entries(on))a!=="read"&&i(r,n(a));return[...o.entries()].sort(([a,r],[s,c])=>r!==c?r-c:a.localeCompare(s)).map(([a])=>a)}function Ad(e){let t=V(e.normalizedUnknown),n=dr(e.commandPaths,e.primaryToken),o=Sd(e),i=wd(e.primaryToken,e.extensionDescriptors).filter(a=>e.commandPaths.includes(a));return Ln([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...i],e.commandPaths,e.primaryToken).filter(a=>!e.normalizedUnknown.includes(" ")||a!==e.normalizedUnknown)}function Rd(e){return[...new Set(e.map(t=>t.split(" ")[0]).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Td(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help --all"])]:[...new Set(["pm --help --all",...n])]}function Od(e,t,n){let o=$([...t]),i=[];for(;o!==void 0;){if(i.push(t[o]),t[o]===e)return i.join(" ");if(!n.includes(i.join(" ")))return e;let a=$(t.slice(o+1));o=a===void 0?void 0:o+1+a}return e}function ns(e,t){if(!e)return;let n=I([...t]);return[...xe(n),...e.split(" "),"--help"]}function uo(e,t,n,o=[]){let i=e.match(/unknown command '([^']+)'/i);if(!i||typeof i[1]!="string")return;let a=os(t,n),r=Od(i[1],o,a),s=j(r);if(s.length===0||a.length===0)return;let c=nr(s,a);if(c){let x=ns("update",o),S=x.slice(0,-2);return{suggestedRetryCommand:_(x),suggestedRetryArgs:x,unknownCommandExamples:[_(x),...c.examples.map(P=>_([...S,...P]))],unknownCommandNextSteps:c.nextSteps}}let l=vd(s);if(l&&!a.includes(l.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[l.installCommand,`pm ${l.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${l.packageAlias}" package. Install it with: ${l.installCommand}. Command after installation: pm ${l.canonicalPath}.`],suggestedRetryCommand:l.installCommand};let d=s.split(" ")[0],m=Ad({commandPaths:a,normalizedUnknown:s,primaryToken:d,extensionDescriptors:n}),p=Rd(a),u=cr(s,a),f=ns(u,o),h=[...new Set([...u?[u]:[],...m.length>0?m:Ln(p,a)])].slice(0,3),y=Td(h,m.length>0),M=m.length>0?`Did you mean: ${h.join(", ")}?`:null;return{...f?{suggestedRetryCommand:_(f),suggestedRetryArgs:f}:{},unknownCommandExamples:f?[_(f),...y.slice(1)]:y,unknownCommandNextSteps:[...M?[M]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...M?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function Id(e){return Array.from(new Set(e))}function Pd(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
25
+ `||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function $d(e){let t=e.length;for(;t>0;){let n=e[t-1];if(n!==","&&n!==":"&&n!==";")break;t-=1}return e.slice(0,t)}function Dd(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(i=>i.trim().toLowerCase()===n))}function Ie(e,t){if(t.length===0)return!0;let n=e;for(let[o,i]of t.entries()){let a=Dd(n,i);if(!a){let r=n.registeredArguments;return r.length>0&&(n.commands.length===0||r[0]?.required===!0)&&(r.at(-1)?.variadic===!0||t.length-o<=r.length)}n=a}return!0}async function Md(e,t,n,o){try{let i=T(process.cwd(),e.path);if(!await K(Y(i)))return{allowedTypes:Ze};let a=await F(i),r=e.noExtensions?void 0:le(),s=se(a,r),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let l=n.findIndex(m=>m===o),d=n[l+2];if(n[l+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{c=(await wt(i,d,a.id_prefix,a.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Ze,pmRoot:i,settings:a,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:Ze}}}function Nd(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?Id([..._d(t,n[1]),...bd(n[1],Qe(t))]).filter(r=>sr(n[1],r)):void 0,i=n?kd(n[1],t):[],a=n!==null&&Qe(t).includes(W(n[1]));return{match:n,suggestions:o,otherCommands:i,scope:a?"declared_on_path":i.length>0?"declared_elsewhere":"declared_nowhere"}}function Fd(e,t,n){if(!t||!n||n.length===0)return;let o=Ed(e,t[1],n[0]);return o?po(o):void 0}function Ld(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?$d(Pd(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let i=k(t);if(i)return lr(t,i,[o])}function jd(e,t){if(!/too many arguments/i.test(e))return;let n=$(t),o=B(t.slice(n));if(o?.alias!=="schema")return;let i=n+o.canonical_argv.length-1,a=t[i+1]?.trim().toLowerCase(),r=t[i+2]?.trim().toLowerCase();if(!a||!r)return;let s=`${a}-${r}`;if(!Zr.includes(s))return;let c=[...t.slice(0,i+1),s,...t.slice(i+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${a} ${r}`,unknownSubcommandAllowedValues:[...Zr],suggestedRetryCommand:po(c)}}function Ud(e,t,n,o){let i=$(t),a=B(t.slice(i))?.alias??k(t);if(!/unknown option /i.test(e)||a===void 0)return a;let r=V(a)?.canonical??a;return je.some(s=>s===a)||os(n,o).includes(r)?a:void 0}async function et(e,t,n,o={},i=process.argv.slice(2)){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",r=Ve([...i]).argv,s=I(r),c=Ud(a,r,t,n),l=po(r),d=Q(r),m=await Md(s,a,r,c),p=m.allowedTypes,u=uo(a,t,n,r),f=Nd(a,c),h=jd(a,r),y=h?.suggestedRetryCommand??Fd(r,f.match,f.suggestions)??Ld(a,r);return{message:a,commandName:c,allowedTypes:p,attemptedCommand:l,normalizedInvocationArgs:[...r],providedOptionFlags:d,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,unknownOptionScope:f.scope,suggestedRetryCommand:y,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function fo(e,t,n,o={},i=process.argv.slice(2)){let a=await et(e,t,n,o,i),{message:r,commandName:s,allowedTypes:c,...l}=a,d=I(a.normalizedInvocationArgs).lean,m=Jr(r,s,c,l,{lean:d}),p=await ji("help_format",{message:m,command:s,allowed_types:c});return p.handled&&typeof p.result=="string"?p.result:m}async function go(e,t,n,o=!1,i={},a=process.argv.slice(2)){let r=await et(e,t,n,i,a),s=Mt(r.message,r.commandName,r.allowedTypes,g.USAGE,r),c=o?$t(s):s,l=I(r.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(l?X(c,d=>`${JSON.stringify(d,null,2)}
26
+ `):c,null,2)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e57ce782-5c73-5c74-a929-0971a990a355")}catch{}})();async function is(e,t,n,o){if(n)return null;let i=e.some(r=>r==="--for"||r.startsWith("--for=")),a=k(e)==="contracts"&&e.includes("--full");return i||a?await o(t):null}import{Option as qd}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c1ac468b-d5b1-5b12-9e4c-3dad7fafd585")}catch{}})();function w(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function rs(e,t){let n=new Map;for(let o of e){let i=w(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let r=w(a.command),s=r.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&i===d){n.set(i,r);break}}}return n}function ho(e,t,n,o){if(!t||!n)return;let i,a=0;for(let[s,c]of e.entries()){if(c!==t)continue;let l=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>a&&p.every((u,f)=>l[f]===u)&&(i=m,a=p.length)}}let r=i?.flags.find(s=>s.long===n||s.short===n);if(r)return Hd(r).takesValue}function Lt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ft(e){return typeof e=="boolean"?e:void 0}function Hd(e){let t=ft(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function Gd(e){let t=qe(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=yo(e);return n?`${n} ${_o(e)}`:null}function ss(e){let t=[...new Set(e.map(Gd).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
27
27
  Extension-provided flags:
28
28
  ${t.join(`
29
- `)}`}function ns(e){let t=new Map;for(let i of e){let a=w(i.target_command);if(a.length===0)continue;let r=t.get(a)??[];r.push(...i.flags),t.set(a,r)}let n=[...t.entries()].sort(([i],[a])=>i.localeCompare(a)),o=new Map;for(let[i,a]of n){let r=ts(a);r&&o.set(i,r)}return o}function os(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Qr(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let i=o.trim();i.length===0||n.has(i)||(n.add(i),t.push(i))}return t}function Dd(e){return Array.isArray(e)?e.map(t=>{let n=typeof t.name=="string"?t.name.trim():"";if(n.length===0)return null;let o={name:n,required:t.required===!0,variadic:t.variadic===!0};return typeof t.description=="string"&&t.description.trim().length>0&&(o.description=t.description.trim()),o}).filter(t=>t!==null):[]}function Md(e){let t=new Map;for(let n of e){let o=w(n.command);if(o.length===0)continue;let i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,a=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:os(o,n.action),description:i,intent:a,examples:Qr(n.examples),failure_hints:Qr(n.failure_hints),arguments:Dd(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",...n.read_output===void 0?{}:{read_output_declared:!0},source:{layer:n.layer,name:n.name,package:n.source_package,version:n.source_version}})}return t}function Nd(e){let t=new Map;for(let n of e){let o=w(n.target_command);if(o.length===0)continue;let i=t.get(o)??[];i.push(...n.flags),t.set(o,i)}return t}function Fd(e,t,n){let o=new Set;for(let i of e){let a=w(i);a.length>0&&o.add(a)}for(let i of t.keys())o.add(i);for(let i of n.keys())o.add(i);return o}function Ld(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function is(e,t,n,o=new Map){let i=Md(t),a=Nd(n),r=Fd(e,i,a),s=new Map,c=[...r].sort((l,d)=>l.localeCompare(d));for(let l of c){let d=Ld(l,i,o)??i.get(l),m=a.get(l)??(d?a.get(d.command):void 0)??[];if(d){s.set(l,{...d,command:l,flags:m});continue}s.set(l,{command:l,action:os(l,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function jd(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function as(e,t){for(let n of t.arguments)e.argument(jd(n),n.description??"Extension argument.")}function Ud(e){if(Nt(e.visible)===!1)return null;let t=Ue(e.long),n=Ft(e.short),o=n&&n.startsWith("-")&&!n.startsWith("--")?n:null,i=t&&t.startsWith("--")&&t.length>2?t:null,a=[o,i].filter(r=>r!==null);return a.length>0?a:null}function go(e){let t=Ud(e);if(!t)return null;let{value_name:n,value_arity:o}=ut(e),i=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${i}`}function qd(e){return go(e)}function ho(e){let t=Ft(e.description)??"Extension-provided option.",n=[];Nt(e.required)===!0&&n.push("required"),Nt(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"",i=e.default!==void 0?` (default: ${JSON.stringify(e.default)})`:"";return`${t}${o}${i}`}function rs(e,t){let n=Ue(t.long),o=Ft(t.short);return e.options.some(i=>{let a=i;return n!==null&&a.long===n||o!==null&&a.short===o})}function yo(e,t){for(let n of t){if(rs(e,n))continue;let o=qd(n);if(!o)continue;let i=ho(n),a=new Id(o,i);if(a.negate=!1,n.list!==!0){e.addOption(a);continue}e.addOption(a.argParser((r,s=[])=>[...Array.isArray(s)?s:[s],r]))}}function _o(e,t){return ts(t.filter(n=>!rs(e,n)))}function Hd(e){let t=go(e);if(!t)return null;let n=Ue(e.long),o=Ft(e.short),i=n&&n.startsWith("--")&&n.length>2?n:null,a=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=ut(e),s=Nt(e.required)===!0;return{flags:t,long:i,short:a,description:ho(e),takes_value:r.value_arity!=="none",value_required:r.value_arity==="required",value_name:r.value_name,variadic:!1,required:s,aliases:[],alias_for:null,...e.default!==void 0?{default_value:e.default}:{},owner:"extension",...Gd(St(e))}}function Gd(e){return e===null?{}:{sdk_option:e}}function vo(e){return At(e.command,xt({readOutput:e.read_output_declared===!0})).map(t=>({flags:t.takes_value?`${t.flag} <${t.value_name}>`:t.flag,long:t.flag,short:null,description:t.description,takes_value:t.takes_value,value_required:t.value_required,value_name:t.takes_value?t.value_name:null,variadic:!1,required:!1,aliases:[...t.aliases??[]],alias_for:null,owner:"host"}))}function wo(e){return["","Inherited host flags (delivered through context.global):",` ${vo(e).map(t=>t.flags).join(", ")}`,` Run pm contracts --command ${e.command} --flags-only --json for each flag's owner and sdk_option key.`].join(`
30
- `)}function ss(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let i=Hd(o);!i||n.has(i.flags)||(n.add(i.flags),t.push(i))}return t}function ls(e,t){if(t.length===0)return e;let n=new Map(e.map(o=>[o.flags,o]));for(let o of t){let i=n.get(o.flags);n.set(o.flags,i?{...i,...o.default_value!==void 0?{default_value:o.default_value}:{},...o.owner===void 0?{}:{owner:o.owner},...o.sdk_option===void 0?{}:{sdk_option:o.sdk_option}}:o)}return[...n.values()]}function cs(e){let t=[];if(e.intent&&t.push(`Intent: ${e.intent}`),e.action&&t.push(`Action contract: ${e.action}`),e.examples.length>0){t.push("Examples:");for(let n of e.examples)t.push(` - ${n}`)}if(e.failure_hints.length>0){t.push("Common failure hints:");for(let n of e.failure_hints)t.push(` - ${n}`)}return t.length===0?null:`
29
+ `)}`}function ls(e){let t=new Map;for(let i of e){let a=w(i.target_command);if(a.length===0)continue;let r=t.get(a)??[];r.push(...i.flags),t.set(a,r)}let n=[...t.entries()].sort(([i],[a])=>i.localeCompare(a)),o=new Map;for(let[i,a]of n){let r=ss(a);r&&o.set(i,r)}return o}function cs(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function as(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let i=o.trim();i.length===0||n.has(i)||(n.add(i),t.push(i))}return t}function zd(e){return Array.isArray(e)?e.map(t=>{let n=typeof t.name=="string"?t.name.trim():"";if(n.length===0)return null;let o={name:n,required:t.required===!0,variadic:t.variadic===!0};return typeof t.description=="string"&&t.description.trim().length>0&&(o.description=t.description.trim()),o}).filter(t=>t!==null):[]}function Wd(e){let t=new Map;for(let n of e){let o=w(n.command);if(o.length===0)continue;let i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,a=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:cs(o,n.action),description:i,intent:a,examples:as(n.examples),failure_hints:as(n.failure_hints),arguments:zd(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",...n.read_output===void 0?{}:{read_output_declared:!0},source:{layer:n.layer,name:n.name,package:n.source_package,version:n.source_version}})}return t}function Bd(e){let t=new Map;for(let n of e){let o=w(n.target_command);if(o.length===0)continue;let i=t.get(o)??[];i.push(...n.flags),t.set(o,i)}return t}function Vd(e,t,n){let o=new Set;for(let i of e){let a=w(i);a.length>0&&o.add(a)}for(let i of t.keys())o.add(i);for(let i of n.keys())o.add(i);return o}function Jd(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function ds(e,t,n,o=new Map){let i=Wd(t),a=Bd(n),r=Vd(e,i,a),s=new Map,c=[...r].sort((l,d)=>l.localeCompare(d));for(let l of c){let d=Jd(l,i,o)??i.get(l),m=a.get(l)??(d?a.get(d.command):void 0)??[];if(d){s.set(l,{...d,command:l,flags:m});continue}s.set(l,{command:l,action:cs(l,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function Kd(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function ms(e,t){for(let n of t.arguments)e.argument(Kd(n),n.description??"Extension argument.")}function Yd(e){if(Ft(e.visible)===!1)return null;let t=qe(e.long),n=Lt(e.short),o=n&&n.startsWith("-")&&!n.startsWith("--")?n:null,i=t&&t.startsWith("--")&&t.length>2?t:null,a=[o,i].filter(r=>r!==null);return a.length>0?a:null}function yo(e){let t=Yd(e);if(!t)return null;let{value_name:n,value_arity:o}=ft(e),i=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${i}`}function Xd(e){return yo(e)}function _o(e){let t=Lt(e.description)??"Extension-provided option.",n=[];Ft(e.required)===!0&&n.push("required"),Ft(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"",i=e.default!==void 0?` (default: ${JSON.stringify(e.default)})`:"";return`${t}${o}${i}`}function ps(e,t){let n=qe(t.long),o=Lt(t.short);return e.options.some(i=>{let a=i;return n!==null&&a.long===n||o!==null&&a.short===o})}function vo(e,t){for(let n of t){if(ps(e,n))continue;let o=Xd(n);if(!o)continue;let i=_o(n),a=new qd(o,i);if(a.negate=!1,n.list!==!0){e.addOption(a);continue}e.addOption(a.argParser((r,s=[])=>[...Array.isArray(s)?s:[s],r]))}}function wo(e,t){return ss(t.filter(n=>!ps(e,n)))}function Zd(e){let t=yo(e);if(!t)return null;let n=qe(e.long),o=Lt(e.short),i=n&&n.startsWith("--")&&n.length>2?n:null,a=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=ft(e),s=Ft(e.required)===!0;return{flags:t,long:i,short:a,description:_o(e),takes_value:r.value_arity!=="none",value_required:r.value_arity==="required",value_name:r.value_name,variadic:!1,required:s,aliases:[],alias_for:null,...e.default!==void 0?{default_value:e.default}:{},owner:"extension",...Qd(Rt(e))}}function Qd(e){return e===null?{}:{sdk_option:e}}function bo(e){return Ae(e.command,kt({readOutput:e.read_output_declared===!0})).map(t=>({flags:t.takes_value?`${t.flag} <${t.value_name}>`:t.flag,long:t.flag,short:null,description:t.description,takes_value:t.takes_value,value_required:t.value_required,value_name:t.takes_value?t.value_name:null,variadic:!1,required:!1,aliases:[...t.aliases??[]],alias_for:null,owner:"host"}))}function Co(e){return["","Inherited host flags (delivered through context.global):",` ${bo(e).map(t=>t.flags).join(", ")}`,` Run pm contracts --command ${e.command} --flags-only --json for each flag's owner and sdk_option key.`].join(`
30
+ `)}function us(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let i=Zd(o);!i||n.has(i.flags)||(n.add(i.flags),t.push(i))}return t}function fs(e,t){if(t.length===0)return e;let n=new Map(e.map(o=>[o.flags,o]));for(let o of t){let i=n.get(o.flags);n.set(o.flags,i?{...i,...o.default_value!==void 0?{default_value:o.default_value}:{},...o.owner===void 0?{}:{owner:o.owner},...o.sdk_option===void 0?{}:{sdk_option:o.sdk_option}}:o)}return[...n.values()]}function gs(e){let t=[];if(e.intent&&t.push(`Intent: ${e.intent}`),e.action&&t.push(`Action contract: ${e.action}`),e.examples.length>0){t.push("Examples:");for(let n of e.examples)t.push(` - ${n}`)}if(e.failure_hints.length>0){t.push("Common failure hints:");for(let n of e.failure_hints)t.push(` - ${n}`)}return t.length===0?null:`
31
31
  Extension command metadata:
32
32
  ${t.join(`
33
- `)}`}function bo(e){let t=e;if(typeof t.aliases=="function")return t.aliases().map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);if(typeof t.alias=="function"){let n=t.alias();if(typeof n=="string"&&n.trim().length>0)return[n.trim().toLowerCase()]}return Array.isArray(t._aliases)?t._aliases.map(n=>n.trim().toLowerCase()).filter(n=>n.length>0):[]}function et(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:bo(o).includes(n))??null}function te(e,t){let n=e;for(let o of t){let i=et(n,o);if(!i)return null;n=i}return n}var Lt=new WeakSet;function tt(e){return Lt.has(e)}function ds(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];o>0&&M.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let a=et(n,i);if(a){n=a;continue}let r=n.command(i);Lt.add(r),o<t.length-1?(r.description("Extension-provided command group."),r.action(()=>{r.help()})):r.description("Extension-provided command path."),n=r}return n}function zd(e,t){let n=t.join(" "),o=M.find(r=>n===r.canonical||n.startsWith(`${r.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let i=e,a=[];for(let r of t){let s=et(i,r);if(!s)return null;a.push(r);let c=s.commands.length>0||M.some(l=>l.canonical.startsWith(`${a.join(" ")} `));if(!Lt.has(s)&&(a.length===t.length||!c))return{core_path:a.join(" "),extension_path:t.join(" ")};i=s}return null}function Wd(e,t,n,o,i=!1){let a=t.split(" ").filter(d=>d.length>0),r=zd(e,a),s=te(e,a),c=M.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Lt.has(s)));if(!r||r.core_path===t&&s!==null&&!n.has(t)&&!i||c&&!n.has(t))return null;let l=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${r.extension_path}:core_owner=pm-cli:${r.core_path}:extension_owner=${l}`}function ms(e,t,n,o,i){return[...new Set([...t,...n.keys()])].filter(a=>a.trim().length>0).sort((a,r)=>a.localeCompare(r)).filter(a=>{let r=Wd(e,a,o,n.get(a),t.includes(a));return r?(i(r),!o.has(a)&&te(e,a.split(" "))!==null):!0})}function ps(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}import Ie 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]="4a2291ff-7618-518c-8bff-e9aa0e2f8af2")}catch{}})();async function Co(e,t={},n=[]){let o={readSettings:N,loadExtensions:He,activateExtensions:Ge,resolveImplicitPmRoot:an,...t};try{let i=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),r=await o.activateExtensions(a);return[...a.failed,...r.failed].map(s=>{let c=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(j).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(j),m=l.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...l.length>0?{declared_commands:l}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(i){return[{layer:"runtime",name:"extension-loader",error:i instanceof Error?i.message:String(i)}]}}async function us(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await Co(t,n,o),a={readSettings:N,loadExtensions:He,activateExtensions:Ge,resolveImplicitPmRoot:an,...n};try{let r=a.resolveImplicitPmRoot(process.cwd());if(Ie.resolve(r)===Ie.resolve(t))return i;let[s,c]=await Promise.all([a.readSettings(t),a.readSettings(r)]),[l,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:r,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return i;i.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Ie.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${Ie.resolve(r)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${Ie.resolve(r)}, or install the extension into the selected tracker with "pm --pm-path ${Ie.resolve(t)} install <package> --project".`})}catch{}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66076c31-6582-5188-a280-87bbb8d19548")}catch{}})();var fs={core:0,standard:1,full:2,internal:3};function gs(e,t,n=!0){let o=t.get(q(e));if(o)return o;if(!n)return;let i=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(i.length===0)return;let a=i.reduce((s,c)=>fs[c.tier]<fs[s]?c.tier:s,"internal"),r=new Set(i.map(({family:s})=>s));return{tier:a,family:r.size===1?i[0].family:"extensions"}}function hs(e,t){if(t.length===0)return e;let n=te(e,t);if(n)return n;let o=t.join(" ");if(q(o)!==o||!Le.some(i=>i===o)&&!Ra(o)&&!We(o)&&!Oe(e,t))return null;for(let i=t.length-1;i>0;i-=1){let a=te(e,t.slice(0,i));if(a)return a}return t.length===1?e:null}function Bd(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function ys(e){let t=e;if(typeof t.attributeName=="function"){let n=t.attributeName();return typeof n=="string"&&n.trim().length>0?n.trim():null}return typeof t.attributeName=="string"&&t.attributeName.trim().length>0?t.attributeName.trim():null}function Vd(e){let t=new Map;for(let n of e){let o=n,i=ys(n);if(!i||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(i)??[];a.push(o.long.trim()),t.set(i,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(i=>i.trim()).filter(i=>i.length>0))].sort((i,a)=>i.localeCompare(a)));return t}function Jd(e){return _(e)}function Kd(e){let t=e.options??[],n=Vd(t);return t.map(o=>{let i=o,a=typeof i.flags=="string"?i.flags.trim():"",r=typeof i.description=="string"?i.description.trim():"",s=ys(o),c=(s?n.get(s)??[]:[]).filter(h=>h!==i.long).map(h=>h.trim()).filter(h=>h.length>0),l=r.match(/^Alias for ([^ ]+)/i),d=l&&l[1]?l[1].trim():null,m=i.mandatory===!0||r.includes("[required]")||r.toLowerCase().includes("required;"),p=a.includes("<"),u=p||a.includes("["),f={flags:a,long:typeof i.long=="string"?i.long:null,short:typeof i.short=="string"?i.short:null,description:r,takes_value:u,value_required:p,value_name:Bd(a),variadic:i.variadic===!0,required:m,aliases:c,alias_for:d};return i.defaultValue!==void 0&&(f.default_value=i.defaultValue),f})}function Yd(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let i=o.alias_for,a=t.get(i);if(!a)continue;let r=o.long,s=new Set([...a.aliases??[],r]);a.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Xd(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(n=>{let o=typeof n.name=="function"?n.name():typeof n.name=="string"?n.name:"argument",i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():null;return{name:o.trim(),required:n.required===!0||i?.toLowerCase().startsWith("required;")===!0,variadic:n.variadic===!0,description:i}})}function Zd(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(i=>i.name()!=="help"||e.parent===null).filter(i=>!n||(fe(i)??Z(i.name()))!=="internal").map(i=>{let a=j(E(i)),r=a,s=fe(i),c=gs(a,t,s!==void 0),l=J.find(({alias:d})=>d===a);return{name:i.name().trim(),aliases:bo(i),description:i.description().trim(),tier:c?.tier??s??Z(r),family:c?.family??Rt(r),...l?{alias_for:l.canonical,alias_lifecycle:l.lifecycle,...l.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((i,a)=>i.name.localeCompare(a.name))}function Qd(e,t,n){if(!n)return t;let o=n.examples??[],i=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?i.length>0?[...i]:[...t.tips]:[],detail_mode:e}}function em(e,t,n,o,i){let a=e!==void 0&&Jn(e)===Re,r=a?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:kr(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":a?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:Qd(n,r,o),intentSource:s}}function tm(e,t){return e===void 0?null:t?.tier??Z(e)}function nm(e,t){return e===void 0?null:t?.family??Rt(e)}function om(e,t,n){if(!(t!==e||!n))return J.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:hs(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function im(e,t,n,o,i=new Map,a=!1){if(!e){let s=Xd(t),c=Zd(t,i,a),l=new Set(c.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...c,...bt.filter(({parent:d,action:m})=>d===n&&!l.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:Z(n.split(" ")[0]),family:Rt(n.split(" ")[0])}))].sort((d,m)=>d.name.localeCompare(m.name)),usage:[n,s.reduce((d,m)=>m.required?d.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let r=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:c,variadic:l,value_kind:d,polymorphic:m})=>({name:s,required:c,variadic:l,description:m?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:c})=>s!==null&&r.has(s)||c.some(l=>r.has(l))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:c,variadic:l})=>{let d=l?`${s}...`:s;return c?`<${d}>`:`[${d}]`})].join(" ")}}function am(e,t){return t!==void 0&&tt(e)?{inherited_options:vo(t)}:{}}function rm(e,t,n,o,i){let a=Vn(n),r=ie(n),s=j(E(t)),c=j(o.join(" ")),l=c.length>s.length?c:s,d=We(l),m=d?.command??s,p=m.length>0?m:void 0,u=p,f=p?i.get(q(p)):void 0,h=p?gs(p,i,fe(t)!==void 0):void 0,{narrative:y,intentSource:D}=em(p,t.description().trim(),a,f,d!==void 0),x=Yd(ls(Kd(t),ss(f))),S=im(d,t,m,x,i,r),I=om(e,t,r);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:tm(u,h),capability_family:nm(u,h),description:d?.description??t.description(),usage:S.usage,intent:d?.description??y.intent,intent_source:D,examples:d?[d.example]:y.examples,tips:d?[Ct(d.accepted_flags)]:y.tips,arguments:S.arguments,options:S.options,...am(t,f),subcommands:S.subcommands,has_subcommands:S.subcommands.length>0,...I===void 0?{}:{command_aliases:I}}}async function _s(e,t,n,o=t){let i=P(t);if(!i.json)return!1;let a=T(t);if(!a.requested)return!1;let r=hs(e,a.commandPathTokens);if(!r){if(!i.quiet){let s=`unknown command '${a.commandPathTokens.join(" ")}'`,c=mo(s,e,n,t),l=Dt(s,"help",Xe,g.USAGE,{...c,attemptedCommand:Jd(t),normalizedInvocationArgs:[...t],providedOptionFlags:Q(t)}),d=i.tokenAccounting?X(l,m=>`${JSON.stringify(m,null,2)}
33
+ `)}`}function xo(e){let t=e;if(typeof t.aliases=="function")return t.aliases().map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);if(typeof t.alias=="function"){let n=t.alias();if(typeof n=="string"&&n.trim().length>0)return[n.trim().toLowerCase()]}return Array.isArray(t._aliases)?t._aliases.map(n=>n.trim().toLowerCase()).filter(n=>n.length>0):[]}function tt(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:xo(o).includes(n))??null}function te(e,t){let n=e;for(let o of t){let i=tt(n,o);if(!i)return null;n=i}return n}var jt=new WeakSet;function nt(e){return jt.has(e)}function hs(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];o>0&&N.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let a=tt(n,i);if(a){n=a;continue}let r=n.command(i);jt.add(r),o<t.length-1?(r.description("Extension-provided command group."),r.action(()=>{r.help()})):r.description("Extension-provided command path."),n=r}return n}function em(e,t){let n=t.join(" "),o=N.find(r=>n===r.canonical||n.startsWith(`${r.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let i=e,a=[];for(let r of t){let s=tt(i,r);if(!s)return null;a.push(r);let c=s.commands.length>0||N.some(l=>l.canonical.startsWith(`${a.join(" ")} `));if(!jt.has(s)&&(a.length===t.length||!c))return{core_path:a.join(" "),extension_path:t.join(" ")};i=s}return null}function tm(e,t,n,o,i=!1){let a=t.split(" ").filter(d=>d.length>0),r=em(e,a),s=te(e,a),c=N.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||jt.has(s)));if(!r||r.core_path===t&&s!==null&&!n.has(t)&&!i||c&&!n.has(t))return null;let l=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${r.extension_path}:core_owner=pm-cli:${r.core_path}:extension_owner=${l}`}function ys(e,t,n,o,i){return[...new Set([...t,...n.keys()])].filter(a=>a.trim().length>0).sort((a,r)=>a.localeCompare(r)).filter(a=>{let r=tm(e,a,o,n.get(a),t.includes(a));return r?(i(r),!o.has(a)&&te(e,a.split(" "))!==null):!0})}function _s(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}import Pe 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]="4a2291ff-7618-518c-8bff-e9aa0e2f8af2")}catch{}})();async function ko(e,t={},n=[]){let o={readSettings:F,loadExtensions:Ge,activateExtensions:ze,resolveImplicitPmRoot:rn,...t};try{let i=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),r=await o.activateExtensions(a);return[...a.failed,...r.failed].map(s=>{let c=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(j).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(j),m=l.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...l.length>0?{declared_commands:l}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(i){return[{layer:"runtime",name:"extension-loader",error:i instanceof Error?i.message:String(i)}]}}async function vs(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await ko(t,n,o),a={readSettings:F,loadExtensions:Ge,activateExtensions:ze,resolveImplicitPmRoot:rn,...n};try{let r=a.resolveImplicitPmRoot(process.cwd());if(Pe.resolve(r)===Pe.resolve(t))return i;let[s,c]=await Promise.all([a.readSettings(t),a.readSettings(r)]),[l,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:r,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return i;i.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Pe.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${Pe.resolve(r)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${Pe.resolve(r)}, or install the extension into the selected tracker with "pm --pm-path ${Pe.resolve(t)} install <package> --project".`})}catch{}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66076c31-6582-5188-a280-87bbb8d19548")}catch{}})();var ws={core:0,standard:1,full:2,internal:3};function bs(e,t,n=!0){let o=t.get(q(e));if(o)return o;if(!n)return;let i=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(i.length===0)return;let a=i.reduce((s,c)=>ws[c.tier]<ws[s]?c.tier:s,"internal"),r=new Set(i.map(({family:s})=>s));return{tier:a,family:r.size===1?i[0].family:"extensions"}}function Cs(e,t){if(t.length===0)return e;let n=te(e,t);if(n)return n;let o=t.join(" ");if(q(o)!==o||!je.some(i=>i===o)&&!Et(o)&&!Be(o)&&!Ie(e,t))return null;for(let i=t.length-1;i>0;i-=1){let a=te(e,t.slice(0,i));if(a)return a}return t.length===1?e:null}function nm(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function xs(e){let t=e;if(typeof t.attributeName=="function"){let n=t.attributeName();return typeof n=="string"&&n.trim().length>0?n.trim():null}return typeof t.attributeName=="string"&&t.attributeName.trim().length>0?t.attributeName.trim():null}function om(e){let t=new Map;for(let n of e){let o=n,i=xs(n);if(!i||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(i)??[];a.push(o.long.trim()),t.set(i,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(i=>i.trim()).filter(i=>i.length>0))].sort((i,a)=>i.localeCompare(a)));return t}function im(e){return _(e)}function am(e){let t=e.options??[],n=om(t);return t.map(o=>{let i=o,a=typeof i.flags=="string"?i.flags.trim():"",r=typeof i.description=="string"?i.description.trim():"",s=xs(o),c=(s?n.get(s)??[]:[]).filter(h=>h!==i.long).map(h=>h.trim()).filter(h=>h.length>0),l=r.match(/^Alias for ([^ ]+)/i),d=l&&l[1]?l[1].trim():null,m=i.mandatory===!0||r.includes("[required]")||r.toLowerCase().includes("required;"),p=a.includes("<"),u=p||a.includes("["),f={flags:a,long:typeof i.long=="string"?i.long:null,short:typeof i.short=="string"?i.short:null,description:r,takes_value:u,value_required:p,value_name:nm(a),variadic:i.variadic===!0,required:m,aliases:c,alias_for:d};return i.defaultValue!==void 0&&(f.default_value=i.defaultValue),f})}function rm(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let i=o.alias_for,a=t.get(i);if(!a)continue;let r=o.long,s=new Set([...a.aliases??[],r]);a.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function sm(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(n=>{let o=typeof n.name=="function"?n.name():typeof n.name=="string"?n.name:"argument",i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():null;return{name:o.trim(),required:n.required===!0||i?.toLowerCase().startsWith("required;")===!0,variadic:n.variadic===!0,description:i}})}function lm(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(i=>i.name()!=="help"||e.parent===null).filter(i=>!n||(fe(i)??Z(i.name()))!=="internal").map(i=>{let a=j(E(i)),r=a,s=fe(i),c=bs(a,t,s!==void 0),l=J.find(({alias:d})=>d===a);return{name:i.name().trim(),aliases:xo(i),description:i.description().trim(),tier:c?.tier??s??Z(r),family:c?.family??Tt(r),...l?{alias_for:l.canonical,alias_lifecycle:l.lifecycle,...l.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((i,a)=>i.name.localeCompare(a.name))}function cm(e,t,n){if(!n)return t;let o=n.examples??[],i=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?i.length>0?[...i]:[...t.tips]:[],detail_mode:e}}function dm(e,t,n,o,i){let a=e!==void 0&&Yn(e)===Te,r=a?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Or(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":a?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:cm(n,r,o),intentSource:s}}function mm(e,t){return e===void 0?null:t?.tier??Z(e)}function pm(e,t){return e===void 0?null:t?.family??Tt(e)}function um(e,t,n){if(!(t!==e||!n))return J.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Cs(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function fm(e,t,n,o,i=new Map,a=!1){if(!e){let s=sm(t),c=lm(t,i,a),l=new Set(c.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...c,...Ct.filter(({parent:d,action:m})=>d===n&&!l.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:Z(n.split(" ")[0]),family:Tt(n.split(" ")[0])}))].sort((d,m)=>d.name.localeCompare(m.name)),usage:[n,s.reduce((d,m)=>m.required?d.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let r=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:c,variadic:l,value_kind:d,polymorphic:m})=>({name:s,required:c,variadic:l,description:m?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:c})=>s!==null&&r.has(s)||c.some(l=>r.has(l))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:c,variadic:l})=>{let d=l?`${s}...`:s;return c?`<${d}>`:`[${d}]`})].join(" ")}}function gm(e,t){return t!==void 0&&nt(e)?{inherited_options:bo(t)}:{}}function hm(e,t,n,o,i){let a=Kn(n),r=ie(n),s=j(E(t)),c=j(o.join(" ")),l=c.length>s.length?c:s,d=Be(l),m=d?.command??s,p=m.length>0?m:void 0,u=p,f=p?i.get(q(p)):void 0,h=p?bs(p,i,fe(t)!==void 0):void 0,{narrative:y,intentSource:M}=dm(p,t.description().trim(),a,f,d!==void 0),x=rm(fs(am(t),us(f))),S=fm(d,t,m,x,i,r),P=um(e,t,r);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:mm(u,h),capability_family:pm(u,h),description:d?.description??t.description(),usage:S.usage,intent:d?.description??y.intent,intent_source:M,examples:d?[d.example]:y.examples,tips:d?[xt(d.accepted_flags)]:y.tips,arguments:S.arguments,options:S.options,...gm(t,f),subcommands:S.subcommands,has_subcommands:S.subcommands.length>0,...P===void 0?{}:{command_aliases:P}}}async function ks(e,t,n,o=t){let i=I(t);if(!i.json)return!1;let a=O(t);if(!a.requested)return!1;let r=Cs(e,a.commandPathTokens);if(!r){if(!i.quiet){let s=`unknown command '${a.commandPathTokens.join(" ")}'`,c=uo(s,e,n,t),l=Mt(s,"help",Ze,g.USAGE,{...c,attemptedCommand:im(t),normalizedInvocationArgs:[...t],providedOptionFlags:Q(t)}),d=i.tokenAccounting?X(l,m=>`${JSON.stringify(m,null,2)}
34
34
  `):l;oe(`${JSON.stringify(d,null,2)}
35
- `)}return process.exitCode=g.USAGE,!0}if(!i.quiet){let s=rm(e,r,t,a.commandPathTokens,n),c=T(o).commandPathTokens;s.requested_path=c;let l=B(c.join(" "));l&&(s.resolved_path=l.canonical),r===e&&!ie(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),Ki(`${JSON.stringify(s,null,2)}
36
- `)}return process.exitCode=g.SUCCESS,!0}function sm(e,t){let n=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${t.types.join("|")}`];return e==="create"&&n.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),n.join(`
37
- `)}function lm(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",i=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${i.length>0?i.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function cm(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let i of[...t.required_create_fields,...t.required_create_repeatables])o.add(i);return{progressive:n,strict:o}}function dm(e,t,n,o){let i=new Set(n),a=o.filter(c=>!i.has(c)),r=c=>c.length>0?c.map(l=>on("create",l)).join(", "):"none";e.push(` required in strict mode: ${r(a)}`);let s=a.map(Ka).filter(c=>c!==void 0);e.push(` explicit empty assertion: ${s.length>0?s.join(", "):"none"}`),["Reminder","Meeting","Event"].includes(t.name)&&(e.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),e.push(" strict parity remains available via --create-mode strict."))}function mm(e,t,n){let o=Oa(n);if(!o)return sm(e,t);let i=_i(o,t);if(!i){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
38
- `)}let a=n.indexOf("--"),r=a<0?n:n.slice(0,a),s=r.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),c=s<0?void 0:r[s]?.startsWith("--create-mode=")?r[s]?.slice(14):r[s+1],l=e==="create"&&c?.toLowerCase()==="strict",d=cm(e,i),m=pt(i,e,d.progressive),p=pt(i,e,l?d.strict:d.progressive),u=h=>h.length>0?h.map(y=>on(e,y)).join(", "):"none",f=["",`Type-aware option policies for ${i.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=pt(i,e,d.strict);dm(f,i,m.required,h.required)}return lm(f,i),p.errors.length>0&&f.push(` config errors: ${p.errors.join("; ")}`),f.join(`
39
- `)}function vs(e,t,n){let o=k(n);if(o!=="create"&&o!=="update")return;let i=et(e,o);i&&i.addHelpText("after",mm(o,t,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]="665c29cd-2a3b-5cfc-9690-6d82541fc5d9")}catch{}})();function pm(e,t){return qe(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function um(e){return qe(e.status)?.toLowerCase()??"pending"}function fm(e){return e.mandatory===!0}function gm(e,t){let n=e.layer.localeCompare(t.layer);if(n!==0)return n;let o=e.name.localeCompare(t.name);return o!==0?o:e.id.localeCompare(t.id)}function Cs(e){let t=[];return e.forEach((n,o)=>{if(!fm(n.definition))return;let i=um(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:pm(n.definition,o),status:i})}),t.sort(gm),t}function ws(e){return Array.isArray(e)&&e.length>0}var hm=new Set(["create","beads import","todos import"]),ym=new Set(["restore","update","close","delete","append","claim","release"]),_m=new Set(["comments","notes","learnings"]),vm=new Set(["files","docs","test"]),wm=new Set(["activate","add","add-field","add-status","add-type","apply","compact","create","deactivate","delete","disable","edit","enable","import","infer","install","materialize","migrate","redact","remove","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type","repair","run","save","set","unset","update","upgrade"]);function xo(e,t){let n=t.force===!0;return hm.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:ym.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:_m.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:vm.has(e)?{isMutation:ws(t.add)||ws(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function bm(e,t,n){if(xo(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return ha(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>wm.has(i.trim().toLowerCase())):!1}function bs(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Cm(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let i=[];if(qe(t[1])||i.push("source"),qe(n.to)||i.push("--to"),i.length!==0)throw new R(`Schema migration requires ${i.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:i.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:i,suggested_flags:i.filter(a=>a.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function xm(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||bs(n.status)!==bs(i.schema.workflow.in_progress_status))return;let a=t[0];if(!a)return;let r=se(i,le()),s=await vt(o,a,i.id_prefix,i.item_format,r.type_to_folder);if(!s)return;let c=await oa(s,{schema:i.schema}),l=typeof n.assignee=="string"?n.assignee.trim():void 0;(l===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(l.toLowerCase())&&l)||b(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function ko(e,t,n,o,i){if(!bm(e,t,n)||(Cm(e,t,n),!await K(Y(i))))return;let a=await Ee(i);sr(o.json===!0)||await xm(e,t,n,i,a.settings);let r=ga({author:yt(o.author,a.settings.author_default),payload:{command:e,args:t,options:n},settings:a.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of r.warnings)pe(s)}function xs(e,t,n){if(n.length===0)return;let o=xo(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let i=n.map(r=>`extension_migration_blocking:${r.layer}:${r.name}:${r.id}:${r.status}`),a=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new R(`Write command "${e}" blocked by unresolved mandatory extension migrations (${i.join(",")}). ${a}`,g.CONFLICT)}async function Eo(e,t,n,o){if(!xo(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await K(Y(n)))return;let{settings:i,metadata:a,warnings:r}=await Ee(n);for(let s of r)pe(s);if(!Xi(i)&&(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(Yi(i),await Zi(n,i,"item_format:auto_select_default")),o.run_preflight_item_format_sync)){let s=se(i,le());await ya(n,i.item_format,"item_format:pre_mutation_sync",s.type_to_folder,i.schema)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0826cb1-5181-51b3-9ad9-0cd7a3d2c4b3")}catch{}})();function So(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=w(n);o.length!==0&&t.push(o)}return t}function $e(e){let t=w(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(i=>i.length>0);for(let i of So(e.commandArgs))o.push(...i.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,q(i)]))]}function Ao(e,t){let n=w(e);if(n.length===0)return!1;let o=$e(t);for(let i of o)if(i===n||i.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(i=>n.startsWith(`${i} `)):!1}function Ut(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...$(n.commands),...$(n.command_handlers),...$(n.command_overrides),...$(n.flag_commands),...$(n.parser_overrides),...ks(n.preflight_ownership),...ks(n.renderer_ownership)]:[]}function $(e){return e??[]}function ks(e){return $(e).flatMap(t=>t.commands)}function nt(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Es=new Set(["hooks","parser","preflight","renderers"]),Ss=new Set(["commands","schema","services","importers"]),km=new Set(["reindex","search","search-advanced"]),Em=new Set(["--template"]);function Pe(e,t){for(let n of t)if(e.has(n))return!0;return!1}function Ro(e){let t=w(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return km.has(n??t)}function To(e,t){for(let n of e.commandArgs??[]){if(!n.startsWith("--"))continue;let[o]=n.split("=",1);if(t.has(o))return!0}return!1}function qt(e){return w(e.commandPath??"")==="create"&&To(e,Em)}function Oo(e){return e.some(t=>{let n=w(t);return n==="templates"||n.startsWith("templates ")})}function jt(e,t){return e.some(n=>Ao(n,t))||qt(t)&&Oo(e)}function Io(e){return[$(e.hooks).length,(e.preflight_overrides??0)-$(e.preflight_ownership).length,$(e.item_types).length,$(e.item_fields).length,$(e.relationship_kinds).length,$(e.service_overrides).length,$(e.assurance_providers).length,$(e.renderer_overrides).length-$(e.renderer_ownership).length].some(t=>t>0)}function Po(e,t){let n=e.activation?.commands??[];if(n.length>0)return jt(n,t);let o=Ut(e);if(jt(o,t)||nt(e).has("search")&&Ro(t.commandPath))return!0;if(e.contributions)return Io(e.contributions)}function Ht(e,t){let n=Po(e,t);if(n!==void 0)return n;let o=nt(e);return!!(Pe(o,Es)||Pe(o,Ss))}function ot(e,t){return e.effective.length===0?!1:it(t)!=="all"?e.effective.some(n=>Ht(n,t)):e.effective.some(n=>{let o=nt(n);return Ut(n).length>0||Pe(o,Es)||Pe(o,Ss)||o.has("search")})}function it(e){if(w(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=$e(e).filter(o=>o.split(" ").every(i=>!i.startsWith("-"))).sort((o,i)=>i.length-o.length)[0]??w(e.commandPath??"");if(t.length===0)return"all";let n=qt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function $o(e){return it(e)==="all"?void 0:t=>Ht(t,e)}function De(e){let t=T(e);if(t.requested&&t.commandPathTokens.length>0){let[i,...a]=t.commandPathTokens;return{commandPath:i,commandArgs:a,allowCommandPrefixMatch:!0}}let n=F(e),o=n.findIndex(i=>i.trim().length>0&&!i.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Do(e){let t=e.args.map(String);if(w(E(e))==="create"){let n=e.optsWithGlobals();typeof n.template=="string"&&n.template.trim().length>0&&t.push("--template")}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8065373f-1652-563e-9b43-f21c104f0f61")}catch{}})();var Gt=Symbol.for("pm.readOutputInvocationProvenance"),Sm=new Map(me.filter(e=>e.reservation_scope==="root_only").map(e=>[St({long:e.flag}),e.flag]));function re(e,t){let n=Reflect.get(e,Gt);n!==void 0&&Reflect.set(t,Gt,n)}function Mo(e,t,n){let o=Gi(t,n);if(!o)return;let i=e;for(;i.parent;)i=i.parent;let a=i.rawArgs,r=new Set(Q(a.slice(2))),s=Hi.find(d=>d.command===o),c=Object.values(s?.dimensions??{}).flatMap(d=>d.legacy_aliases.flatMap(m=>r.has(m.flag)?[m.flag]:[])),l=Reflect.get(n,Gt);Reflect.set(n,Gt,{canonical_include_modes:l?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),re(n,e)}function Am(e){let t=e.optsWithGlobals(),n=E(e);if(q(n)===n)return t;let o=e.opts();for(let i=e.parent;i?.parent;i=i.parent)for(let a of i.options){let r=a.attributeName(),s=i.getOptionValueSource(r)==="cli";if(s&&!e.options.some(c=>c.long===a.long))throw new R(`Unknown option '${a.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:a.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(r)!=="cli"){let c=i.getOptionValue(r);e.setOptionValueWithSource(r,c,"cli")}r in o?t[r]=o[r]:delete t[r]}return t}function No(e,t,n,o){Mo(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:a,modes:r}=Bi(t,i,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),r.length===0)return;re(o,e);let s=Wi(t);for(let l of r){let d=s.get(l),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let c=a.length>0?a.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let l=e;l;l=l.parent)l.setOptionValueWithSource("outputInclude",c,"cli");Et(e,n)}function Me(e,t,n=[],o){let i={...Am(e)};re(e,i),delete i.json,delete i.quiet,delete i.path,delete i.pmPath,delete i.noExtensions,delete i.extensions,delete i.profile,delete i.pager,delete i.changedFields,delete i.fullChangedFields,delete i.idOnly,delete i.lean,delete i.tokenAccounting,delete i.outputInclude,delete i.outputLimit,delete i.outputBudget,delete i.outputFormat,delete i.outputSession,delete i.expectHash;let a=qa(t);for(let[r,s]of Object.entries(a))i[r]===void 0&&(i[r]=s);if(n.length>0){let r=$n(n),s=V(E(e)).map(d=>({long:d.flag,short:d.short,aliases:d.aliases})),c={...a};for(let d of r)i[d]!==void 0&&(c[d]=i[d]);Dn(c,[...s,...n],E(e),o);let l=Ua(i,n,a,E(e));return re(i,l),l}return i}function Ts(e,t,n){let o=$n(t.map(({long:r})=>({long:r}))),i=[...Sm].find(([r])=>e[r]!==void 0&&!o.has(r));if(i===void 0)return;let a=i[1];throw new R(`Unknown option '${a}' for extension command '${n}'. ${a} is a root-only pm flag and this command does not declare it.`,g.USAGE,{code:"unknown_option",flag:a,required:`Remove ${a}, or use it on the root command (pm --help ${a}).`,nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function at(e,t,n){let o=Je(e,t),i=[t],a=[];for(let r of n){if(r.startsWith("-"))break;i.push(r);let s=Je(e,i.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function zt(e){return e.arguments??[]}function As(e){let t=zt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Fo(e,t){if(!e)return!1;let n=w(t);return e.importers.some(o=>w(`${o.importer} import`)===n)||e.exporters.some(o=>w(`${o.exporter} export`)===n)}var Os=Symbol("pm.commandOptionTokens"),Rs=Symbol("pm.capturesOptionTokens");function Is(e){if(Reflect.get(e,Rs)===!0)return;Reflect.set(e,Rs,!0);let t=e.parseOptions.bind(e);e.parseOptions=n=>(Reflect.set(e,Os,[...n]),t(n))}function Rm(e){let t=new Map;for(let n of e.options){let o={arity:n.required?"required":n.optional?"optional":"none",key:n.attributeName(),variadic:n.variadic};for(let i of[n.short,n.long])i&&t.set(i,o)}return t}function Tm(e){let t=Reflect.get(e,"_passThroughOptions")===!0;return!t&&Reflect.get(e,"_enablePositionalOptions")!==!0?{}:{stop:{atSubcommand:n=>e.commands.some(o=>o.name()===n||o.aliases().includes(n)),atFirstUnrecognized:t}}}function Ps(e,t,n){if(t.length===0)return;let o=[];for(let a=e;a?.parent;a=a.parent)o.unshift(a);let i=[];for(let a of o){let r=Reflect.get(a,Os);if(r===void 0)continue;let s=Rm(a),c=[];for(let l=a;l;l=l.parent)c.push(l);i.push({tokens:r,optionOf:l=>s.get(l),includesLooseFlags:a===e,negativeNumbersAreValues:!c.some(l=>l.options.some(d=>d.short!==void 0&&/^-\d$/u.test(d.short))),...Tm(a)})}Ga(i,t,n)}function Lo(e,t){let n=zt(e),o=n.filter(s=>s.required).length,i=n.some(s=>s.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],r=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new R(`Missing required argument for extension command '${e.command}'. Usage: ${As(e)}${r}`,g.USAGE);if(t.length>i){let s=t.slice(i).join(" ");throw new R(`Too many arguments for extension command '${e.command}': ${s}. Usage: ${As(e)}${r}`,g.USAGE)}}function Om(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Wt(e,t){return{definitions:e,inheritedFlags:xt({readOutput:t}).map(n=>n.flag)}}function Im(e,t,n){let o=Object.keys(e).filter(a=>e[a]!==void 0).sort().map(Om);if(o.length===0)return;let{inheritedFlags:i}=Wt([],n);throw new R(`Unknown option '${o.join(", ")}' for extension command '${t}'. This command declares no flags; it accepts only the host flags ${i.join(", ")}.`,g.USAGE,{code:"unknown_option",flag:o[0],required:`Remove ${o.join(", ")}, or ask the package to declare it with api.registerFlags.`,nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function Pm(e,t,n){let o=e.read_output_declared===!0;if(n.length>0){Dn(t,n,e.command,Wt(n,o));return}Im(t,e.command,o)}function jo(e,t,n,o){e&&(Lo(e,t),Pm(e,n,o))}import{Command as $s}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0503f6e5-36d9-5afb-a17f-feef2241f984")}catch{}})();var $m=new Set(["--version","-V"]);function rt(e){let t=F(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function Ds(e){if(F(e)[0]!=="item"||!e.includes("--dry-run"))return;let t=new $s().configureOutput({writeErr:()=>{}}).exitOverride(),n=new Set;for(let i of me)for(let a of[i.flag,i.short,...i.aliases??[]]){if(a===void 0||n.has(a))continue;n.add(a);let r=i.value_name!==void 0||i.flag==="--pm-path";t.option(`${a}${r?" <value>":""}`)}try{t.parseOptions(e)}catch{}let o=t.opts();return{path:o.pmPath??o.path}}var Dm=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Uo=new Set(["activity","aggregate","context","ctx","events","get","graph","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search"]),Ms=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),Mm=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Nm=new Set(["claim","close-task","pause-task","release","start-task","test"]),ve={setup:!0,listQuery:!0,mutation:!0,operation:!0},Fm=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function st(e){return e.some(t=>$m.has(t))}function Lm(e,t){if(!M.some(o=>o.canonical_argv[0]===t))return;let n=new $s().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of At(t,V(t))){let i=o.takes_value?o.value_required?" <value>":" [value]":"";for(let a of[o.flag,o.short,...o.aliases??[]])a!==void 0&&n.option(`${a}${i}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return ve;let i=W([t,...o.operands])?.alias;if(M.some(a=>a.alias===i))return{...ve,targetCommandName:i}}catch{return ve}}function qo(e){if(st(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||T(e).requested)return ve;let t=k(e);if(!t)return ve;let n=t.trim().toLowerCase(),o=F(e),i=W(o)?.alias;return M.some(a=>a.alias===i)?{...ve,targetCommandName:i}:Lm(o,n==="ctx"?"context":n)||(Dm.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Uo.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:Ms.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Mm.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:ve)}function Ho(e){return e.length===0||T(e).requested||e.includes("--explain")&&k(e)===void 0}function Go(e,t){return rt(t)||st(t)?!1:ie(t)||T(t).requested?!0:!!k(t)}function zo(e){if(st(e))return!1;let t=k(e);return t?Fm.has(t):!1}function jm(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,i=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),a=i?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${i}${l.slice(d)}`:i:l}):e.argv,r=je(a),s=i&&n>=0?`${o}=[redacted]`:t,c=i&&e.normalizedDisplay.includes("=")?`${i}=[redacted]`:e.normalizedDisplay;return{argv:r,normalizedDisplay:c,sourceDisplay:s}}function Wo(e){let t=e.commandName;if(!t)return;let n=e.trace.find(l=>l.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(l=>l.length>0),i=o.length>0?o.join(" "):"the canonical flag",a=Ms.has(t)||Nm.has(t),r=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",c=jm({argv:e.argv,normalizedDisplay:i,normalizedTokens:o,rawFrom:n.from});throw new R(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:r,examples:[_(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:_(c.argv)}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d83c356-db56-5116-9fe7-e0c27973b36f")}catch{}})();var Um=new Set(["success","nonexistent_command","invalid_option","missing_required_option","missing_required_argument","invalid_usage","validation_failed","health_findings","validation_findings","conflict","runtime_failed","unknown_failed"]),qm=new Set(["parse","preflight","execute","unknown"]),Hm=new Set(["usage","validation","conflict","runtime","unknown"]);function we(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let i=o.trim();if(i.length>0)return i}}}function Bo(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Bt(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.trunc(o))}}function Vo(e){if(!e)return;let t=e.trim().toLowerCase();if(Um.has(t))return t}function Jo(e){if(!e)return;let t=e.trim().toLowerCase();if(qm.has(t))return t}function Ko(e){if(!e)return;let t=e.trim().toLowerCase();if(Hm.has(t))return t}function Yo(e){let t=we(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(r=>typeof r=="string"&&r.trim().length>0);if(typeof a=="string")return a.trim()}if(Bo(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let o=Bt(e,"failed");if(typeof o=="number"&&o>0)return`failed_runs:${o}`;let i=e?.run_results;if(Array.isArray(i)){let a=i.filter(r=>rn(r)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function Xo(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function Zo(){let e=rn(ce()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Bt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,i=Va(o),a=we(e,"error_code","errorCode")??Xo(i,o),r=Ko(we(e,"error_category","errorCategory"))??(i?void 0:mt(a)),s=i?void 0:Yo(e)??`command_exit_${o}`,c=Vo(we(e,"command_resolution","commandResolution"))??wt({ok:i,errorCode:a,errorCategory:r}),l=Jo(we(e,"resolution_stage","resolutionStage"))??"execute";return{ok:i,error:s,exit_code:o,error_code:a,error_category:r,command_resolution:c,resolution_stage: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]="e76e3620-29a9-5526-832f-2460349a8e91")}catch{}})();var Qo="PM_CLI_PACKAGE_ROOT",Ws=Symbol("pm.deprecatedAliasInvocation"),Kt=new Map;for(let e of J){let t=e.alias.split(" ")[0],n=Kt.get(t)??[];n.push(e),Kt.set(t,n)}for(let e of Kt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function Gm(){return Ci(import.meta.url,["../.."])}(typeof process.env[Qo]!="string"||process.env[Qo]?.trim().length===0)&&(process.env[Qo]=Gm());var Ce=null,U=null,Yt=null;function zm(e){Ce=e}function Wm(e){A=e}var lt=null,be=null,A=new Map,ri=250,Bm=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Vm=new Set(["1","true","yes","on"]),Jm=ze(()=>import("./chunks/register-setup-4VOTYLL2.js")),Km=ze(()=>import("./chunks/register-list-query-GXP77CX7.js")),Ym=ze(()=>import("./chunks/register-mutation-XJ2DROUM.js")),Xm=ze(()=>import("./chunks/register-operations-O5LERXM7.js"));function Jt(e){return _(e)}function Bs(e){let t=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!t||t.length===0)return;let n=[...new Set(t.map(o=>ue(o)??o))];return n.length>0?n:void 0}function Zm(e,t,n,o){if(n?.suggested_retry||o===Wn||o===zn||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let i=Q(t),a=new Set(i.map(m=>ue(m)??m)),r=Bs(e),s=t.find(m=>v.commands.some(p=>p.name()===m)),c=s?v.commands.find(m=>m.name()===s):void 0,l=new Set([...v.options,...c?.options??[]].flatMap(m=>m.flags.split(/[ ,|]+/).map(p=>ue(p)).filter(p=>p!==void 0))),d=r?.filter(m=>{let p=ue(m)??m;return a.has(p)?!1:l.has(p)||fo(t,s,p,A)!==void 0});return d&&d.length>0?d:void 0}function Qm(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],a=i?ue(i):void 0,r=e.find(p=>v.commands.some(u=>u.name()===p)),s=r?v.commands.find(p=>p.name()===r):void 0,c=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,l=fo(e,r,a,A),d=a?c?.isBoolean()===!0||l===!1?[a]:[a,"<value>"]:[],m=a?Jt([...e,...d]):t;return m===t?void 0:m}function ep(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let i=e[o];i!=null&&(n[o]=i)}return n}function tp(e){let t=e.existingRecovery;return{attempted_command:t?.attempted_command??e.attemptedCommand,normalized_args:t?.normalized_args??[...e.invocationArgv],provided_fields:t?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:t?.missing??e.inferredMissing,...ep(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Ns(e,t){return{...e,recovery:t}}function np(e,t){if(t===void 0)return;let n=gr(e,t.code,t.field,fr(e,t.code,t.recovery)),o=op(e),i=hr(e,t.code,t.field,n,o);return yr(e,t.code,i,o)}var Fs=" ";function op(e){let t=e.map(i=>i===""?Fs:/^--(?:pm-)?path=$/u.test(i)?`${i}${Fs}`:i),n=P(t).path;if(n!==void 0&&n.trim()!=="")return[];let o=xe({});return n!==void 0&&o.length>0?null:o}function Vs(e,t,n){let o=je(t),i=F(o),a=L(i),[r,s]=a===void 0?[]:i.slice(a,a+2),c=o.includes("--explain");e=e===void 0?void 0:aa(e);let l=np(o,e),d=l&&(r==="history-redact"||r==="history"&&s==="redact")?{...l,...l.attempted_command?{attempted_command:Jt(o)}:{},...l.normalized_args?{normalized_args:[...o]}:{},...l.suggested_retry?{suggested_retry:Jt(o)}:{},...l.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:l;if(d?.recovery_mode==="compact"&&!c)return Ns(e,d);let m=Jt(o),p=Q(o),u=Zm(n,o,d,e?.code),f=Qm(o,m,u,d),h=tp({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:f,existingRecovery:d});return Ns(e,h)}async function ct(e){let t=U;U=null,await _r(t,e);let n=Ce;if(Ce=null,!n){gt();return}let o=[],i=Mi();try{await vr({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?i?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Si(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:ce(),affected:i}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{gt()}!n.globalOptions.json&&o.length>0&&b(`[pm] warning: afterCommand hook_warnings=${G(o)}`),n.profileEnabled&&o.length>0&&b(`profile:extensions hook_warnings=${G(o)}`)}async function Js(e,t){await ca();let n=U,o=Ce,i=n?.command??o?.commandName??e,a=n??_n(o?.globalOptions??t),r=A.get(w(i))?.source;kn(i,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:a.source_context,source_context_source:a.source_context_source,pm_version:n?.pm_version??Ne,extension:r})}function Ks(e){return Vm.has((process.env[e]??"").trim().toLowerCase())}function Ys(e){return Ks("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Bm.has(Math.trunc(e))}async function Xt(e,t){return Ys(e.exit_code)?(await Js(e.command,t),fa({...e,source_context:e.source_context??_n(t).source_context}),!0):!1}async function Xs(e){let t=de(e.error),n=Wr(t);e.bootstrapGlobal.json?b(JSON.stringify(Ke(Gr(t,g.GENERIC_FAILURE)),null,2)):b(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await Js(e.attemptedCommand,e.bootstrapGlobal),En(e.error);let a=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=a.errorCategory,i=a.commandResolution,await en(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:i,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||b(`Failed to report error: ${de(a)}`)}try{await ct({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:i,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||b(`Failed to run error hooks: ${de(a)}`)}try{await Se()}catch(a){e.bootstrapGlobal.json||b(`Failed to flush error reporting: ${de(a)}`)}}var ip={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},ei=new Map;function ti(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Zs(e,t){return e.options.some(n=>n.long===t)}function Qs(e,t){return e.options.some(n=>n.short===t)}function ni(e,t,n,o){let i=t.trim();if(!i)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(Qs(e,i))return;if(o){e.option(`${i} <value>`,`${a} (repeatable)`,Pn);return}e.option(`${i} <value>`,a);return}let r=i.startsWith("--")?i:`--${i}`;if(!Zs(e,r)){if(o){e.option(`${r} <value>`,`${a} (repeatable)`,Pn);return}e.option(`${r} <value>`,a)}}async function el(e,t){let n=ip[e];if(!n)return[];let o=`${t}:${n}`,i=ei.get(o);if(i)return i;if(!await K(Y(t)))return ei.set(o,[]),[];let a=await N(t),r=(dn(a.schema).command_to_fields.get(n)??[]).flatMap(s=>[s.cli_flag,...s.cli_aliases].map(c=>({long:`--${c}`,type:ti(s.type),value_type:ti(s.type)})));return ei.set(o,r),r}async function tl(e,t){let n=P(t),o=O(process.cwd(),n.path);if(!await K(Y(o)))return;let i=be?.key===ci(o)?be.snapshot:null,a=i===null?await N(o):i.settings,r=dn(a.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let l=te(e,c.path.split(" "));if(l)for(let d of r.command_to_fields.get(c.command)??[]){let m=d.description??"";ni(l,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)ni(l,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function si(e,t,n,o,i){let a=k(n);if(!(a!=="create"&&a!=="update"))try{let r=i??await N(t),s=se(r,o);vs(e,s,n)}catch{}}function oi(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function nl(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function li(e){return e.some(t=>t==="--profile")}function ci(e){return`pm-root:${e}`}function ii(e){for(let t of e)t.startsWith("settings_read_")&&pe(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function ol(e,t){e.profile&&(b(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&b(`profile:extensions activation_warnings=${G(t.activationWarnings)}`))}function Zt(e,t,n){if(!e)return;let o=w(n.commandPath??"")||"<none>";b(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function Qt(e,t=Ee){let n=ci(e);if(be?.key===n)return be.snapshot;try{let o=Date.now(),{settings:i,warnings:a}=await t(e),r=await Ai({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:r,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return be={key:n,snapshot:s},s}catch{return be={key:n,snapshot:null},null}}async function Fe(e,t,n=N){let o=t?it(t):"all",i=nl(e,o);if(lt?.key===i)return lt.snapshot;try{let a=await n(e),r=await He({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?$o(t):void 0}),s=await Ge({...r,loaded:r.loaded}),c=[...new Set(s.commands.handlers.map(u=>w(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),l=ns(s.registrations.flags),d=es(s.commands.handlers,s.registrations.commands),m=is(c,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:a,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...r.warnings],activationWarnings:[...s.warnings],loadedCount:r.loaded.length,loadFailedCount:r.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:r.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return lt={key:i,snapshot:p},p}catch{return lt={key:i,snapshot:null},null}}async function il(e){let t=Ve(e);if(t.noExtensions){let r=O(process.cwd(),t.path);return await K(Y(r))&&ii((await Ee(r)).warnings),null}let n=O(process.cwd(),t.path),o=await Qt(n);if(!o)return null;ii(o.settingsReadWarnings);let i={commandPath:E(e),commandArgs:Do(e)};if(!ot(o.discovery,i))return Zt(t.profile,o,i),null;let a=await Fe(n,i);return a?(ol(t,a),{hooks:a.hooks,commands:a.commands,parsers:a.parsers,preflight:a.preflight,services:a.services,renderers:a.renderers,registrations:a.registrations,pmRoot:n}):null}async function di(e){let t=await Fe(e);return t?new Map(t.commandDescriptors):A}async function ap(e,t){return!e.requested||t.noExtensions||Oe(v,e.commandPathTokens)?A:di(O(process.cwd(),t.path))}async function al(e,t){return(await Aa({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function rl(e,t,n){let o=t.author;return Sa(e,Xa.forActiveExtensionHost({pmRoot:e,author:o}),o,w(n))}async function sl(e,t,n,o=[]){let i=E(e),a=Mn(e.args.map(String),o),r={...t};delete r.author;let s={...n},c=O(process.cwd(),n.path),l={args:[...a],path:n.path},d=await ht({command:i,args:a,options:r,global:s,pm_root:c});n.profile&&d.warnings.length>0&&b(`profile:extensions parser_warnings=${G(d.warnings)}`),a=d.context.args,r=d.context.options,s=d.context.global,Hn(l,{args:a,path:s.path},r),jo(A.get(w(i)),a,r,o),ke(void 0),ft({command:i,args:a,options:{...r},global:{...s},pm_root:c});let m=await cn({command:i,args:a,options:r,global:s,pm_root:c,sdk:rl(c,s,i)});if(s.profile&&m.warnings.length>0&&b(`profile:extensions command_handler_warnings=${G(m.warnings)}`),!m.handled)throw m.warnings.length>0?da(i,m):new R(`Command "${i}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),ke(m.result),m.result}var Ls=Symbol("pm.wrappedActionHandler");function rp(e,t){let n=e[e.length-1];return n instanceof ai?n:t}function js(e,t,n){e&&n.length>0&&b(`profile:extensions ${t}=${G(n)}`)}function sp(e){let t=A.get(w(e.commandPath));if(!t||!Fo(e.activeRegistrations,e.commandPath))return;let n=zt(t).length===0?Ha(e.commandArgs):Mn(e.commandArgs,e.extensionFlagDefinitions);Lo(t,n)}function lp(e,t,n){e.args=[...n],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),t.length>0&&Array.isArray(t[0])&&(t[0]=[...e.processedArgs])}function mi(e,t,n){if(!tt(e))return;let o=A.get(w(t))?.read_output_declared===!0;return Wt(n,o)}function ll(e){let t=n=>{let o=n;if(Is(n),typeof o._actionHandler=="function"&&o[Ls]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let r=rp(a,n),s=Date.now();In(r);let c=Ve(r),l=q(E(r));if(["package inventory","packages inventory","extension inventory"].includes(l))return mr(l,c.expectHash),await i.apply(this,a);let d=O(process.cwd(),c.path),m=r.args.map(String),p=le(),u=p?at(p,l,m):[],f=await el(l,d),h=mi(r,l,u),y=Me(r,m,[...u,...f],h);Ps(r,u,l),A.has(w(l))&&delete y.author,h!==void 0&&Ts(y,u,l);let D={args:[...m],path:c.path},x=await ht({command:l,args:m,options:y,global:c,pm_root:d});js(c.profile,"parser_warnings",x.warnings),m=x.context.args,y=x.context.options,re(r,y),c=x.context.global,Hn(D,{args:m,path:c.path},y),sp({activeRegistrations:p,commandPath:l,commandArgs:m,extensionFlagDefinitions:u}),c=await Ma(c),Et(r,c),lp(r,a,m),kt(r,y),ke(void 0),ft({command:l,args:m,options:{...y},global:{...c},pm_root:d});let S=await cn({command:l,args:m,options:y,global:c,pm_root:d,sdk:rl(d,c,l)});if(js(c.profile,"command_handler_warnings",S.warnings),S.handled){ke(S.result),yn(S.result,{...c,command:l,commandArgs:m,commandOptions:y,pmRoot:d}),c.profile&&b(`profile:command=${l} took_ms=${Date.now()-s}`);return}return await i.apply(this,a)},o[Ls]=!0}for(let i of n.commands)t(i)};t(e)}async function Vt(e){A=new Map,ne({overrides:[]}),e&&await si(e.rootProgram,e.pmRoot,e.invocationArgv,ki(),e.settings)}function cp(e,t,n,o){if(t?.flags&&t.flags.length>0){yo(e,t.flags);let i=_o(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);t&&tt(e)&&e.addHelpText("after",wo(t)),o&&e.addHelpText("after",o)}function dp(e,t,n,o){t&&e.addHelpText("after",t),n&&e.addHelpText("after",wo(n)),o&&e.addHelpText("after",o)}function cl(e,t,n){let o={core:0,standard:1,full:2,internal:3},i=(a,r)=>{let s=r.join(" "),c=[...n.entries()].filter(([d])=>d===s||d.startsWith(`${s} `)).map(([,d])=>d),l=c.length===0?"standard":c.reduce((d,m)=>o[m.tier]<o[d]?m.tier:d,"internal");Ot(a,l);for(let d of a.commands)i(d,[...r,d.name()])};for(let a of e.commands)t.has(a.name())||i(a,[a.name()])}async function dl(e,t){let n=P(t),o=O(process.cwd(),n.path);if(n.noExtensions){await Vt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await Qt(o),a=De(t);if(!i){await Vt();return}if(!ot(i.discovery,a)){await Vt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),Zt(li(t),i,a);return}let r=await Fe(o,a);if(!r){await Vt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}ne(r.services),A=new Map(r.commandDescriptors),await si(e,o,t,r.registrations,r.settings);let s=ms(e,r.commandHandlers,r.commandDescriptors,r.commandAliases,d=>ps(r.activationWarnings,b,d)),c=new Set(e.commands.map(d=>d.name())),l=d=>{let m=d.split(" ").filter(x=>x.length>0),p=r.commandDescriptors.get(d),u=te(e,m),f=r.commandFlagHelp.get(d),h=p?cs(p):null;if(u){cp(u,p,f,h);return}let y=ds(e,m);p?.description&&y.description(p.description);let D=f;p&&(as(y,p),p.flags.length>0&&(yo(y,p.flags),D=_o(y,p.flags)??void 0)),dp(y,D,p,h),y.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...x)=>{let S=x[x.length-1],I=S instanceof ai?S:y,dt=Ve(I),Cl=Date.now(),tn=at(r.registrations,d,I.args.map(String)),fi=Me(I,I.args.map(String),tn,mi(I,d,tn)),gi=await sl(I,fi,dt,tn);await Na(dt,gi),yn(gi,{...dt,command:d,commandArgs:I.args.map(String),commandOptions:fi,pmRoot:o}),dt.profile&&b(`profile:command=${d} took_ms=${Date.now()-Cl}`)})};for(let d of s)l(d);cl(e,c,r.commandDescriptors)}var Ne=xi(import.meta.url,["../.."])??"0.0.0",v=On(Ne);async function Us(e){if(!U)return;let t=Reflect.get(e,Ws);typeof t=="string"&&await Ya(t)}async function qs(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function Hs(e,t,n){!U||!await vn(!0)||(kn(e,t,n,{source_context:U.source_context,source_context_source:U.source_context_source}),ma(e),Yt=U)}async function en(e,t,n){let o=Yt;if(!o)return;Yt=null;let i=!1;try{let a=await N(o.global_pm_root);i=a.telemetry.enabled&&a.telemetry.installation_id===o.installation_id}catch{}await vn(i)?ua(e,t,n):pa()}async function mp(e){let t=await il(e);return ln(t?.registrations??null),t}function ml(e,t){t&&rt(t)||(e.hook("preAction",async(n,o)=>{Ce=null,U=null,Yt=null,gt(),In(o);let i=o.optsWithGlobals(),a=Ve(o),r=q(E(o)),s=o.args.map(String),c={args:[...s],path:a.path},l=Me(o,s),d={...a},m=O(process.cwd(),a.path),p=await mp(o);if(zi(r,{...l,...Fa(r,o.processedArgs),outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),No(o,r,d,l),await qs(o,void 0,()=>_a(r,d)),!p){Ce=Ri({commandName:r,commandArgs:s,commandOptions:l,globalOptions:d,pmRoot:m}),U=await Sn({command:r,pm_version:Ne,args:s,options:l,global:d,pm_root:m}),await Us(e),await Hs(r,s,l),await Eo(r,l,m,oi()),await ko(r,s,l,d,m),await qn({command:o,commandPath:r,commandArgs:s,commandOptions:l,expectHash:a.expectHash,pmRoot:m,globalOptions:d});return}Ti(p.hooks),Oi(p.commands),Ii(p.parsers),Pi(p.preflight),ne(p.services),$i(p.renderers),ln(p.registrations);let u=at(p.registrations,r,s);l=Me(o,s,u,mi(o,r,u)),No(o,r,d,l);let f=await ht({command:r,args:s,options:l,global:d,pm_root:p.pmRoot});d.profile&&f.warnings.length>0&&b(`profile:extensions parser_warnings=${G(f.warnings)}`),s=f.context.args,l=f.context.options,re(o,l),d=f.context.global;let h={args:[...s],path:d.path};kt(o,l);let y=await Ni({command:r,args:s,options:l,global:d,pm_root:p.pmRoot,decision:oi()});d.profile&&y.warnings.length>0&&b(`profile:extensions preflight_warnings=${G(y.warnings)}`),s=y.context.args,l=y.context.options,re(o,l),d=y.context.global,kt(o,l);let D=y.decision;await Eo(r,l,p.pmRoot,D),await ko(r,s,l,d,p.pmRoot),await qn({command:o,commandPath:r,commandArgs:c.args,commandOptions:l,expectHash:a.expectHash,pmRoot:p.pmRoot,rewritten:Un(c,[h,{args:s,path:d.path}]),globalOptions:{...d,path:a.path,noExtensions:a.noExtensions}});let x=D.run_extension_migrations?await qs(o,[],()=>al(p.registrations.migrations,p.pmRoot)):[];d.profile&&x.length>0&&b(`profile:extensions migration_warnings=${G(x)}`);let S=Cs(p.registrations.migrations);Ce={hooks:p.hooks,commandName:r,commandArgs:s,commandOptions:{...l},globalOptions:{...d},pmRoot:p.pmRoot,profileEnabled:!!d.profile,migrationBlockers:S},ke(void 0),ft({command:r,args:s,options:{...l},global:{...d},pm_root:p.pmRoot}),U=await Sn({command:r,pm_version:Ne,args:s,options:l,global:d,pm_root:p.pmRoot}),await Us(e),await Hs(r,s,l);let I=await Ei(p.hooks,{command:r,args:s,options:{...l},global:{...d},pm_root:p.pmRoot});d.profile&&I.length>0&&b(`profile:extensions hook_warnings=${G(I)}`),D.enforce_mandatory_migration_gate&&xs(r,l,S)}),e.hook("postAction",async()=>{let n=Zo();await en(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await ct(n),await Se()}))}ml(v);var Gs=Symbol("pmCliIdempotentTopLevelRegistration");function pl(e){let t=e;if(t[Gs])return;t[Gs]=!0;let n=e.command.bind(e);e.command=((o,...i)=>{let a=o.split(/\s+/u)[0];return e.commands.some(r=>r.name()===a||r.aliases().includes(a))?new ai(a):n(o,...i)})}async function pp(e,t){if(pl(e),t.setup){let{registerSetupCommands:n}=await Jm();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Km(),o=typeof t.targetCommandName=="string"&&Uo.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Ym();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Xm();n(e)}}function up(e){return async t=>{let n=mt(t.errorCode),o=wt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await wa({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Ne,pm_root:e.bootstrapPmRoot,error_code:t.errorCode,error_message:t.errorMessage,exit_code:t.exitCode,error_category:n,command_resolution:o,resolution_stage:t.resolutionStage}),{errorCategory:n,commandResolution:o}}}async function ul(e){if(e.bootstrapGlobal.noExtensions||rt(e.invocationArgv))return;let t=De(e.invocationArgv),n=await Qt(e.bootstrapPmRoot);if(n&&ot(n.discovery,t)){let o=await Fe(e.bootstrapPmRoot,t);fl(o);return}n&&Zt(li(e.invocationArgv),n,t),ne({overrides:[]})}function fl(e){if(!e){ne({overrides:[]});return}ne(e.services)}async function pi(e){await en(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await ct({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function gl(){await en(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await ct({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function hl(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof R)&&(Cn(e.error)||!n))return!1;let o=de(e.error),i=e.error instanceof R?e.error.exitCode:bn(t),a=e.error instanceof R||la(e.error)?e.error.context:void 0,r=Vs(a,e.invocationArgv,o),s=qr(o,r),c=Ke(e.bootstrapGlobal.lean?Pt(ao(o,i,r)):ao(o,i,r)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?X(c,u=>`${JSON.stringify(u,null,2)}
40
- `):c,null,2):jr(o,r,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?oe(`${l}
41
- `):b(l);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:i,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Xt({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:U?.source_context},e.bootstrapGlobal);return await pi({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(En(xn(e.error,o)),await Se(ri)),process.exitCode=i,!0}async function yl(e,t){let n=T(e.invocationArgv).commandPathTokens.join(" ")||lo(e.invocationArgv),o=q(n),i=`unknown command '${n}'`,a=O(process.cwd(),e.bootstrapGlobal.path),r=e.bootstrapGlobal.noExtensions?A:await di(a),s=De(e.invocationArgv),c=e.bootstrapGlobal.noExtensions?[]:await Co(a,{},$e(s)),l=await Qe({message:i},v,r,{failedExtensions:c},e.invocationArgv),d=ro(l.message,l.commandName,l.allowedTypes,{unknownCommandExamples:l.unknownCommandExamples,unknownCommandNextSteps:l.unknownCommandNextSteps,attemptedCommand:l.attemptedCommand,normalizedInvocationArgs:l.normalizedInvocationArgs,providedOptionFlags:l.providedOptionFlags,unknownOptionSuggestions:l.unknownOptionSuggestions,suggestedRetryCommand:l.suggestedRetryCommand,failedExtensions:c}),{errorCategory:m,commandResolution:p}=await e.emitTelemetryCommandError({command:o,errorCode:d.code,errorMessage:d.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),u=await Xt({command:o,error_code:d.code,error_category:m,exit_code:g.USAGE,error_message:d.detail,command_resolution:p,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await uo({message:i},v,r,e.bootstrapGlobal.lean===!0,{failedExtensions:c},e.invocationArgv):await po({message:i},v,r,{failedExtensions:c},e.invocationArgv),h=so(f,e.jsonErrors,c);await pi({errorMessage:i,exitCode:g.USAGE,classificationCode:d.code,errorCategory:m,commandResolution:p,resolutionStage:"parse"}),e.jsonErrors?oe(`${Ln(h)}
42
- `):b(h),u&&await Se(ri),process.exitCode=g.USAGE}async function _l(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let o=T(e.invocationArgv);return o.requested&&!Oe(v,o.commandPathTokens)?(await yl(e,t),!0):(await gl(),!0)}async function vl(e,t){let n=await Qe(e.error,v,A,{},e.invocationArgv),o=ro(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:i,commandResolution:a}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),r=await Xt({command:e.attemptedCommand,error_code:o.code,error_category:i,exit_code:g.USAGE,error_message:o.detail,command_resolution:a,resolution_stage:"parse",source_context:U?.source_context},e.bootstrapGlobal),s=e.jsonErrors?await uo(e.error,v,A,e.bootstrapGlobal.lean===!0,{},e.invocationArgv):await po(e.error,v,A,{},e.invocationArgv),c=await us(o.code,e.bootstrapPmRoot,{},$e(De(e.invocationArgv))),l=so(s,e.jsonErrors,c);await pi({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:i,commandResolution:a,resolutionStage:"parse"}),e.jsonErrors?oe(`${Ln(l)}
43
- `):b(l),r&&await Se(ri),process.exitCode=g.USAGE}function wl(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return typeof t=="string"&&(t==="commander.version"||t.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function bl(e){let t=e.error.code,n=String(e.error.message??"");if(!await _l(e,t,n)){if(t==="commander.version"){await gl();return}await vl(e,t)}}async function ui(e){let t=P(e.invocationArgv),n=O(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:k(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:up({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await ul({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await hl(o,wn(e.error))){if(wl(e.error)){await bl(o);return}await Xs({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}function fp(e,t,n){let o=n.requested?n.commandPathTokens:F(t),i=W(o);if(i&&!te(e,[...i.canonical_argv]))throw new zs(g.USAGE,"commander.unknownCommand",`unknown command '${i.alias}'`)}function gp(e,t){let n=L(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let r=L(t.slice(n+1));if(r===void 0)return;n+=r+1}let o=Kt.get(t[n]),i=t.slice(n).filter(r=>!["--global","--project","--local"].includes(r)),a=o?.find(r=>r.alias.split(" ").every((s,c)=>i[c]===s));a?.lifecycle==="deprecated"&&Reflect.set(e,Ws,a.alias)}function hp(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function yp(e,t){v=On(Ne),v.hook("preAction",(a,r)=>{t.configurationOnly=["item mutate","item complete"].includes(E(r))&&r.optsWithGlobals().dryRun===!0}),ml(v,e),lt=null,be=null,A=new Map,Di();let n=[...e],o,i;try{let a=Be(e);n=a.argv,gp(v,e);let r=hp(n),s=n.length===0,c=P(n);if(c.authorMissingValue)throw new R("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=La(c.author),Wo(a),i=Ta(n);let l=qo(n);await pp(v,l),Kn(v,!0),Go(v,n)?await dl(v,n):(A=new Map,ne({overrides:[]})),zo(n)&&await tl(v,n),Kn(v);let d=T(n);fp(v,n,d),Ho(n)&&Er(v,n),ll(v);let m=await ap(d,c);if(await _s(v,n,m,e))return;if(d.requested&&!Oe(v,d.commandPathTokens))throw new zs(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||ie(n)&&k(n)===void 0){v.outputHelp();return}if(rt(n)){await v.parseAsync(r);return}let p=O(process.cwd(),c.path),u=await N(p),f=await Zr(n,p,c.noExtensions,Fe);await pr(h=>Ea({pmRoot:p,packages:f?.contextIntentPackages},()=>Li({env:{...process.env,PM_PATH:p},argv:r,cwd:process.cwd()},()=>ji(u.agent_identity.harness_signals,()=>h(()=>v.parseAsync(r)),{probesEnabled:u.agent_identity?.probes_enabled}))))}catch(a){await ui({error:a,invocationArgv:n})}finally{i?.(),o?.()}}async function Cg(e=process.argv.slice(2)){let t=e;try{t=Be(e).argv}catch{}let n=Ds(t),o={configurationOnly:n!==void 0},i=()=>o.configurationOnly,a=()=>lr(P(t).json,async()=>{try{await ja(process.env,()=>yp(e,o))}catch(r){await ui({error:r,invocationArgv:[...e]})}});if(n!==void 0){let r=O(process.cwd(),P(t).path),s=O(process.cwd(),n.path),c=wi(process.cwd());await _t(r,()=>_t(s,()=>_t(c,a,i),i),i)}else await a()}var xg={activationCommandMatchesProbe:Ao,applyDynamicExtensionRootHelpVisibility:cl,bootstrapProfileEnabled:li,buildBootstrapActivationProbe:De,buildPostActionTelemetryOutcome:Zo,buildPmCliRecoveryContext:Vs,buildRuntimeExtensionDiscoverySnapshotCacheKey:ci,buildRuntimeExtensionActivationScope:it,buildRuntimeExtensionSnapshotCacheKey:nl,buildRuntimeExtensionFilterForProbe:$o,addRuntimeFieldOption:ni,collectActivationCommandCandidates:$e,collectExtensionFlagDefinitionsForCommand:Je,collectExtensionFlagDefinitionsForInvocation:at,collectLeadingCommandArgs:So,collectParsedActivationCommandArgs:Do,collectRuntimeFieldLooseFlagDefinitionsForCommand:el,commandHasLongOption:Zs,commandHasShortOption:Qs,commandPathNeedsSearchExtensions:Ro,commandPathNeedsTemplateExtensions:qt,describeUnknownError:de,defaultPreflightDecision:oi,discoveryNeedsActivationForProbe:ot,emitExtensionProfile:ol,emitExtensionSkippedProfile:Zt,emitSettingsReadWarnings:ii,ensureIdempotentTopLevelCommandRegistration:pl,enforceExplicitRetryForFlagTypos:Wo,envFlagEnabled:Ks,executeRegisteredRuntimeMigrations:al,extractCommandScopedOptions:Me,extensionActivationCommands:Ut,extensionCapabilities:nt,extensionNeedsActivationForProbe:Ht,extensionProvidesTemplatesRuntime:Oo,hasAnyCapability:Pe,hasGlobalExtensionContributions:Io,handleGenericRunPmCliError:Xs,handleRunPmCliCommanderError:bl,handleRunPmCliError:ui,handleRunPmCliHelpDisplayError:_l,handleRunPmCliKnownError:hl,handleRunPmCliCommanderUsageError:vl,handleUnknownHelpCommandError:yl,inferMissingFieldsFromErrorMessage:Bs,inferPostActionErrorCode:Xo,inferPostActionFailureMessage:Yo,invocationRequestsVersion:st,isCommanderError:Cn,loadRuntimeExtensionCommandDescriptorsForRecovery:di,loadRuntimeExtensionDiscoverySnapshot:Qt,loadRuntimeExtensionSnapshot:Fe,maybeLoadRuntimeExtensions:il,maybeAttachCreateUpdatePolicyHelpText:si,maybeLogHandledCliErrorToSentry:Xt,matchesStaticExtensionCommand:jt,normalizeTelemetryCommandResolution:Vo,normalizeTelemetryErrorCategory:Ko,normalizeTelemetryResolutionStage:Jo,normalizeThrownExitCode:bn,probeUsesAnyFlag:To,prepareExtensionServicesForRunPmCliError:ul,readRecordBoolean:Bo,readRecordNumber:Bt,readRecordString:we,recordCliReadOutputInvocationProvenance:Mo,registerDynamicExtensionCommandPaths:dl,registerRuntimeSchemaFieldFlags:tl,resolveCoreCommandRegistrationSelection:qo,resolveStaticExtensionActivationDecision:Po,resolveUnknownHelpToken:lo,readThrownExitCode:wn,runAndClearAfterCommandHooks:ct,runRequiredExtensionCommand:sl,shouldAttachRichHelpTextForInvocation:Ho,shouldLogHandledErrorToSentry:Ys,shouldRegisterDynamicExtensionPaths:Go,shouldRegisterRuntimeSchemaFlags:zo,shouldHandleRunPmCliCommanderError:wl,setActiveExtensionHookContextForTest:zm,setActiveRuntimeExtensionCommandDescriptorsForTest:Wm,setRecoveredExtensionServices:fl,toLooseFieldDefinitionType:ti,isImporterOrExporterCommandPath:Fo,validateDynamicExtensionCommandInvocation:jo,wrapProgramActionsForExtensionHandlers:ll,wrapThrownErrorForSentry:xn};export{xg as _testOnly,Cg as runPmCli};
35
+ `)}return process.exitCode=g.USAGE,!0}if(!i.quiet){let s=hm(e,r,t,a.commandPathTokens,n),c=O(o).commandPathTokens;s.requested_path=c;let l=V(c.join(" "));l&&(s.resolved_path=l.canonical),r===e&&!ie(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),Qi(`${JSON.stringify(s,null,2)}
36
+ `)}return process.exitCode=g.SUCCESS,!0}function ym(e,t){let n=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${t.types.join("|")}`];return e==="create"&&n.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),n.join(`
37
+ `)}function _m(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",i=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${i.length>0?i.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function vm(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let i of[...t.required_create_fields,...t.required_create_repeatables])o.add(i);return{progressive:n,strict:o}}function wm(e,t,n,o){let i=new Set(n),a=o.filter(c=>!i.has(c)),r=c=>c.length>0?c.map(l=>an("create",l)).join(", "):"none";e.push(` required in strict mode: ${r(a)}`);let s=a.map(Qa).filter(c=>c!==void 0);e.push(` explicit empty assertion: ${s.length>0?s.join(", "):"none"}`),["Reminder","Meeting","Event"].includes(t.name)&&(e.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),e.push(" strict parity remains available via --create-mode strict."))}function bm(e,t,n){let o=Da(n);if(!o)return ym(e,t);let i=wi(o,t);if(!i){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
38
+ `)}let a=n.indexOf("--"),r=a<0?n:n.slice(0,a),s=r.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),c=s<0?void 0:r[s]?.startsWith("--create-mode=")?r[s]?.slice(14):r[s+1],l=e==="create"&&c?.toLowerCase()==="strict",d=vm(e,i),m=ut(i,e,d.progressive),p=ut(i,e,l?d.strict:d.progressive),u=h=>h.length>0?h.map(y=>an(e,y)).join(", "):"none",f=["",`Type-aware option policies for ${i.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=ut(i,e,d.strict);wm(f,i,m.required,h.required)}return _m(f,i),p.errors.length>0&&f.push(` config errors: ${p.errors.join("; ")}`),f.join(`
39
+ `)}function Es(e,t,n){let o=k(n);if(o!=="create"&&o!=="update")return;let i=tt(e,o);i&&i.addHelpText("after",bm(o,t,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]="665c29cd-2a3b-5cfc-9690-6d82541fc5d9")}catch{}})();function Cm(e,t){return He(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function xm(e){return He(e.status)?.toLowerCase()??"pending"}function km(e){return e.mandatory===!0}function Em(e,t){let n=e.layer.localeCompare(t.layer);if(n!==0)return n;let o=e.name.localeCompare(t.name);return o!==0?o:e.id.localeCompare(t.id)}function Rs(e){let t=[];return e.forEach((n,o)=>{if(!km(n.definition))return;let i=xm(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:Cm(n.definition,o),status:i})}),t.sort(Em),t}function Ss(e){return Array.isArray(e)&&e.length>0}var Sm=new Set(["create","beads import","todos import"]),Am=new Set(["restore","update","close","delete","append","claim","release"]),Rm=new Set(["comments","notes","learnings"]),Tm=new Set(["files","docs","test"]),Om=new Set(["activate","add","add-field","add-status","add-type","apply","compact","create","deactivate","delete","disable","edit","enable","import","infer","install","materialize","migrate","redact","remove","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type","repair","run","save","set","unset","update","upgrade"]);function Eo(e,t){let n=t.force===!0;return Sm.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Am.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:Rm.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:Tm.has(e)?{isMutation:Ss(t.add)||Ss(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function Im(e,t,n){if(Eo(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return wa(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>Om.has(i.trim().toLowerCase())):!1}function As(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Pm(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let i=[];if(He(t[1])||i.push("source"),He(n.to)||i.push("--to"),i.length!==0)throw new R(`Schema migration requires ${i.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:i.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:i,suggested_flags:i.filter(a=>a.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function $m(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||As(n.status)!==As(i.schema.workflow.in_progress_status))return;let a=t[0];if(!a)return;let r=se(i,le()),s=await wt(o,a,i.id_prefix,i.item_format,r.type_to_folder);if(!s)return;let c=await sa(s,{schema:i.schema}),l=typeof n.assignee=="string"?n.assignee.trim():void 0;(l===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(l.toLowerCase())&&l)||b(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function So(e,t,n,o,i){if(!Im(e,t,n)||(Pm(e,t,n),!await K(Y(i))))return;let a=await Ee(i);mr(o.json===!0)||await $m(e,t,n,i,a.settings);let r=va({author:_t(o.author,a.settings.author_default),payload:{command:e,args:t,options:n},settings:a.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of r.warnings)pe(s)}function Ts(e,t,n){if(n.length===0)return;let o=Eo(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let i=n.map(r=>`extension_migration_blocking:${r.layer}:${r.name}:${r.id}:${r.status}`),a=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new R(`Write command "${e}" blocked by unresolved mandatory extension migrations (${i.join(",")}). ${a}`,g.CONFLICT)}async function Ao(e,t,n,o){if(!Eo(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await K(Y(n)))return;let{settings:i,metadata:a,warnings:r}=await Ee(n);for(let s of r)pe(s);if(!ta(i)&&(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(ea(i),await na(n,i,"item_format:auto_select_default")),o.run_preflight_item_format_sync)){let s=se(i,le());await ba(n,i.item_format,"item_format:pre_mutation_sync",s.type_to_folder,i.schema)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0826cb1-5181-51b3-9ad9-0cd7a3d2c4b3")}catch{}})();function Ro(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=w(n);o.length!==0&&t.push(o)}return t}function De(e){let t=w(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(i=>i.length>0);for(let i of Ro(e.commandArgs))o.push(...i.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,q(i)]))]}function To(e,t){let n=w(e);if(n.length===0)return!1;let o=De(t);for(let i of o)if(i===n||i.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(i=>n.startsWith(`${i} `)):!1}function qt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...D(n.commands),...D(n.command_handlers),...D(n.command_overrides),...D(n.flag_commands),...D(n.parser_overrides),...Os(n.preflight_ownership),...Os(n.renderer_ownership)]:[]}function D(e){return e??[]}function Os(e){return D(e).flatMap(t=>t.commands)}function ot(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Is=new Set(["hooks","parser","preflight","renderers"]),Ps=new Set(["commands","schema","services","importers"]),Dm=new Set(["reindex","search","search-advanced"]),Mm=new Set(["--template"]);function $e(e,t){for(let n of t)if(e.has(n))return!0;return!1}function Oo(e){let t=w(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Dm.has(n??t)}function Io(e,t){for(let n of e.commandArgs??[]){if(!n.startsWith("--"))continue;let[o]=n.split("=",1);if(t.has(o))return!0}return!1}function Ht(e){return w(e.commandPath??"")==="create"&&Io(e,Mm)}function Po(e){return e.some(t=>{let n=w(t);return n==="templates"||n.startsWith("templates ")})}function Ut(e,t){return e.some(n=>To(n,t))||Ht(t)&&Po(e)}function $o(e){return[D(e.hooks).length,(e.preflight_overrides??0)-D(e.preflight_ownership).length,D(e.item_types).length,D(e.item_fields).length,D(e.relationship_kinds).length,D(e.service_overrides).length,D(e.assurance_providers).length,D(e.renderer_overrides).length-D(e.renderer_ownership).length].some(t=>t>0)}function Do(e,t){let n=e.activation?.commands??[];if(n.length>0)return Ut(n,t);let o=qt(e);if(Ut(o,t)||ot(e).has("search")&&Oo(t.commandPath))return!0;if(e.contributions)return $o(e.contributions)}function Gt(e,t){let n=Do(e,t);if(n!==void 0)return n;let o=ot(e);return!!($e(o,Is)||$e(o,Ps))}function it(e,t){return e.effective.length===0?!1:at(t)!=="all"?e.effective.some(n=>Gt(n,t)):e.effective.some(n=>{let o=ot(n);return qt(n).length>0||$e(o,Is)||$e(o,Ps)||o.has("search")})}function at(e){if(w(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=De(e).filter(o=>o.split(" ").every(i=>!i.startsWith("-"))).sort((o,i)=>i.length-o.length)[0]??w(e.commandPath??"");if(t.length===0)return"all";let n=Ht(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Mo(e){return at(e)==="all"?void 0:t=>Gt(t,e)}function Me(e){let t=O(e);if(t.requested&&t.commandPathTokens.length>0){let[i,...a]=t.commandPathTokens;return{commandPath:i,commandArgs:a,allowCommandPrefixMatch:!0}}let n=L(e),o=n.findIndex(i=>i.trim().length>0&&!i.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function No(e){let t=e.args.map(String);if(w(E(e))==="create"){let n=e.optsWithGlobals();typeof n.template=="string"&&n.template.trim().length>0&&t.push("--template")}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8065373f-1652-563e-9b43-f21c104f0f61")}catch{}})();var zt=Symbol.for("pm.readOutputInvocationProvenance"),Nm=new Map(me.filter(e=>e.reservation_scope==="root_only").map(e=>[Rt({long:e.flag}),e.flag]));function re(e,t){let n=Reflect.get(e,zt);n!==void 0&&Reflect.set(t,zt,n)}function Fo(e,t,n){let o=Wi(t,n);if(!o)return;let i=e;for(;i.parent;)i=i.parent;let a=i.rawArgs,r=new Set(Q(a.slice(2))),s=zi.find(d=>d.command===o),c=Object.values(s?.dimensions??{}).flatMap(d=>d.legacy_aliases.flatMap(m=>r.has(m.flag)?[m.flag]:[])),l=Reflect.get(n,zt);Reflect.set(n,zt,{canonical_include_modes:l?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),re(n,e)}function Fm(e){let t=e.optsWithGlobals(),n=E(e);if(q(n)===n)return t;let o=e.opts();for(let i=e.parent;i?.parent;i=i.parent)for(let a of i.options){let r=a.attributeName(),s=i.getOptionValueSource(r)==="cli";if(s&&!e.options.some(c=>c.long===a.long))throw new R(`Unknown option '${a.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:a.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(r)!=="cli"){let c=i.getOptionValue(r);e.setOptionValueWithSource(r,c,"cli")}r in o?t[r]=o[r]:delete t[r]}return t}function Lo(e,t,n,o){Fo(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:a,modes:r}=Yi(t,i,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),r.length===0)return;re(o,e);let s=Ki(t);for(let l of r){let d=s.get(l),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let c=a.length>0?a.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let l=e;l;l=l.parent)l.setOptionValueWithSource("outputInclude",c,"cli");At(e,n)}function Ne(e,t,n=[],o){let i={...Fm(e)};re(e,i),delete i.json,delete i.quiet,delete i.path,delete i.pmPath,delete i.noExtensions,delete i.extensions,delete i.profile,delete i.pager,delete i.changedFields,delete i.fullChangedFields,delete i.idOnly,delete i.lean,delete i.tokenAccounting,delete i.outputInclude,delete i.outputLimit,delete i.outputBudget,delete i.outputFormat,delete i.outputSession,delete i.expectHash;let a=Wa(t);for(let[r,s]of Object.entries(a))i[r]===void 0&&(i[r]=s);if(n.length>0){let r=Dn(n),s=H(E(e)).map(d=>({long:d.flag,short:d.short,aliases:d.aliases})),c={...a};for(let d of r)i[d]!==void 0&&(c[d]=i[d]);Mn(c,[...s,...n],E(e),o);let l=za(i,n,a,E(e));return re(i,l),l}return i}function Ms(e,t,n){let o=Dn(t.map(({long:r})=>({long:r}))),i=[...Nm].find(([r])=>e[r]!==void 0&&!o.has(r));if(i===void 0)return;let a=i[1];throw new R(`Unknown option '${a}' for extension command '${n}'. ${a} is a root-only pm flag and this command does not declare it.`,g.USAGE,{code:"unknown_option",flag:a,required:`Remove ${a}, or use it on the root command (pm --help ${a}).`,nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function rt(e,t,n){let o=Ke(e,t),i=[t],a=[];for(let r of n){if(r.startsWith("-"))break;i.push(r);let s=Ke(e,i.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function Wt(e){return e.arguments??[]}function $s(e){let t=Wt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function jo(e,t){if(!e)return!1;let n=w(t);return e.importers.some(o=>w(`${o.importer} import`)===n)||e.exporters.some(o=>w(`${o.exporter} export`)===n)}var Ns=Symbol("pm.commandOptionTokens"),Ds=Symbol("pm.capturesOptionTokens");function Fs(e){if(Reflect.get(e,Ds)===!0)return;Reflect.set(e,Ds,!0);let t=e.parseOptions.bind(e);e.parseOptions=n=>(Reflect.set(e,Ns,[...n]),t(n))}function Lm(e){let t=new Map;for(let n of e.options){let o={arity:n.required?"required":n.optional?"optional":"none",key:n.attributeName(),variadic:n.variadic};for(let i of[n.short,n.long])i&&t.set(i,o)}return t}function jm(e){let t=Reflect.get(e,"_passThroughOptions")===!0;return!t&&Reflect.get(e,"_enablePositionalOptions")!==!0?{}:{stop:{atSubcommand:n=>e.commands.some(o=>o.name()===n||o.aliases().includes(n)),atFirstUnrecognized:t}}}function Ls(e,t,n){if(t.length===0)return;let o=[];for(let a=e;a?.parent;a=a.parent)o.unshift(a);let i=[];for(let a of o){let r=Reflect.get(a,Ns);if(r===void 0)continue;let s=Lm(a),c=[];for(let l=a;l;l=l.parent)c.push(l);i.push({tokens:r,optionOf:l=>s.get(l),includesLooseFlags:a===e,negativeNumbersAreValues:!c.some(l=>l.options.some(d=>d.short!==void 0&&/^-\d$/u.test(d.short))),...jm(a)})}Va(i,t,n)}function Uo(e,t){let n=Wt(e),o=n.filter(s=>s.required).length,i=n.some(s=>s.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],r=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new R(`Missing required argument for extension command '${e.command}'. Usage: ${$s(e)}${r}`,g.USAGE);if(t.length>i){let s=t.slice(i).join(" ");throw new R(`Too many arguments for extension command '${e.command}': ${s}. Usage: ${$s(e)}${r}`,g.USAGE)}}function Um(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Bt(e,t){return{definitions:e,inheritedFlags:kt({readOutput:t}).map(n=>n.flag)}}function qm(e,t,n){let o=Object.keys(e).filter(a=>e[a]!==void 0).sort().map(Um);if(o.length===0)return;let{inheritedFlags:i}=Bt([],n);throw new R(`Unknown option '${o.join(", ")}' for extension command '${t}'. This command declares no flags; it accepts only the host flags ${i.join(", ")}.`,g.USAGE,{code:"unknown_option",flag:o[0],required:`Remove ${o.join(", ")}, or ask the package to declare it with api.registerFlags.`,nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function Hm(e,t,n){let o=e.read_output_declared===!0;if(n.length>0){Mn(t,n,e.command,Bt(n,o));return}qm(t,e.command,o)}function qo(e,t,n,o){e&&(Uo(e,t),Hm(e,n,o))}import{Command as js}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0503f6e5-36d9-5afb-a17f-feef2241f984")}catch{}})();var Gm=new Set(["--version","-V"]);function st(e){let t=L(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function Us(e){if(L(e)[0]!=="item"||!e.includes("--dry-run"))return;let t=new js().configureOutput({writeErr:()=>{}}).exitOverride(),n=new Set;for(let i of me)for(let a of[i.flag,i.short,...i.aliases??[]]){if(a===void 0||n.has(a))continue;n.add(a);let r=i.value_name!==void 0||i.flag==="--pm-path";t.option(`${a}${r?" <value>":""}`)}try{t.parseOptions(e)}catch{}let o=t.opts();return{path:o.pmPath??o.path}}var zm=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Ho=new Set(["activity","aggregate","context","ctx","events","get","graph","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search"]),qs=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),Wm=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Bm=new Set(["claim","close-task","pause-task","release","start-task","test"]),ve={setup:!0,listQuery:!0,mutation:!0,operation:!0},Vm=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function lt(e){return e.some(t=>Gm.has(t))}function Jm(e,t){if(!N.some(o=>o.canonical_argv[0]===t))return;let n=new js().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of Ae(t,H(t))){let i=o.takes_value?o.value_required?" <value>":" [value]":"";for(let a of[o.flag,o.short,...o.aliases??[]])a!==void 0&&n.option(`${a}${i}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return ve;let i=B([t,...o.operands])?.alias;if(N.some(a=>a.alias===i))return{...ve,targetCommandName:i}}catch{return ve}}function Go(e){if(lt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||O(e).requested)return ve;let t=k(e);if(!t)return ve;let n=t.trim().toLowerCase(),o=L(e),i=B(o)?.alias;return N.some(a=>a.alias===i)?{...ve,targetCommandName:i}:Jm(o,n==="ctx"?"context":n)||(zm.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Ho.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:qs.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Wm.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:ve)}function zo(e){return e.length===0||O(e).requested||e.includes("--explain")&&k(e)===void 0}function Wo(e,t){return st(t)||lt(t)?!1:ie(t)||O(t).requested?!0:!!k(t)}function Bo(e){if(lt(e))return!1;let t=k(e);return t?Vm.has(t):!1}function Km(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,i=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),a=i?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${i}${l.slice(d)}`:i:l}):e.argv,r=Ue(a),s=i&&n>=0?`${o}=[redacted]`:t,c=i&&e.normalizedDisplay.includes("=")?`${i}=[redacted]`:e.normalizedDisplay;return{argv:r,normalizedDisplay:c,sourceDisplay:s}}function Vo(e){let t=e.commandName;if(!t)return;let n=e.trace.find(l=>l.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(l=>l.length>0),i=o.length>0?o.join(" "):"the canonical flag",a=qs.has(t)||Bm.has(t),r=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",c=Km({argv:e.argv,normalizedDisplay:i,normalizedTokens:o,rawFrom:n.from});throw new R(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:r,examples:[_(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:_(c.argv)}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d83c356-db56-5116-9fe7-e0c27973b36f")}catch{}})();var Ym=new Set(["success","nonexistent_command","invalid_option","missing_required_option","missing_required_argument","invalid_usage","validation_failed","health_findings","validation_findings","conflict","runtime_failed","unknown_failed"]),Xm=new Set(["parse","preflight","execute","unknown"]),Zm=new Set(["usage","validation","conflict","runtime","unknown"]);function we(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let i=o.trim();if(i.length>0)return i}}}function Jo(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Vt(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.trunc(o))}}function Ko(e){if(!e)return;let t=e.trim().toLowerCase();if(Ym.has(t))return t}function Yo(e){if(!e)return;let t=e.trim().toLowerCase();if(Xm.has(t))return t}function Xo(e){if(!e)return;let t=e.trim().toLowerCase();if(Zm.has(t))return t}function Zo(e){let t=we(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(r=>typeof r=="string"&&r.trim().length>0);if(typeof a=="string")return a.trim()}if(Jo(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let o=Vt(e,"failed");if(typeof o=="number"&&o>0)return`failed_runs:${o}`;let i=e?.run_results;if(Array.isArray(i)){let a=i.filter(r=>sn(r)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function Qo(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function ei(){let e=sn(ce()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Vt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,i=Xa(o),a=we(e,"error_code","errorCode")??Qo(i,o),r=Xo(we(e,"error_category","errorCategory"))??(i?void 0:pt(a)),s=i?void 0:Zo(e)??`command_exit_${o}`,c=Ko(we(e,"command_resolution","commandResolution"))??bt({ok:i,errorCode:a,errorCategory:r}),l=Yo(we(e,"resolution_stage","resolutionStage"))??"execute";return{ok:i,error:s,exit_code:o,error_code:a,error_category:r,command_resolution:c,resolution_stage: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]="87f0c49a-08fa-5f0d-bac3-58aaea71dc68")}catch{}})();var ti="PM_CLI_PACKAGE_ROOT",Xs=Symbol("pm.deprecatedAliasInvocation"),Yt=new Map;for(let e of J){let t=e.alias.split(" ")[0],n=Yt.get(t)??[];n.push(e),Yt.set(t,n)}for(let e of Yt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function Qm(){return ki(import.meta.url,["../.."])}(typeof process.env[ti]!="string"||process.env[ti]?.trim().length===0)&&(process.env[ti]=Qm());var Ce=null,U=null,Xt=null;function ep(e){Ce=e}function tp(e){A=e}var ct=null,be=null,A=new Map,li=250,np=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),op=new Set(["1","true","yes","on"]),ip=We(()=>import("./chunks/register-setup-LFB5ERXH.js")),ap=We(()=>import("./chunks/register-list-query-XMQYFUFI.js")),rp=We(()=>import("./chunks/register-mutation-OBVCFLDK.js")),sp=We(()=>import("./chunks/register-operations-CGNFZ6DR.js"));function Kt(e){return _(e)}function Zs(e){let t=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!t||t.length===0)return;let n=[...new Set(t.map(o=>ue(o)??o))];return n.length>0?n:void 0}function lp(e,t,n,o){if(n?.suggested_retry||o===Vn||o===Bn||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let i=Q(t),a=new Set(i.map(m=>ue(m)??m)),r=Zs(e),s=t.find(m=>v.commands.some(p=>p.name()===m)),c=s?v.commands.find(m=>m.name()===s):void 0,l=new Set([...v.options,...c?.options??[]].flatMap(m=>m.flags.split(/[ ,|]+/).map(p=>ue(p)).filter(p=>p!==void 0))),d=r?.filter(m=>{let p=ue(m)??m;return a.has(p)?!1:l.has(p)||ho(t,s,p,A)!==void 0});return d&&d.length>0?d:void 0}function cp(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],a=i?ue(i):void 0,r=e.find(p=>v.commands.some(u=>u.name()===p)),s=r?v.commands.find(p=>p.name()===r):void 0,c=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,l=ho(e,r,a,A),d=a?c?.isBoolean()===!0||l===!1?[a]:[a,"<value>"]:[],m=a?Kt([...e,...d]):t;return m===t?void 0:m}function dp(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let i=e[o];i!=null&&(n[o]=i)}return n}function mp(e){let t=e.existingRecovery;return{attempted_command:t?.attempted_command??e.attemptedCommand,normalized_args:t?.normalized_args??[...e.invocationArgv],provided_fields:t?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:t?.missing??e.inferredMissing,...dp(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Hs(e,t){return{...e,recovery:t}}function pp(e,t){if(t===void 0)return;let n=br(e,t.code,t.field,_r(e,t.code,t.recovery)),o=up(e),i=Cr(e,t.code,t.field,n,o),a=wr(e,t.code,i,o,()=>Aa(T(process.cwd(),I(e).path)));return xr(e,t.code,a,o)}var Gs=" ";function up(e){let t=e.map(i=>i===""?Gs:/^--(?:pm-)?path=$/u.test(i)?`${i}${Gs}`:i),n=I(t).path;if(n!==void 0&&n.trim()!=="")return[];let o=xe({});return n!==void 0&&o.length>0?null:o}function Qs(e,t,n){let o=Ue(t),i=L(o),a=$(i),[r,s]=a===void 0?[]:i.slice(a,a+2),c=o.includes("--explain");e=e===void 0?void 0:ca(e);let l=pp(o,e),d=l&&(r==="history-redact"||r==="history"&&s==="redact")?{...l,...l.attempted_command?{attempted_command:Kt(o)}:{},...l.normalized_args?{normalized_args:[...o]}:{},...l.suggested_retry?{suggested_retry:Kt(o)}:{},...l.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:l;if(d?.recovery_mode==="compact"&&!c)return Hs(e,d);let m=Kt(o),p=Q(o),u=lp(n,o,d,e?.code),f=cp(o,m,u,d),h=mp({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:f,existingRecovery:d});return Hs(e,h)}async function dt(e){let t=U;U=null,await kr(t,e);let n=Ce;if(Ce=null,!n){ht();return}let o=[],i=Fi();try{await Er({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?i?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Ri(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:ce(),affected:i}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{ht()}!n.globalOptions.json&&o.length>0&&b(`[pm] warning: afterCommand hook_warnings=${z(o)}`),n.profileEnabled&&o.length>0&&b(`profile:extensions hook_warnings=${z(o)}`)}async function el(e,t){await ua();let n=U,o=Ce,i=n?.command??o?.commandName??e,a=n??vn(o?.globalOptions??t),r=A.get(w(i))?.source;En(i,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:a.source_context,source_context_source:a.source_context_source,pm_version:n?.pm_version??Fe,extension:r})}function tl(e){return op.has((process.env[e]??"").trim().toLowerCase())}function nl(e){return tl("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!np.has(Math.trunc(e))}async function Zt(e,t){return nl(e.exit_code)?(await el(e.command,t),_a({...e,source_context:e.source_context??vn(t).source_context}),!0):!1}async function ol(e){let t=de(e.error),n=Xr(t);e.bootstrapGlobal.json?b(JSON.stringify(Ye(Kr(t,g.GENERIC_FAILURE)),null,2)):b(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await el(e.attemptedCommand,e.bootstrapGlobal),Sn(e.error);let a=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=a.errorCategory,i=a.commandResolution,await tn(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:i,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||b(`Failed to report error: ${de(a)}`)}try{await dt({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:i,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||b(`Failed to run error hooks: ${de(a)}`)}try{await Se()}catch(a){e.bootstrapGlobal.json||b(`Failed to flush error reporting: ${de(a)}`)}}var fp={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},ni=new Map;function oi(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function il(e,t){return e.options.some(n=>n.long===t)}function al(e,t){return e.options.some(n=>n.short===t)}function ii(e,t,n,o){let i=t.trim();if(!i)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(al(e,i))return;if(o){e.option(`${i} <value>`,`${a} (repeatable)`,$n);return}e.option(`${i} <value>`,a);return}let r=i.startsWith("--")?i:`--${i}`;if(!il(e,r)){if(o){e.option(`${r} <value>`,`${a} (repeatable)`,$n);return}e.option(`${r} <value>`,a)}}async function rl(e,t){let n=fp[e];if(!n)return[];let o=`${t}:${n}`,i=ni.get(o);if(i)return i;if(!await K(Y(t)))return ni.set(o,[]),[];let a=await F(t),r=(mn(a.schema).command_to_fields.get(n)??[]).flatMap(s=>[s.cli_flag,...s.cli_aliases].map(c=>({long:`--${c}`,type:oi(s.type),value_type:oi(s.type)})));return ni.set(o,r),r}async function sl(e,t){let n=I(t),o=T(process.cwd(),n.path);if(!await K(Y(o)))return;let i=be?.key===mi(o)?be.snapshot:null,a=i===null?await F(o):i.settings,r=mn(a.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let l=te(e,c.path.split(" "));if(l)for(let d of r.command_to_fields.get(c.command)??[]){let m=d.description??"";ii(l,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)ii(l,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function ci(e,t,n,o,i){let a=k(n);if(!(a!=="create"&&a!=="update"))try{let r=i??await F(t),s=se(r,o);Es(e,s,n)}catch{}}function ai(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function ll(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function di(e){return e.some(t=>t==="--profile")}function mi(e){return`pm-root:${e}`}function ri(e){for(let t of e)t.startsWith("settings_read_")&&pe(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function cl(e,t){e.profile&&(b(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&b(`profile:extensions activation_warnings=${z(t.activationWarnings)}`))}function Qt(e,t,n){if(!e)return;let o=w(n.commandPath??"")||"<none>";b(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function en(e,t=Ee){let n=mi(e);if(be?.key===n)return be.snapshot;try{let o=Date.now(),{settings:i,warnings:a}=await t(e),r=await Ti({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:r,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return be={key:n,snapshot:s},s}catch{return be={key:n,snapshot:null},null}}async function Le(e,t,n=F){let o=t?at(t):"all",i=ll(e,o);if(ct?.key===i)return ct.snapshot;try{let a=await n(e),r=await Ge({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Mo(t):void 0}),s=await ze({...r,loaded:r.loaded}),c=[...new Set(s.commands.handlers.map(u=>w(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),l=ls(s.registrations.flags),d=rs(s.commands.handlers,s.registrations.commands),m=ds(c,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:a,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...r.warnings],activationWarnings:[...s.warnings],loadedCount:r.loaded.length,loadFailedCount:r.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:r.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return ct={key:i,snapshot:p},p}catch{return ct={key:i,snapshot:null},null}}async function dl(e){let t=Je(e);if(t.noExtensions){let r=T(process.cwd(),t.path);return await K(Y(r))&&ri((await Ee(r)).warnings),null}let n=T(process.cwd(),t.path),o=await en(n);if(!o)return null;ri(o.settingsReadWarnings);let i={commandPath:E(e),commandArgs:No(e)};if(!it(o.discovery,i))return Qt(t.profile,o,i),null;let a=await Le(n,i);return a?(cl(t,a),{hooks:a.hooks,commands:a.commands,parsers:a.parsers,preflight:a.preflight,services:a.services,renderers:a.renderers,registrations:a.registrations,pmRoot:n}):null}async function pi(e){let t=await Le(e);return t?new Map(t.commandDescriptors):A}async function gp(e,t){return!e.requested||t.noExtensions||Ie(v,e.commandPathTokens)?A:pi(T(process.cwd(),t.path))}async function ml(e,t){return(await Pa({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function pl(e,t,n){let o=t.author;return Ia(e,tr.forActiveExtensionHost({pmRoot:e,author:o}),o,w(n))}async function ul(e,t,n,o=[]){let i=E(e),a=Nn(e.args.map(String),o),r={...t};delete r.author;let s={...n},c=T(process.cwd(),n.path),l={args:[...a],path:n.path},d=await yt({command:i,args:a,options:r,global:s,pm_root:c});n.profile&&d.warnings.length>0&&b(`profile:extensions parser_warnings=${z(d.warnings)}`),a=d.context.args,r=d.context.options,s=d.context.global,Gn(l,{args:a,path:s.path},r),qo(A.get(w(i)),a,r,o),ke(void 0),gt({command:i,args:a,options:{...r},global:{...s},pm_root:c});let m=await dn({command:i,args:a,options:r,global:s,pm_root:c,sdk:pl(c,s,i)});if(s.profile&&m.warnings.length>0&&b(`profile:extensions command_handler_warnings=${z(m.warnings)}`),!m.handled)throw m.warnings.length>0?fa(i,m):new R(`Command "${i}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),ke(m.result),m.result}var zs=Symbol("pm.wrappedActionHandler");function hp(e,t){let n=e[e.length-1];return n instanceof si?n:t}function Ws(e,t,n){e&&n.length>0&&b(`profile:extensions ${t}=${z(n)}`)}function yp(e){let t=A.get(w(e.commandPath));if(!t||!jo(e.activeRegistrations,e.commandPath))return;let n=Wt(t).length===0?Ba(e.commandArgs):Nn(e.commandArgs,e.extensionFlagDefinitions);Uo(t,n)}function _p(e,t,n){e.args=[...n],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),t.length>0&&Array.isArray(t[0])&&(t[0]=[...e.processedArgs])}function ui(e,t,n){if(!nt(e))return;let o=A.get(w(t))?.read_output_declared===!0;return Bt(n,o)}function fl(e){let t=n=>{let o=n;if(Fs(n),typeof o._actionHandler=="function"&&o[zs]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let r=hp(a,n),s=Date.now();Pn(r);let c=Je(r),l=q(E(r));if(["package inventory","packages inventory","extension inventory"].includes(l))return gr(l,c.expectHash),await i.apply(this,a);let d=T(process.cwd(),c.path),m=r.args.map(String),p=le(),u=p?rt(p,l,m):[],f=await rl(l,d),h=ui(r,l,u),y=Ne(r,m,[...u,...f],h);Ls(r,u,l),A.has(w(l))&&delete y.author,h!==void 0&&Ms(y,u,l);let M={args:[...m],path:c.path},x=await yt({command:l,args:m,options:y,global:c,pm_root:d});Ws(c.profile,"parser_warnings",x.warnings),m=x.context.args,y=x.context.options,re(r,y),c=x.context.global,Gn(M,{args:m,path:c.path},y),yp({activeRegistrations:p,commandPath:l,commandArgs:m,extensionFlagDefinitions:u}),c=await ja(c),At(r,c),_p(r,a,m),St(r,y),ke(void 0),gt({command:l,args:m,options:{...y},global:{...c},pm_root:d});let S=await dn({command:l,args:m,options:y,global:c,pm_root:d,sdk:pl(d,c,l)});if(Ws(c.profile,"command_handler_warnings",S.warnings),S.handled){ke(S.result),_n(S.result,{...c,command:l,commandArgs:m,commandOptions:y,pmRoot:d}),c.profile&&b(`profile:command=${l} took_ms=${Date.now()-s}`);return}return await i.apply(this,a)},o[zs]=!0}for(let i of n.commands)t(i)};t(e)}async function Jt(e){A=new Map,ne({overrides:[]}),e&&await ci(e.rootProgram,e.pmRoot,e.invocationArgv,Si(),e.settings)}function vp(e,t,n,o){if(t?.flags&&t.flags.length>0){vo(e,t.flags);let i=wo(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);t&&nt(e)&&e.addHelpText("after",Co(t)),o&&e.addHelpText("after",o)}function wp(e,t,n,o){t&&e.addHelpText("after",t),n&&e.addHelpText("after",Co(n)),o&&e.addHelpText("after",o)}function gl(e,t,n){let o={core:0,standard:1,full:2,internal:3},i=(a,r)=>{let s=r.join(" "),c=[...n.entries()].filter(([d])=>d===s||d.startsWith(`${s} `)).map(([,d])=>d),l=c.length===0?"standard":c.reduce((d,m)=>o[m.tier]<o[d]?m.tier:d,"internal");It(a,l);for(let d of a.commands)i(d,[...r,d.name()])};for(let a of e.commands)t.has(a.name())||i(a,[a.name()])}async function hl(e,t){let n=I(t),o=T(process.cwd(),n.path);if(n.noExtensions){await Jt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await en(o),a=Me(t);if(!i){await Jt();return}if(!it(i.discovery,a)){await Jt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),Qt(di(t),i,a);return}let r=await Le(o,a);if(!r){await Jt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}ne(r.services),A=new Map(r.commandDescriptors),await ci(e,o,t,r.registrations,r.settings);let s=ys(e,r.commandHandlers,r.commandDescriptors,r.commandAliases,d=>_s(r.activationWarnings,b,d)),c=new Set(e.commands.map(d=>d.name())),l=d=>{let m=d.split(" ").filter(x=>x.length>0),p=r.commandDescriptors.get(d),u=te(e,m),f=r.commandFlagHelp.get(d),h=p?gs(p):null;if(u){vp(u,p,f,h);return}let y=hs(e,m);p?.description&&y.description(p.description);let M=f;p&&(ms(y,p),p.flags.length>0&&(vo(y,p.flags),M=wo(y,p.flags)??void 0)),wp(y,M,p,h),y.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...x)=>{let S=x[x.length-1],P=S instanceof si?S:y,mt=Je(P),Rl=Date.now(),nn=rt(r.registrations,d,P.args.map(String)),hi=Ne(P,P.args.map(String),nn,ui(P,d,nn)),yi=await ul(P,hi,mt,nn);await Ua(mt,yi),_n(yi,{...mt,command:d,commandArgs:P.args.map(String),commandOptions:hi,pmRoot:o}),mt.profile&&b(`profile:command=${d} took_ms=${Date.now()-Rl}`)})};for(let d of s)l(d);gl(e,c,r.commandDescriptors)}var Fe=Ei(import.meta.url,["../.."])??"0.0.0",v=In(Fe);async function Bs(e){if(!U)return;let t=Reflect.get(e,Xs);typeof t=="string"&&await er(t)}async function Vs(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function Js(e,t,n){!U||!await wn(!0)||(En(e,t,n,{source_context:U.source_context,source_context_source:U.source_context_source}),ga(e),Xt=U)}async function tn(e,t,n){let o=Xt;if(!o)return;Xt=null;let i=!1;try{let a=await F(o.global_pm_root);i=a.telemetry.enabled&&a.telemetry.installation_id===o.installation_id}catch{}await wn(i)?ya(e,t,n):ha()}async function bp(e){let t=await dl(e);return cn(t?.registrations??null),t}function yl(e,t){t&&st(t)||(e.hook("preAction",async(n,o)=>{Ce=null,U=null,Xt=null,ht(),Pn(o);let i=o.optsWithGlobals(),a=Je(o),r=q(E(o)),s=o.args.map(String),c={args:[...s],path:a.path},l=Ne(o,s),d={...a},m=T(process.cwd(),a.path),p=await bp(o);if(Ji(r,{...l,...qa(r,o.processedArgs),outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),Lo(o,r,d,l),await Vs(o,void 0,()=>Ca(r,d)),!p){Ce=Oi({commandName:r,commandArgs:s,commandOptions:l,globalOptions:d,pmRoot:m}),U=await An({command:r,pm_version:Fe,args:s,options:l,global:d,pm_root:m}),await Bs(e),await Js(r,s,l),await Ao(r,l,m,ai()),await So(r,s,l,d,m),await Hn({command:o,commandPath:r,commandArgs:s,commandOptions:l,expectHash:a.expectHash,pmRoot:m,globalOptions:d});return}Ii(p.hooks),Pi(p.commands),$i(p.parsers),Di(p.preflight),ne(p.services),Mi(p.renderers),cn(p.registrations);let u=rt(p.registrations,r,s);l=Ne(o,s,u,ui(o,r,u)),Lo(o,r,d,l);let f=await yt({command:r,args:s,options:l,global:d,pm_root:p.pmRoot});d.profile&&f.warnings.length>0&&b(`profile:extensions parser_warnings=${z(f.warnings)}`),s=f.context.args,l=f.context.options,re(o,l),d=f.context.global;let h={args:[...s],path:d.path};St(o,l);let y=await Li({command:r,args:s,options:l,global:d,pm_root:p.pmRoot,decision:ai()});d.profile&&y.warnings.length>0&&b(`profile:extensions preflight_warnings=${z(y.warnings)}`),s=y.context.args,l=y.context.options,re(o,l),d=y.context.global,St(o,l);let M=y.decision;await Ao(r,l,p.pmRoot,M),await So(r,s,l,d,p.pmRoot),await Hn({command:o,commandPath:r,commandArgs:c.args,commandOptions:l,expectHash:a.expectHash,pmRoot:p.pmRoot,rewritten:qn(c,[h,{args:s,path:d.path}]),globalOptions:{...d,path:a.path,noExtensions:a.noExtensions}});let x=M.run_extension_migrations?await Vs(o,[],()=>ml(p.registrations.migrations,p.pmRoot)):[];d.profile&&x.length>0&&b(`profile:extensions migration_warnings=${z(x)}`);let S=Rs(p.registrations.migrations);Ce={hooks:p.hooks,commandName:r,commandArgs:s,commandOptions:{...l},globalOptions:{...d},pmRoot:p.pmRoot,profileEnabled:!!d.profile,migrationBlockers:S},ke(void 0),gt({command:r,args:s,options:{...l},global:{...d},pm_root:p.pmRoot}),U=await An({command:r,pm_version:Fe,args:s,options:l,global:d,pm_root:p.pmRoot}),await Bs(e),await Js(r,s,l);let P=await Ai(p.hooks,{command:r,args:s,options:{...l},global:{...d},pm_root:p.pmRoot});d.profile&&P.length>0&&b(`profile:extensions hook_warnings=${z(P)}`),M.enforce_mandatory_migration_gate&&Ts(r,l,S)}),e.hook("postAction",async()=>{let n=ei();await tn(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await dt(n),await Se()}))}yl(v);var Ks=Symbol("pmCliIdempotentTopLevelRegistration");function _l(e){let t=e;if(t[Ks])return;t[Ks]=!0;let n=e.command.bind(e);e.command=((o,...i)=>{let a=o.split(/\s+/u)[0];return e.commands.some(r=>r.name()===a||r.aliases().includes(a))?new si(a):n(o,...i)})}async function Cp(e,t){if(_l(e),t.setup){let{registerSetupCommands:n}=await ip();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await ap(),o=typeof t.targetCommandName=="string"&&Ho.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await rp();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await sp();n(e)}}function xp(e){return async t=>{let n=pt(t.errorCode),o=bt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await ka({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Fe,pm_root:e.bootstrapPmRoot,error_code:t.errorCode,error_message:t.errorMessage,exit_code:t.exitCode,error_category:n,command_resolution:o,resolution_stage:t.resolutionStage}),{errorCategory:n,commandResolution:o}}}async function vl(e){if(e.bootstrapGlobal.noExtensions||st(e.invocationArgv))return;let t=Me(e.invocationArgv),n=await en(e.bootstrapPmRoot);if(n&&it(n.discovery,t)){let o=await Le(e.bootstrapPmRoot,t);wl(o);return}n&&Qt(di(e.invocationArgv),n,t),ne({overrides:[]})}function wl(e){if(!e){ne({overrides:[]});return}ne(e.services)}async function fi(e){await tn(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await dt({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function bl(){await tn(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await dt({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function Cl(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof R)&&(xn(e.error)||!n))return!1;let o=de(e.error),i=e.error instanceof R?e.error.exitCode:Cn(t),a=e.error instanceof R||pa(e.error)?e.error.context:void 0,r=Qs(a,e.invocationArgv,o),s=Vr(o,r),c=Ye(e.bootstrapGlobal.lean?$t(so(o,i,r)):so(o,i,r)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?X(c,u=>`${JSON.stringify(u,null,2)}
40
+ `):c,null,2):Wr(o,r,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?oe(`${l}
41
+ `):b(l);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:i,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Zt({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:U?.source_context},e.bootstrapGlobal);return await fi({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(Sn(kn(e.error,o)),await Se(li)),process.exitCode=i,!0}async function xl(e,t){let n=O(e.invocationArgv).commandPathTokens.join(" ")||mo(e.invocationArgv),o=q(n),i=`unknown command '${n}'`,a=T(process.cwd(),e.bootstrapGlobal.path),r=e.bootstrapGlobal.noExtensions?A:await pi(a),s=Me(e.invocationArgv),c=e.bootstrapGlobal.noExtensions?[]:await ko(a,{},De(s)),l=await et({message:i},v,r,{failedExtensions:c},e.invocationArgv),d=lo(l.message,l.commandName,l.allowedTypes,{unknownCommandExamples:l.unknownCommandExamples,unknownCommandNextSteps:l.unknownCommandNextSteps,attemptedCommand:l.attemptedCommand,normalizedInvocationArgs:l.normalizedInvocationArgs,providedOptionFlags:l.providedOptionFlags,unknownOptionSuggestions:l.unknownOptionSuggestions,suggestedRetryCommand:l.suggestedRetryCommand,failedExtensions:c}),{errorCategory:m,commandResolution:p}=await e.emitTelemetryCommandError({command:o,errorCode:d.code,errorMessage:d.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),u=await Zt({command:o,error_code:d.code,error_category:m,exit_code:g.USAGE,error_message:d.detail,command_resolution:p,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await go({message:i},v,r,e.bootstrapGlobal.lean===!0,{failedExtensions:c},e.invocationArgv):await fo({message:i},v,r,{failedExtensions:c},e.invocationArgv),h=co(f,e.jsonErrors,c);await fi({errorMessage:i,exitCode:g.USAGE,classificationCode:d.code,errorCategory:m,commandResolution:p,resolutionStage:"parse"}),e.jsonErrors?oe(`${jn(h)}
42
+ `):b(h),u&&await Se(li),process.exitCode=g.USAGE}async function kl(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let o=O(e.invocationArgv);return o.requested&&!Ie(v,o.commandPathTokens)?(await xl(e,t),!0):(await bl(),!0)}async function El(e,t){let n=await et(e.error,v,A,{},e.invocationArgv),o=lo(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:i,commandResolution:a}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),r=await Zt({command:e.attemptedCommand,error_code:o.code,error_category:i,exit_code:g.USAGE,error_message:o.detail,command_resolution:a,resolution_stage:"parse",source_context:U?.source_context},e.bootstrapGlobal),s=e.jsonErrors?await go(e.error,v,A,e.bootstrapGlobal.lean===!0,{},e.invocationArgv):await fo(e.error,v,A,{},e.invocationArgv),c=await vs(o.code,e.bootstrapPmRoot,{},De(Me(e.invocationArgv))),l=co(s,e.jsonErrors,c);await fi({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:i,commandResolution:a,resolutionStage:"parse"}),e.jsonErrors?oe(`${jn(l)}
43
+ `):b(l),r&&await Se(li),process.exitCode=g.USAGE}function Sl(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return typeof t=="string"&&(t==="commander.version"||t.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function Al(e){let t=e.error.code,n=String(e.error.message??"");if(!await kl(e,t,n)){if(t==="commander.version"){await bl();return}await El(e,t)}}async function gi(e){let t=I(e.invocationArgv),n=T(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:k(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:xp({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await vl({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Cl(o,bn(e.error))){if(Sl(e.error)){await Al(o);return}await ol({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}function kp(e,t,n){let o=n.requested?n.commandPathTokens:L(t),i=B(o);if(i&&!te(e,[...i.canonical_argv]))throw new Ys(g.USAGE,"commander.unknownCommand",`unknown command '${i.alias}'`)}function Ep(e,t){let n=$(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let r=$(t.slice(n+1));if(r===void 0)return;n+=r+1}let o=Yt.get(t[n]),i=t.slice(n).filter(r=>!["--global","--project","--local"].includes(r)),a=o?.find(r=>r.alias.split(" ").every((s,c)=>i[c]===s));a?.lifecycle==="deprecated"&&Reflect.set(e,Xs,a.alias)}function Sp(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function Ap(e,t){v=In(Fe),v.hook("preAction",(a,r)=>{t.configurationOnly=["item mutate","item complete"].includes(E(r))&&r.optsWithGlobals().dryRun===!0}),yl(v,e),ct=null,be=null,A=new Map,Ni();let n=[...e],o,i;try{let a=Ve(e);n=a.argv,Ep(v,e);let r=Sp(n),s=n.length===0,c=I(n);if(c.authorMissingValue)throw new R("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=Ha(c.author),Vo(a),i=$a(n);let l=Go(n);await Cp(v,l),Xn(v,!0),Wo(v,n)?await hl(v,n):(A=new Map,ne({overrides:[]})),Bo(n)&&await sl(v,n),Xn(v);let d=O(n);kp(v,n,d),zo(n)&&Ir(v,n),fl(v);let m=await gp(d,c);if(await ks(v,n,m,e))return;if(d.requested&&!Ie(v,d.commandPathTokens))throw new Ys(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||ie(n)&&k(n)===void 0){v.outputHelp();return}if(st(n)){await v.parseAsync(r);return}let p=T(process.cwd(),c.path),u=await F(p),f=await is(n,p,c.noExtensions,Le);await hr(h=>Oa({pmRoot:p,packages:f?.contextIntentPackages},()=>Ui({env:{...process.env,PM_PATH:p},argv:r,cwd:process.cwd()},()=>qi(u.agent_identity.harness_signals,()=>h(()=>v.parseAsync(r)),{probesEnabled:u.agent_identity?.probes_enabled}))))}catch(a){await gi({error:a,invocationArgv:n})}finally{i?.(),o?.()}}async function qg(e=process.argv.slice(2)){let t=e;try{t=Ve(e).argv}catch{}let n=Us(t),o={configurationOnly:n!==void 0},i=()=>o.configurationOnly,a=()=>pr(I(t).json,async()=>{try{await Ga(process.env,()=>Ap(e,o))}catch(r){await gi({error:r,invocationArgv:[...e]})}});if(n!==void 0){let r=T(process.cwd(),I(t).path),s=T(process.cwd(),n.path),c=Ci(process.cwd());await vt(r,()=>vt(s,()=>vt(c,a,i),i),i)}else await a()}var Hg={activationCommandMatchesProbe:To,applyDynamicExtensionRootHelpVisibility:gl,bootstrapProfileEnabled:di,buildBootstrapActivationProbe:Me,buildPostActionTelemetryOutcome:ei,buildPmCliRecoveryContext:Qs,buildRuntimeExtensionDiscoverySnapshotCacheKey:mi,buildRuntimeExtensionActivationScope:at,buildRuntimeExtensionSnapshotCacheKey:ll,buildRuntimeExtensionFilterForProbe:Mo,addRuntimeFieldOption:ii,collectActivationCommandCandidates:De,collectExtensionFlagDefinitionsForCommand:Ke,collectExtensionFlagDefinitionsForInvocation:rt,collectLeadingCommandArgs:Ro,collectParsedActivationCommandArgs:No,collectRuntimeFieldLooseFlagDefinitionsForCommand:rl,commandHasLongOption:il,commandHasShortOption:al,commandPathNeedsSearchExtensions:Oo,commandPathNeedsTemplateExtensions:Ht,describeUnknownError:de,defaultPreflightDecision:ai,discoveryNeedsActivationForProbe:it,emitExtensionProfile:cl,emitExtensionSkippedProfile:Qt,emitSettingsReadWarnings:ri,ensureIdempotentTopLevelCommandRegistration:_l,enforceExplicitRetryForFlagTypos:Vo,envFlagEnabled:tl,executeRegisteredRuntimeMigrations:ml,extractCommandScopedOptions:Ne,extensionActivationCommands:qt,extensionCapabilities:ot,extensionNeedsActivationForProbe:Gt,extensionProvidesTemplatesRuntime:Po,hasAnyCapability:$e,hasGlobalExtensionContributions:$o,handleGenericRunPmCliError:ol,handleRunPmCliCommanderError:Al,handleRunPmCliError:gi,handleRunPmCliHelpDisplayError:kl,handleRunPmCliKnownError:Cl,handleRunPmCliCommanderUsageError:El,handleUnknownHelpCommandError:xl,inferMissingFieldsFromErrorMessage:Zs,inferPostActionErrorCode:Qo,inferPostActionFailureMessage:Zo,invocationRequestsVersion:lt,isCommanderError:xn,loadRuntimeExtensionCommandDescriptorsForRecovery:pi,loadRuntimeExtensionDiscoverySnapshot:en,loadRuntimeExtensionSnapshot:Le,maybeLoadRuntimeExtensions:dl,maybeAttachCreateUpdatePolicyHelpText:ci,maybeLogHandledCliErrorToSentry:Zt,matchesStaticExtensionCommand:Ut,normalizeTelemetryCommandResolution:Ko,normalizeTelemetryErrorCategory:Xo,normalizeTelemetryResolutionStage:Yo,normalizeThrownExitCode:Cn,probeUsesAnyFlag:Io,prepareExtensionServicesForRunPmCliError:vl,readRecordBoolean:Jo,readRecordNumber:Vt,readRecordString:we,recordCliReadOutputInvocationProvenance:Fo,registerDynamicExtensionCommandPaths:hl,registerRuntimeSchemaFieldFlags:sl,resolveCoreCommandRegistrationSelection:Go,resolveStaticExtensionActivationDecision:Do,resolveUnknownHelpToken:mo,readThrownExitCode:bn,runAndClearAfterCommandHooks:dt,runRequiredExtensionCommand:ul,shouldAttachRichHelpTextForInvocation:zo,shouldLogHandledErrorToSentry:nl,shouldRegisterDynamicExtensionPaths:Wo,shouldRegisterRuntimeSchemaFlags:Bo,shouldHandleRunPmCliCommanderError:Sl,setActiveExtensionHookContextForTest:ep,setActiveRuntimeExtensionCommandDescriptorsForTest:tp,setRecoveredExtensionServices:wl,toLooseFieldDefinitionType:oi,isImporterOrExporterCommandPath:jo,validateDynamicExtensionCommandInvocation:qo,wrapProgramActionsForExtensionHandlers:fl,wrapThrownErrorForSentry:kn};export{Hg as _testOnly,qg as runPmCli};
44
44
  //# sourceMappingURL=main.js.map