@unbrained/pm-cli 2026.8.27 → 2026.8.28

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 (105) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +25 -1
  3. package/dist/cli/error-guidance.js +61 -7
  4. package/dist/cli/register-annotations.js +58 -41
  5. package/dist/cli-bundle/bundle-manifest.json +121 -121
  6. package/dist/cli-bundle/chunks/{chunk-SH6P7FXI.js → chunk-BY2FQ2NI.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-TNX6HC54.js → chunk-E73FDIWT.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-SHMDY36D.js → chunk-FEVBFFCQ.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-CVBBGWW5.js → chunk-M7OXRQE3.js} +10 -6
  10. package/dist/cli-bundle/chunks/{chunk-R4ETAOJC.js → chunk-NBCBFVZI.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-SKXLJIEK.js → chunk-NTXZHRKA.js} +45 -45
  12. package/dist/cli-bundle/chunks/{chunk-52EKTW6V.js → chunk-QE6WQXFO.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-MFNTKMTI.js → chunk-TIQ6AMH2.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-X2RROGZE.js +2 -0
  15. package/dist/cli-bundle/chunks/{chunk-OS27HHBN.js → chunk-XRVVYRRO.js} +28 -28
  16. package/dist/cli-bundle/chunks/{chunk-3OO3W6FW.js → chunk-XWEQGHHG.js} +2 -2
  17. package/dist/cli-bundle/chunks/{register-list-query-EUWM6VII.js → register-list-query-J35ZPQQ5.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-mutation-FD4HSAVU.js → register-mutation-J6XJJOGU.js} +4 -4
  19. package/dist/cli-bundle/chunks/{register-operations-HRMNFEC3.js → register-operations-AE3JEMFT.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-setup-33GNICLX.js → register-setup-OQERLLWE.js} +2 -2
  21. package/dist/cli-bundle/focused-chunks/{chunk-4BR5UU52.js → chunk-4ZDRZYYJ.js} +41 -41
  22. package/dist/cli-bundle/focused-chunks/{chunk-MXTYGECH.js → chunk-AHAM2HAU.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-SUBSWYW3.js → chunk-JZYPPMXF.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/chunk-LLNTHF5X.js +2 -0
  25. package/dist/cli-bundle/focused-chunks/chunk-LYFWQMVC.js +2 -0
  26. package/dist/cli-bundle/focused-chunks/{chunk-EKX37ZHA.js → chunk-THEPQMLX.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/chunk-YJLDHJOD.js +2 -0
  28. package/dist/cli-bundle/main.js +14 -14
  29. package/dist/cli-bundle/sdk-authoring.js +1 -1
  30. package/dist/cli-bundle/sdk-contracts.js +2 -2
  31. package/dist/cli-bundle/sdk-core.js +26 -26
  32. package/dist/cli-bundle/sdk-governance.js +1 -1
  33. package/dist/cli-bundle/sdk-merge.js +20 -20
  34. package/dist/cli-bundle/sdk-query.js +1 -1
  35. package/dist/cli-bundle/sdk-runtime.js +1 -1
  36. package/dist/cli-bundle/sdk-testing.js +1 -1
  37. package/dist/cli-bundle/sdk.js +10 -10
  38. package/dist/mcp/tool-definitions.js +5 -5
  39. package/dist/sdk/agent/command-recovery.js +3 -3
  40. package/dist/sdk/agent/task-transcript-contracts.d.ts +52 -0
  41. package/dist/sdk/agent/task-transcript-contracts.js +198 -0
  42. package/dist/sdk/annotations.d.ts +5 -2
  43. package/dist/sdk/annotations.js +66 -36
  44. package/dist/sdk/cli-bootstrap.d.ts +2 -8
  45. package/dist/sdk/cli-bootstrap.js +7 -67
  46. package/dist/sdk/cli-contracts/bootstrap-command-scanner.d.ts +23 -0
  47. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +80 -0
  48. package/dist/sdk/cli-contracts/flag-contracts.js +5 -2
  49. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +5 -5
  50. package/dist/sdk/cli-contracts/tool-parameter-tables.js +15 -2
  51. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  52. package/dist/sdk/cli-contracts/tool-schema.js +16 -3
  53. package/dist/sdk/comments.d.ts +4 -0
  54. package/dist/sdk/comments.js +2 -2
  55. package/dist/sdk/completion.js +9 -5
  56. package/dist/sdk/contracts.d.ts +1 -0
  57. package/dist/sdk/contracts.js +3 -2
  58. package/dist/sdk/extension/install-sources.d.ts +13 -0
  59. package/dist/sdk/extension/install-sources.js +62 -30
  60. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +26 -2
  61. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +26 -14
  62. package/dist/sdk/index.d.ts +1 -0
  63. package/dist/sdk/index.js +3 -2
  64. package/dist/sdk/learnings.d.ts +4 -0
  65. package/dist/sdk/learnings.js +7 -4
  66. package/dist/sdk/lifecycle/close.js +4 -3
  67. package/dist/sdk/notes.d.ts +4 -0
  68. package/dist/sdk/notes.js +2 -2
  69. package/dist/sdk/runtime-input.js +5 -2
  70. package/dist/sdk/runtime.d.ts +6 -6
  71. package/dist/sdk/runtime.js +8 -8
  72. package/docs/COMMANDS.md +4 -3
  73. package/docs/OUTPUT_TOKEN_ACCOUNTING.md +20 -7
  74. package/docs/RELEASING.md +9 -1
  75. package/docs/SDK.md +12 -0
  76. package/docs/SDK_CONTEXT_INTEGRITY.md +12 -1
  77. package/docs/SDK_RUNTIME_BOUNDARIES.md +10 -0
  78. package/docs/TESTING.md +6 -2
  79. package/docs/agent-task-token-baseline.json +97 -11
  80. package/docs/agent-task-transcripts.json +211 -0
  81. package/docs/generated/FLAG_LEXICON_BUDGETS.md +3 -3
  82. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  83. package/docs/performance/cli-transport-overhead.md +10 -2
  84. package/marketplace.json +2 -2
  85. package/package.json +2 -2
  86. package/packages/pm-beads/package.json +1 -1
  87. package/packages/pm-calendar/package.json +1 -1
  88. package/packages/pm-command-kit/package.json +1 -1
  89. package/packages/pm-digital-twin/package.json +1 -1
  90. package/packages/pm-governance-audit/package.json +1 -1
  91. package/packages/pm-guide-shell/package.json +1 -1
  92. package/packages/pm-kanban/package.json +1 -1
  93. package/packages/pm-lifecycle-hooks/package.json +1 -1
  94. package/packages/pm-linked-test-adapters/package.json +1 -1
  95. package/packages/pm-search-advanced/package.json +1 -1
  96. package/packages/pm-templates/package.json +1 -1
  97. package/packages/pm-todos/package.json +1 -1
  98. package/packages/pm-vcs/package.json +1 -1
  99. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  100. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  101. package/sdk/public-surface.json +197 -25
  102. package/dist/cli-bundle/chunks/chunk-QTO7USTH.js +0 -2
  103. package/dist/cli-bundle/focused-chunks/chunk-2AGZ5BRT.js +0 -2
  104. package/dist/cli-bundle/focused-chunks/chunk-AQ5IYEZZ.js +0 -2
  105. package/dist/cli-bundle/focused-chunks/chunk-YHWHX6YY.js +0 -2
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import{A as or,B as Ht,D as rr,d as Mo,g as z,h as Xo,i as P,j as Qo,k,l as Zo,q as et,r as er,s as tr,u as nr,v as Q,w as Lt,x as Ut,y as jt,z as qt}from"./chunks/chunk-QTO7USTH.js";import{A as Uo,ab as Yo,f as Lo}from"./chunks/chunk-CVBBGWW5.js";import"./chunks/chunk-TNX6HC54.js";import"./chunks/chunk-R4ETAOJC.js";import{Qb as Wo,Sc as Ze,Vc as Bo,Wc as Ko,Xc as X,Yc as Jo,pc as Vo}from"./chunks/chunk-OS27HHBN.js";import{Ea as zo,ma as Ho}from"./chunks/chunk-SKXLJIEK.js";import{Fb as Go}from"./chunks/chunk-MFNTKMTI.js";import"./chunks/chunk-WYRZZ5ZE.js";import{$ as Wn,Ac as Y,Aj as ke,Bc as lo,C as f,Cc as He,Cd as At,D as xt,Dc as ae,Dj as $o,E as v,Ec as xe,Eg as Co,Fe as R,Fg as ko,Fm as Qe,G as we,Ge as Ve,Gj as Po,Gm as Ft,Hc as mo,Hg as Ot,Hm as Mt,Ic as ze,Ig as y,Im as Se,Jm as $,K as vt,Kb as Qn,Km as jo,La as kt,Lj as Nt,Lm as Dt,Mj as No,Nj as Fo,Oa as J,Oc as St,Pc as Ge,Qa as Yn,Qc as po,Ra as qe,Rc as uo,Rm as M,Sb as Zn,Ua as Et,Ub as eo,Va as Xn,Vf as yo,Wa as E,Wf as Tt,Za as H,aa as Vn,ai as Eo,ba as Ct,bi as ce,c as q,ci as I,cj as To,di as So,dj as Rt,dn as qo,ej as It,fj as $t,gc as to,gj as ve,hc as _e,hj as Pt,ia as Bn,ij as Oo,ja as Kn,jc as be,jf as se,jg as wo,jj as Ce,kc as no,kf as go,kg as _o,la as Jn,lg as bo,mf as ho,mg as xo,mj as Ro,ng as vo,nj as Io,pe as fo,pm as Do,qm as Xe,tc as oo,tf as Be,uc as ro,ui as Ke,vc as io,vi as Ao,vk as Je,wc as ao,xc as B,xe as We,xk as Ee,yc as so,yk as Ye,zc as co}from"./chunks/chunk-3OO3W6FW.js";import{Command as In,CommanderError as Jc}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]="8eca3029-0d1f-569a-84ce-5ccd0b92a272")}catch{}})();var Sa=new Set(["__proto__","prototype","constructor"]),ir=Symbol("looseOptionOccurrences");function Ae(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function Aa(e,t,n){let o=e[t];if(o===void 0){e[t]=n;return}if(Array.isArray(o)){o.push(n),e[t]=o;return}e[t]=[o,n]}function zt(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let a=n.indexOf("=");if(a>=0)return{consumed:1,key:n.slice(1,a).trim(),value:n.slice(a+1)};let s=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:s,value:c}:{consumed:1,key:s,value:!0}}let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(2,o).trim(),value:n.slice(o+1)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let r=n.slice(2).trim(),i=e[t+1];return typeof i=="string"&&!i.startsWith("-")?{consumed:2,key:r,value:i}:{consumed:1,key:r,value:!0}}function tt(e){return Sa.has(e)}function ar(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Wn(t)}function Te(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let r=Ae(n.slice(2));r.length>0&&!tt(r)&&t.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){let r=Ae(o.slice(1));r.length>0&&!tt(r)&&t.push(r)}return[...new Set(t)]}function sr(e){let t=new Set;for(let n of e)for(let o of Te(n))t.add(o);return t}function Ta(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=Ae(t.slice(2));if(n.length>0&&!tt(n))return n}return Te(e)[0]??null}function Oa(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Gt(e,t,n){if(t.length===0)return;let o=new Set,r=new Map,i=[],a=[];for(let s of t){let c=Te(s),d=Oa(s);d!==null&&a.push(d);for(let l of c)o.add(l),s.enabled===!1&&r.set(l,d);s.required===!0&&s.enabled!==!1&&c.length>0&&i.push({keys:c,label:d})}for(let s of Object.keys(e)){if(!o.has(s)){let d=a.length>0?` Expected one of: ${[...new Set(a)].join(", ")}.`:"";throw new v(`Unknown option '--${s}' for extension command '${n}'.${d}`,f.USAGE)}let c=r.get(s);if(c)throw new v(`Option '${c}' is disabled for extension command '${n}'.`,f.USAGE)}for(let s of i)if(!s.keys.some(c=>Object.hasOwn(e,c)))throw new v(`Missing required option '${s.label}' for extension command '${n}'.`,f.USAGE)}function Ra(e){return typeof e=="string"||e==null?e:String(e)}function Ia(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function $a(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var Pa={string:Ra,number:Ia,boolean:$a};function nt(e,t){return Array.isArray(e)?e.map(n=>nt(n,t)):Pa[t](e)}function cr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):Vn(e);return t?o.map(r=>nt(r,t)):o}function Na(e,t,n,o){return n?cr(e,t,o):t?nt(e,t):e}function Fa(e,t,n){let o=e[ir];if(!o||o.length===0)return n;let r=new Set(t);return o.filter(i=>r.has(i.key)).map(i=>i.value)}function lr(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[r,i]of Object.entries(e))o[r]=i;for(let r of t){let i=Ta(r);if(!i)continue;let a=r.list===!0,s=Te(r);for(let l of s)if(!(l===i||!Object.hasOwn(o,l))){if(Object.hasOwn(o,i)){if(!a){delete o[l];continue}let m=o[i],p=o[l];o[i]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[l];continue}o[i]=o[l],delete o[l]}let c=ar(r),d=r.repeatable===!0;if(!Object.hasOwn(o,i)){r.default!==void 0&&(o[i]=Na(r.default,c,a,d));continue}if(a){o[i]=cr(Fa(n,s,o[i]),c,d);continue}c&&(o[i]=nt(o[i],c))}return o}function dr(e){let t=Object.create(null),n=[];Object.defineProperty(t,ir,{value:n});let o=0;for(;o<e.length;){let r=zt(e,o);if(!r){o+=1;continue}let i=Ae(r.key);if(i.length===0||tt(i)){o+=r.consumed;continue}Aa(t,i,r.value),n.push({...r,key:i}),o+=r.consumed}return t}function mr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=zt(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function Wt(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let a of t){let s=ar(a);for(let c of Te(a))n.add(c),s==="boolean"&&o.add(c)}if(n.size===0)return[...e];let r=[],i=0;for(;i<e.length;){if(e[i]==="--"){r.push(...e.slice(i+1));break}let a=zt(e,i);if(a){let s=Ae(a.key);if(n.has(s)){let c=e[i],d=o.has(s)&&!c.includes("=")?1:a.consumed;i+=d;continue}}r.push(e[i]),i+=1}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0186e30-9c25-5539-b778-1ef2ee21764a")}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]="1399e88f-710a-5e5c-b4b3-70e35ec401cf")}catch{}})();var pr=new WeakMap;function ur(e,t){pr.set(e,t)}function Z(e){return pr.get(e)}function fr(e){return e.length>0?[e[0]]:[]}function Ma(e){let t=["","Intent:",` ${e.why}`],n=fr(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(`
2
+ import{A as Ht,B as or,C as zt,E as rr,d as Do,h as z,i as Ae,j as P,k as Zo,l as k,m as Qo,r as tt,s as er,t as tr,v as nr,w as Z,x as Ut,y as jt,z as qt}from"./chunks/chunk-X2RROGZE.js";import{A as jo,ab as Xo,f as Uo}from"./chunks/chunk-M7OXRQE3.js";import"./chunks/chunk-E73FDIWT.js";import"./chunks/chunk-NBCBFVZI.js";import{Qb as Bo,Sc as et,Vc as Ko,Wc as Jo,Xc as X,Yc as Yo,pc as Vo}from"./chunks/chunk-XRVVYRRO.js";import{Ea as Go,ma as zo}from"./chunks/chunk-NTXZHRKA.js";import{Fb as Wo}from"./chunks/chunk-TIQ6AMH2.js";import"./chunks/chunk-WYRZZ5ZE.js";import{$ as Bn,Ac as Y,Aj as ke,Bc as mo,C as f,Cc as ze,Cd as Tt,D as vt,Dc as ae,Dj as Po,E as v,Ec as xe,Eg as ko,Fe as A,Fg as Eo,Fm as Qe,G as we,Ge as Ve,Gj as No,Gm as Ft,Hc as po,Hg as Rt,Hm as Dt,Ic as Ge,Ig as y,Im as Se,Jm as $,K as Ct,Kb as Qn,Km as qo,La as Et,Lj as Mt,Lm as Lt,Mj as Mo,Nj as Fo,Oa as J,Oc as At,Pc as We,Qa as Xn,Qc as uo,Ra as He,Rc as fo,Rm as F,Sb as eo,Ua as St,Ub as to,Va as Zn,Vf as wo,Wa as E,Wf as Ot,Za as H,aa as Vn,ai as So,ba as kt,bi as le,c as q,ci as I,cj as Oo,di as Ao,dj as It,dn as Ho,ej as $t,fj as Pt,gc as no,gj as ve,hc as _e,hj as Nt,ia as Kn,ij as Ro,ja as Jn,jc as be,jf as se,jg as _o,jj as Ce,kc as oo,kf as ho,kg as bo,la as Yn,lg as xo,mf as yo,mg as vo,mj as Io,ng as Co,nj as $o,pe as go,pm as Lo,qm as Ze,tc as ro,tf as Ke,uc as io,ui as Je,vc as ao,vi as To,vk as Ye,wc as so,xc as V,xe as Be,xk as Ee,yc as lo,yk as Xe,zc as co}from"./chunks/chunk-XWEQGHHG.js";import{Command as $n,CommanderError as Yl}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]="8eca3029-0d1f-569a-84ce-5ccd0b92a272")}catch{}})();var Sa=new Set(["__proto__","prototype","constructor"]),ir=Symbol("looseOptionOccurrences");function Te(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function Aa(e,t,n){let o=e[t];if(o===void 0){e[t]=n;return}if(Array.isArray(o)){o.push(n),e[t]=o;return}e[t]=[o,n]}function Gt(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let a=n.indexOf("=");if(a>=0)return{consumed:1,key:n.slice(1,a).trim(),value:n.slice(a+1)};let s=n.slice(1).trim(),l=e[t+1];return typeof l=="string"&&!l.startsWith("-")?{consumed:2,key:s,value:l}:{consumed:1,key:s,value:!0}}let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(2,o).trim(),value:n.slice(o+1)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let r=n.slice(2).trim(),i=e[t+1];return typeof i=="string"&&!i.startsWith("-")?{consumed:2,key:r,value:i}:{consumed:1,key:r,value:!0}}function nt(e){return Sa.has(e)}function ar(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Bn(t)}function Oe(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let r=Te(n.slice(2));r.length>0&&!nt(r)&&t.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){let r=Te(o.slice(1));r.length>0&&!nt(r)&&t.push(r)}return[...new Set(t)]}function sr(e){let t=new Set;for(let n of e)for(let o of Oe(n))t.add(o);return t}function Ta(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=Te(t.slice(2));if(n.length>0&&!nt(n))return n}return Oe(e)[0]??null}function Oa(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Wt(e,t,n){if(t.length===0)return;let o=new Set,r=new Map,i=[],a=[];for(let s of t){let l=Oe(s),d=Oa(s);d!==null&&a.push(d);for(let c of l)o.add(c),s.enabled===!1&&r.set(c,d);s.required===!0&&s.enabled!==!1&&l.length>0&&i.push({keys:l,label:d})}for(let s of Object.keys(e)){if(!o.has(s)){let d=a.length>0?` Expected one of: ${[...new Set(a)].join(", ")}.`:"";throw new v(`Unknown option '--${s}' for extension command '${n}'.${d}`,f.USAGE)}let l=r.get(s);if(l)throw new v(`Option '${l}' is disabled for extension command '${n}'.`,f.USAGE)}for(let s of i)if(!s.keys.some(l=>Object.hasOwn(e,l)))throw new v(`Missing required option '${s.label}' for extension command '${n}'.`,f.USAGE)}function Ra(e){return typeof e=="string"||e==null?e:String(e)}function Ia(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function $a(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var Pa={string:Ra,number:Ia,boolean:$a};function ot(e,t){return Array.isArray(e)?e.map(n=>ot(n,t)):Pa[t](e)}function lr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):Vn(e);return t?o.map(r=>ot(r,t)):o}function Na(e,t,n,o){return n?lr(e,t,o):t?ot(e,t):e}function Ma(e,t,n){let o=e[ir];if(!o||o.length===0)return n;let r=new Set(t);return o.filter(i=>r.has(i.key)).map(i=>i.value)}function cr(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[r,i]of Object.entries(e))o[r]=i;for(let r of t){let i=Ta(r);if(!i)continue;let a=r.list===!0,s=Oe(r);for(let c of s)if(!(c===i||!Object.hasOwn(o,c))){if(Object.hasOwn(o,i)){if(!a){delete o[c];continue}let m=o[i],p=o[c];o[i]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[c];continue}o[i]=o[c],delete o[c]}let l=ar(r),d=r.repeatable===!0;if(!Object.hasOwn(o,i)){r.default!==void 0&&(o[i]=Na(r.default,l,a,d));continue}if(a){o[i]=lr(Ma(n,s,o[i]),l,d);continue}l&&(o[i]=ot(o[i],l))}return o}function dr(e){let t=Object.create(null),n=[];Object.defineProperty(t,ir,{value:n});let o=0;for(;o<e.length;){let r=Gt(e,o);if(!r){o+=1;continue}let i=Te(r.key);if(i.length===0||nt(i)){o+=r.consumed;continue}Aa(t,i,r.value),n.push({...r,key:i}),o+=r.consumed}return t}function mr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=Gt(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function Bt(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let a of t){let s=ar(a);for(let l of Oe(a))n.add(l),s==="boolean"&&o.add(l)}if(n.size===0)return[...e];let r=[],i=0;for(;i<e.length;){if(e[i]==="--"){r.push(...e.slice(i+1));break}let a=Gt(e,i);if(a){let s=Te(a.key);if(n.has(s)){let l=e[i],d=o.has(s)&&!l.includes("=")?1:a.consumed;i+=d;continue}}r.push(e[i]),i+=1}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0186e30-9c25-5539-b778-1ef2ee21764a")}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]="1399e88f-710a-5e5c-b4b3-70e35ec401cf")}catch{}})();var pr=new WeakMap;function ur(e,t){pr.set(e,t)}function Q(e){return pr.get(e)}function fr(e){return e.length>0?[e[0]]:[]}function Fa(e){let t=["","Intent:",` ${e.why}`],n=fr(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(`
3
3
  `)}function Da(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(`
4
- `)}function gr(e,t){return t==="detailed"?Da(e):Ma(e)}function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var La={cal:"calendar",ctx:"context"};function Ua(e,t){return e.commands.find(n=>n.name()===t)??null}function ja(e,t){let n=e;for(let o of t){let r=Ua(n,o);if(!r)return null;n=r}return n}function Vt(e,t,n,o){let r=ja(e,t.split(" ").filter(i=>i.length>0));r&&r.addHelpText("after",gr(n,o))}function Kt(e){return e.includes("--explain")?"detailed":"compact"}function le(e){return e.includes("--all")||e.includes("--explain")}var hr={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 install ./my-package --project","pm 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 extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension 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 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 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 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 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 extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --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 extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension 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 extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension 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 extension catalog --project","pm extension 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 install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm 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 upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm 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."]},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-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-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-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-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 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?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",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:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","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 "All acceptance criteria met" --message "Close after verification"','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 --message "Claim for implementation"','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 takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","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 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task 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."]}},Bt={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-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."]};function qa(e){let t=N(e??"");return t?La[t]??t:""}function Ha(e){let t=qa(e);return t?hr[t]??Bt:Bt}function yr(e,t){let n=Ha(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:fr(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function za(){let e=se.filter(({lifecycle:n})=>n==="permanent"),t=se.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(" ")} (${ho(n)})`)].join(`
5
- `)}function Ga(e,t,n,o){let r=new Set(Bo);e.configureHelp({visibleCommands(i){let a=t.visibleCommands(i);return n?a.filter(s=>(Z(s)??X(s.name()))!=="internal"):i!==e?a:a.filter(s=>o.has(s))},visibleOptions(i){let a=t.visibleOptions(i);return i!==e||n?a:a.filter(s=>r.has(s.flags))}})}function Wa(e,t,n,o){let r=new Set(Jo("core")),i=e.createHelp();i.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let a=()=>`${i.formatHelp(e,i)}${o}
6
- `,s=t.visibleCommands(e);for(let c of s)Z(c)===void 0&&(c.name()==="help"||r.has(c.name()))&&n.add(c);for(let c of s)Z(c)==="core"&&(n.add(c),Ko(a()).within_budget||n.delete(c))}function wr(e,t=process.argv.slice(2)){let n=e.createHelp(),o=le(t),r=new Set;Ga(e,n,o,r);let i=Kt(t),a=gr(Bt,i);e.addHelpText("after",a),o&&e.addHelpText("after",za()),Wa(e,n,r,a);for(let[l,m]of Object.entries(hr))Vt(e,l,m,i);let s=N(P(t).commandPathTokens.join(" ")),c=Ee(s);if(c){Vt(e,c.parent,{why:c.description,examples:[c.example],tips:[`Action path: pm ${c.command}`,Ye(c.accepted_flags)]},i);return}let d=Je.filter(({parent:l})=>l===s);d.length>0&&Vt(e,s,{why:`Dispatches one declared positional action: ${d.map(({action:l})=>l).join("|")}.`,examples:d.map(({example:l})=>l),tips:[`Inspect one action directly with pm ${s} <action> --help --json.`]},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]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function _r(e,t){await No(e,{ok:t.ok,error:t.error,result:xe(),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 br(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await I(e.pmRoot);await Go({pmRoot:e.pmRoot,author:We(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function D(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function ee(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return D(t)}function K(e){let t=new Set,n=[];for(let o of e){let r=ee(o);r&&(t.has(r)||n.push(r),t.add(r))}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]="bb31fb1f-bf61-5eab-aa63-5d04fbac282f")}catch{}})();function it(e){let{why:t,title:n,...o}=e;return o}var Va=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Ba(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Va.has(e.code)}function Er(e){return`urn:pm-cli:error:${e}`}function x(e){return{...e,type:Er(e.code)}}var de={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},xr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},vr={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},ot={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Ka={guide:de,shell:de,completion:de,"completion-statuses":de,"completion-tags":de,"completion-types":de,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:xr,cal:xr,reindex:vr,"search-advanced":vr,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":ot,"dedupe-audit":ot,"dedupe-merge":ot,normalize:ot};function Ja(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Ka[t]}function Jt(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Ya(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 Xa(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 Yt(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function G(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let r=n.map(i=>({role:typeof i?.role=="string"?i.role.trim():"",value:typeof i?.value=="string"?i.value.trim():""})).filter(i=>i.role.length>0&&i.value.length>0);r.length>0&&(e.parsed_positionals=r);return}let o=Ya(n);o&&(e[t]=o)}function me(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Yt(t,"attempted_command",e.attempted_command),G(t,"normalized_args",e.normalized_args),G(t,"parsed_positionals",e.parsed_positionals),G(t,"provided_fields",e.provided_fields),G(t,"missing",e.missing),G(t,"missing_required_fields",e.missing_required_fields),G(t,"suggested_flags",e.suggested_flags),G(t,"allowed_values",e.allowed_values),G(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),Yt(t,"suggested_retry",e.suggested_retry),G(t,"suggested_retry_args",e.suggested_retry_args),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=Xa(e.fallback_candidates);return n&&(t.fallback_candidates=n),Yt(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Xt(e,t,n){n&&e.push(` ${t}: ${n}`)}function te(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function Qa(e){let t=me(e);if(!t)return[];let n=["Recovery bundle:"];if(Xt(n,"suggested_retry",t.suggested_retry),Xt(n,"attempted_command",t.attempted_command),te(n,"normalized_args",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(te(n,"provided_fields",t.provided_fields,", "),te(n,"missing",t.missing,", "),te(n,"missing_required_fields",t.missing_required_fields,", "),te(n,"suggested_flags",t.suggested_flags,", "),te(n,"allowed_values",t.allowed_values,", "),te(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}`),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Xt(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}function Sr(e){let t=[`Error: ${e.title}`,"","What is required:",` ${e.required}`];e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...Jt("Next steps:",e.nextSteps))),t.push("","What happened:",` ${e.happened}`),e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...Jt("Examples:",e.examples))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...Jt("Verification errors:",e.verificationErrors)));let n=Qa(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
7
- `)}function Ar(e,t){return Ba(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 Za(e,t){return e.flag?e.flag:e.recovery?.provided_fields?.find(n=>n!=="--json"&&n!=="--quiet"&&t.includes(n))}function es(e,t,n){if(e.value!==void 0)return e.value;if(n)return t[t.indexOf(n)+1];let o=e.recovery?.allowed_values;if(o?.length)return t.find((r,i)=>i>0&&!r.startsWith("-")&&!o.includes(r))}function ts(e,t){let n=e.recovery?.normalized_args??[],o=Za(e,n),r=es(e,n,o);return{surface:o??e.recovery?.missing?.[0]??Tr(e.recovery)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function ns(e,t){return Ar({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:ts(e,t)},e)}function Zt(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;return yo(ns(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function en(e){return Ar({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function at(e){return e.replace(/\(outputHelp\)/g,"").trim()}function os(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 ne(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 Cr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Tr(e){return tr(e?.normalized_args)}function rs(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 is(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let i of o){let a=n.findIndex(s=>s===i);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=r,R(s)}}}function as(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function rt(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function W(e,t,n){if(!n)return e;let o=at(t),r=rt(n.code,e.code),i=rt(n.type,Er(r)),a=ne(n.examples)??e.examples,s=ne(n.nextSteps)??e.nextSteps,c=ne(n.verification_errors)??e.verificationErrors,d=e.code==="command_failed"&&n.code?as(o):void 0,l=me(n.recovery),m=l&&e.recovery?me({...e.recovery,...l}):l??e.recovery;return{...e,code:r,type:i,title:d??e.title,happened:o.length>0?o:e.happened,required:rt(n.required,e.required),why:rt(n.why,e.why),examples:a,nextSteps:s,verificationErrors:c,flag:n.flag,value:n.value,unmatchedSelectors:n.unmatched_selectors,availableDependencies:n.available_dependencies,recovery:m}}function ss(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 r=o[1],i=Xn(process.cwd(),r);return W(x(i?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${i}.`,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 ${i} <command>`,`PM_PATH=${i} pm <command>`],nextSteps:[`Re-run with "--pm-path ${i}" or export PM_PATH=${i}.`]}:{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 cs(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],i=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),a=i?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return W(x({code:"item_not_found",title:"Item ID not found",happened:a,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:i?["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 ls(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:W(x({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 ds(e,t,n){return t.includes("is locked")?W(x({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function ms(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let i=!!r,a=i?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",c=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return W(x({code:"missing_required_option",title:i?"Missing required options":`Missing required option ${s}`,happened:t,required:i?"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 ps(e,t,n){return t.startsWith("No update flags provided")?W(x({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 us(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=me(n?.recovery),r=Tr(o),i=r?`pm ${r} --help`:"pm <command> --help",a=rs(t),s=me({...o,allowed_values:o?.allowed_values??a}),c=is(o,a),d=c?[c,i]:[i,"pm contracts --command <command> --flags-only --json"],l=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${i}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return W(x({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:d,nextSteps:l,recovery:s}),e,n)}function tn(e,t){let n=at(e),o=ss(e,n,t)??cs(e,n,t)??ls(e,n,t)??ds(e,n,t)??ms(e,n,t)??ps(e,n,t)??us(e,n,t);return o||W(x({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 fs(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 gs(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function hs(e){if(!(!Array.isArray(e)||e.length===0))return R(e)}function nn(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 L(e,t={}){let n=nn(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:hs(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return me({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:i,...t})}function Qt(e,t){return!t||e.includes(t)?e:[...e,t]}var ys=new Set(["--add","--add-json","--remove"]),ws=new Set(["command","cmd","path"]);function _s(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(ys.has(o))return o}}function bs(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 r=e[o];if(r!=="--add"&&r!=="--remove")continue;let i=e[o+1];if(typeof i!="string"||!ws.has(i))return;let a=[];for(let d=o+2;d<e.length;d+=1){let l=e[d];if(l.startsWith("--")&&l.length>2)break;a.push(l)}if(a.length<2)return;let s=`${i}=${a.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return R(c)}}function xs(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let i=gs(r[1]),a=i.startsWith("--type"),s=o?.suggestedRetryCommand,c=nn(o?.providedOptionFlags),d=[i],l=fs(t,i,n),m=s?Qt(l,s):l,p=a?[`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?Qt(p,`Replay with preserved arguments: ${s}`):p,g=c&&c.length>0?Qt(u,`Already provided options: ${c.join(", ")}`):u;return x({code:"missing_required_option",title:`Missing required option ${i}`,happened:`Commander rejected the command because ${i} was not provided.`,required:`Pass ${i} with a valid value before running the command.`,why:a?"--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:g,recovery:L(o,{missing:d})})}function vs(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return x({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:L(n,{missing:[r]})})}function Cs(e,t,n){return x({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:L(t,{suggested_flags:n})})}var ks={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 Es(e){let t=ne(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Ss(e,t,n,o,r){let i=o.otherCommands.slice(0,3),a=o.candidateTotal-i.length,s=a>0?` and ${String(a)} 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.length?`${e} is accepted by ${i.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,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,r?`Replay with suggested correction: ${r}`:void 0].filter(c=>typeof c=="string")}function As(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},i=o[1],a=nn(r.unknownOptionSuggestions)??[],s=r.suggestedRetryCommand;if(t==="update"&&(i==="--file"||i==="--doc"))return Cs(i,n,a);let c=Es(r),d=Ss(i,t,a,c,s),l=[s,`pm ${t??"<command>"} --help`].filter(m=>typeof m=="string");return x({code:"unknown_option",title:`Unknown option ${i}`,happened:`Commander does not recognize option ${i} for this command path.`,required:ks[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",examples:l,nextSteps:d,recovery:L(n,{suggested_flags:a.length>0?a:void 0,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function Ts(e,t,n,o,r){let i=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return x({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:Cr([t.installCommand,...n]),nextSteps:Cr([i,...a]),recovery:L(r)})}function Os(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=ne(t?.unknownCommandExamples),i=ne(t?.unknownCommandNextSteps),a=Ja(o),s=r??["pm --help"],c=i??["Verify spelling and active extensions, then rerun."],d=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),l=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!l||!d.has(l))?Ts(o,a,s,c,t):x({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:L(t)})}function Rs(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ne(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return x({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${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:[...r?[r]:[],`pm ${t} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:L(e,{allowed_values:o,suggested_retry:r})})}function Is(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=_s(o);if(!r)return null;let i=bs(o);return x({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} 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:[...i?[i]:[],'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:[...i?[`Replay with the value re-joined into one argument: ${i}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:L(n,i?{suggested_retry:i}:{})})}var $s=new Set(["comments","docs","files","learnings","notes","test"]);function Ps(e,t,n){if(!/too many arguments/i.test(e)||!$s.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>d===t),i=o[r+1],a=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(i?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return x({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:L(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:c})})}var Ns=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"]),kr=new Set(["context","ctx"]);function Fs(e,t,n){if(!/too many arguments/i.test(e)||!kr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>kr.has(d)),i=r===-1?1:r+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let d=!1;for(let l of o.slice(i)){if(d){d=!1;continue}let m=l.split("=")[0];if(Ns.has(m)){d=!l.includes("=");continue}if(!l.startsWith("-")){s=l;break}}}if(!s)return null;let c=`pm get ${s}`;return x({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:L(n,{suggested_retry:c})})}function on(e,t,n,o){let r=at(e),i=xs(r,t,n,o)??vs(r,t,o)??As(r,t,o)??Os(r,o)??Rs(o)??Ps(r,t,o)??Is(r,t,o)??Fs(r,t,o);return i||x({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:L(o)})}function Or(e,t){let n=tn(e,t);return Tt(Sr(n),n.required).output}function Rr(e,t){return en(tn(e,t))}function rn(e,t,n){return Zt(tn(e,n),t)}function Ir(e,t,n,o){let r=on(e,t,n,o);return Tt(Sr(r),r.required).output}function an(e,t,n,o){return en(on(e,t,n,o))}function st(e,t,n,o,r){return Zt(on(e,t,n,r),o)}function $r(e,t){let n=Pr(e);return Zt(n,t)}function Pr(e){let t=at(e);return os(t)?x({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."]}):x({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 Nr(e){return en(Pr(e))}import{Option as Ms}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]="99d39b7c-ec26-5c95-85c0-ac28112a6fe6")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Mr(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let i of t){if(i.layer!==o.layer||i.name!==o.name)continue;let a=_(i.command),s=a.split(" "),c=s.at(-1),d=s.slice(1).join(" "),l=d?`${s[0]}-${c} ${d}`:`${s[0]}-${c}`;if(c&&r===l){n.set(r,a);break}}}return n}function sn(e,t,n,o){if(!t||!n)return;let r,i=0;for(let[s,c]of e.entries()){if(c!==t)continue;let d=e.slice(s);for(let[l,m]of o.entries()){let p=l.split(" ");p.length>i&&p.every((u,g)=>d[g]===u)&&(r=m,i=p.length)}}let a=r?.flags.find(s=>s.long===n||s.short===n);if(a)return ct(a).takesValue}function A(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function V(e){return typeof e=="boolean"?e:void 0}function ct(e){let t=A(e.value_type)??A(e.type),n=A(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||V(e.required)===!0||V(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function Ds(e){if(V(e.visible)===!1)return null;let n=A(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=A(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",i=A(e.value_name),a=i?` <${i}>`:"",s=A(e.description)??"Extension-provided option.",c=[];V(e.required)===!0&&c.push("required"),V(e.enabled)===!1&&c.push("disabled");let d=c.length>0?` [${c.join(", ")}]`:"";return`${r}${n}${a} ${s}${d}`}function Dr(e){let t=[...new Set(e.map(Ds).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
4
+ `)}function gr(e,t){return t==="detailed"?Da(e):Fa(e)}function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var La={cal:"calendar",ctx:"context"};function Ua(e,t){return e.commands.find(n=>n.name()===t)??null}function ja(e,t){let n=e;for(let o of t){let r=Ua(n,o);if(!r)return null;n=r}return n}function Vt(e,t,n,o){let r=ja(e,t.split(" ").filter(i=>i.length>0));r&&r.addHelpText("after",gr(n,o))}function Jt(e){return e.includes("--explain")?"detailed":"compact"}function ce(e){return e.includes("--all")||e.includes("--explain")}var hr={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 install ./my-package --project","pm 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 extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension 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 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 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 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 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 extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --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 extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension 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 extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension 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 extension catalog --project","pm extension 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 install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm 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 upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm 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."]},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-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-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-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-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 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?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",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:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","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 "All acceptance criteria met" --message "Close after verification"','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 --message "Claim for implementation"','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 takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","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 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task 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."]}},Kt={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-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."]};function qa(e){let t=N(e??"");return t?La[t]??t:""}function Ha(e){let t=qa(e);return t?hr[t]??Kt:Kt}function yr(e,t){let n=Ha(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:fr(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function za(){let e=se.filter(({lifecycle:n})=>n==="permanent"),t=se.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(" ")} (${yo(n)})`)].join(`
5
+ `)}function Ga(e,t,n,o){let r=new Set(Ko);e.configureHelp({visibleCommands(i){let a=t.visibleCommands(i);return n?a.filter(s=>(Q(s)??X(s.name()))!=="internal"):i!==e?a:a.filter(s=>o.has(s))},visibleOptions(i){let a=t.visibleOptions(i);return i!==e||n?a:a.filter(s=>r.has(s.flags))}})}function Wa(e,t,n,o){let r=new Set(Yo("core")),i=e.createHelp();i.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let a=()=>`${i.formatHelp(e,i)}${o}
6
+ `,s=t.visibleCommands(e);for(let l of s)Q(l)===void 0&&(l.name()==="help"||r.has(l.name()))&&n.add(l);for(let l of s)Q(l)==="core"&&(n.add(l),Jo(a()).within_budget||n.delete(l))}function wr(e,t=process.argv.slice(2)){let n=e.createHelp(),o=ce(t),r=new Set;Ga(e,n,o,r);let i=Jt(t),a=gr(Kt,i);e.addHelpText("after",a),o&&e.addHelpText("after",za()),Wa(e,n,r,a);for(let[c,m]of Object.entries(hr))Vt(e,c,m,i);let s=N(P(t).commandPathTokens.join(" ")),l=Ee(s);if(l){Vt(e,l.parent,{why:l.description,examples:[l.example],tips:[`Action path: pm ${l.command}`,Xe(l.accepted_flags)]},i);return}let d=Ye.filter(({parent:c})=>c===s);d.length>0&&Vt(e,s,{why:`Dispatches one declared positional action: ${d.map(({action:c})=>c).join("|")}.`,examples:d.map(({example:c})=>c),tips:[`Inspect one action directly with pm ${s} <action> --help --json.`]},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]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function _r(e,t){await Mo(e,{ok:t.ok,error:t.error,result:xe(),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 br(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await I(e.pmRoot);await Wo({pmRoot:e.pmRoot,author:Be(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function D(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function ee(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return D(t)}function K(e){let t=new Set,n=[];for(let o of e){let r=ee(o);r&&(t.has(r)||n.push(r),t.add(r))}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]="ca79853d-468c-5522-b5f9-6509c66e3d9b")}catch{}})();function at(e){let{why:t,title:n,...o}=e;return o}var Ba=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Va(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Ba.has(e.code)}function Er(e){return`urn:pm-cli:error:${e}`}function x(e){return{...e,type:Er(e.code)}}var de={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},xr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},vr={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},rt={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Ka={guide:de,shell:de,completion:de,"completion-statuses":de,"completion-tags":de,"completion-types":de,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:xr,cal:xr,reindex:vr,"search-advanced":vr,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":rt,"dedupe-audit":rt,"dedupe-merge":rt,normalize:rt};function Ja(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Ka[t]}function Yt(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Ya(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 Xa(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 Xt(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function G(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let r=n.map(i=>({role:typeof i?.role=="string"?i.role.trim():"",value:typeof i?.value=="string"?i.value.trim():""})).filter(i=>i.role.length>0&&i.value.length>0);r.length>0&&(e.parsed_positionals=r);return}let o=Ya(n);o&&(e[t]=o)}function me(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Xt(t,"attempted_command",e.attempted_command),G(t,"normalized_args",e.normalized_args),G(t,"parsed_positionals",e.parsed_positionals),G(t,"provided_fields",e.provided_fields),G(t,"missing",e.missing),G(t,"missing_required_fields",e.missing_required_fields),G(t,"suggested_flags",e.suggested_flags),G(t,"allowed_values",e.allowed_values),G(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),Xt(t,"suggested_retry",e.suggested_retry),G(t,"suggested_retry_args",e.suggested_retry_args),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=Xa(e.fallback_candidates);return n&&(t.fallback_candidates=n),Xt(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Zt(e,t,n){n&&e.push(` ${t}: ${n}`)}function te(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function Za(e){let t=me(e);if(!t)return[];let n=["Recovery bundle:"];if(Zt(n,"suggested_retry",t.suggested_retry),Zt(n,"attempted_command",t.attempted_command),te(n,"normalized_args",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(te(n,"provided_fields",t.provided_fields,", "),te(n,"missing",t.missing,", "),te(n,"missing_required_fields",t.missing_required_fields,", "),te(n,"suggested_flags",t.suggested_flags,", "),te(n,"allowed_values",t.allowed_values,", "),te(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}`),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Zt(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}function Sr(e){let t=[`Error: ${e.title}`,"","What is required:",` ${e.required}`];e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...Yt("Next steps:",e.nextSteps))),t.push("","What happened:",` ${e.happened}`),e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...Yt("Examples:",e.examples))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...Yt("Verification errors:",e.verificationErrors)));let n=Za(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
7
+ `)}function Ar(e,t){return Va(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 Qa(e,t){if(e.flag)return e.flag;let n=r=>{let i=r.split("=",1)[0];return Ae([i]).length>0&&!["--help","--no-changed-fields","--version"].includes(i)&&t.some(a=>a===i||a.startsWith(`${i}=`))},o=[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(r=>r[0]).find(r=>n(r));return o||e.recovery?.provided_fields?.map(r=>r.split("=",1)[0]).find(r=>n(r))}function es(e,t,n){if(e.value!==void 0)return e.value;if(n){let r=t.find(a=>a===n||a.startsWith(`${n}=`));if(r?.startsWith(`${n}=`))return r.slice(n.length+1);let i=t.indexOf(n);return i>=0?t[i+1]:void 0}let o=e.recovery?.allowed_values;if(o?.length)return t.find((r,i)=>i>0&&!r.startsWith("-")&&!o.includes(r))}function ts(e,t){let n=e.recovery?.normalized_args??[],o=Qa(e,n),r=es(e,n,o);return{surface:o??e.recovery?.missing?.[0]??Tr(e.recovery)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function ns(e,t){return Ar({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:ts(e,t)},e)}function en(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;return wo(ns(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function tn(e){return Ar({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function st(e){return e.replace(/\(outputHelp\)/g,"").trim()}function os(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 ne(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 Cr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Tr(e){return tr(e?.normalized_args)}function rs(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 is(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let i of o){let a=n.findIndex(s=>s===i);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=r,A(s)}}}function as(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function it(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function W(e,t,n){if(!n)return e;let o=st(t),r=it(n.code,e.code),i=it(n.type,Er(r)),a=ne(n.examples)??e.examples,s=ne(n.nextSteps)??e.nextSteps,l=ne(n.verification_errors)??e.verificationErrors,d=e.code==="command_failed"&&n.code?as(o):void 0,c=me(n.recovery),m=c&&e.recovery?me({...e.recovery,...c}):c??e.recovery;return{...e,code:r,type:i,title:d??e.title,happened:o.length>0?o:e.happened,required:it(n.required,e.required),why:it(n.why,e.why),examples:a,nextSteps:s,verificationErrors:l,flag:n.flag,value:n.value,unmatchedSelectors:n.unmatched_selectors,availableDependencies:n.available_dependencies,recovery:m}}function ss(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 r=o[1],i=Zn(process.cwd(),r);return W(x(i?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${i}.`,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 ${i} <command>`,`PM_PATH=${i} pm <command>`],nextSteps:[`Re-run with "--pm-path ${i}" or export PM_PATH=${i}.`]}:{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 ls(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],i=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),a=i?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return W(x({code:"item_not_found",title:"Item ID not found",happened:a,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:i?["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 cs(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:W(x({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 ds(e,t,n){return t.includes("is locked")?W(x({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function ms(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let i=!!r,a=i?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",l=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return W(x({code:"missing_required_option",title:i?"Missing required options":`Missing required option ${s}`,happened:t,required:i?"Provide every required option for this command invocation.":l,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 ps(e,t,n){return t.startsWith("No update flags provided")?W(x({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 us(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=me(n?.recovery),r=Tr(o),i=r?`pm ${r} --help`:"pm <command> --help",a=rs(t),s=me({...o,allowed_values:o?.allowed_values??a}),l=is(o,a),d=l?[l,i]:[i,"pm contracts --command <command> --flags-only --json"],c=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${i}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return W(x({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:d,nextSteps:c,recovery:s}),e,n)}function nn(e,t){let n=st(e),o=ss(e,n,t)??ls(e,n,t)??cs(e,n,t)??ds(e,n,t)??ms(e,n,t)??ps(e,n,t)??us(e,n,t);return o||W(x({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 fs(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 gs(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function hs(e){if(!(!Array.isArray(e)||e.length===0))return A(e)}function on(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 L(e,t={}){let n=on(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:hs(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return me({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:i,...t})}function Qt(e,t){return!t||e.includes(t)?e:[...e,t]}var ys=new Set(["--add","--add-json","--remove"]),ws=new Set(["command","cmd","path"]);function _s(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(ys.has(o))return o}}function bs(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 r=e[o];if(r!=="--add"&&r!=="--remove")continue;let i=e[o+1];if(typeof i!="string"||!ws.has(i))return;let a=[];for(let d=o+2;d<e.length;d+=1){let c=e[d];if(c.startsWith("--")&&c.length>2)break;a.push(c)}if(a.length<2)return;let s=`${i}=${a.join(" ")}`,l=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return A(l)}}function xs(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let i=gs(r[1]),a=i.startsWith("--type"),s=o?.suggestedRetryCommand,l=on(o?.providedOptionFlags),d=[i],c=fs(t,i,n),m=s?Qt(c,s):c,p=a?[`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?Qt(p,`Replay with preserved arguments: ${s}`):p,g=l&&l.length>0?Qt(u,`Already provided options: ${l.join(", ")}`):u;return x({code:"missing_required_option",title:`Missing required option ${i}`,happened:`Commander rejected the command because ${i} was not provided.`,required:`Pass ${i} with a valid value before running the command.`,why:a?"--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:g,recovery:L(o,{missing:d})})}function vs(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return x({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:L(n,{missing:[r]})})}function Cs(e,t,n){return x({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:L(t,{suggested_flags:n})})}var ks={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 Es(e){let t=ne(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Ss(e,t,n,o,r){let i=o.otherCommands.slice(0,3),a=o.candidateTotal-i.length,s=a>0?` and ${String(a)} 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.length?`${e} is accepted by ${i.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,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,r?`Replay with suggested correction: ${r}`:void 0].filter(l=>typeof l=="string")}function As(e,t){if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};let n=e.normalizedInvocationArgs;if(n===void 0)return{};if(n.filter(i=>i===t||i.startsWith(`${t}=`)).length!==1)return{};let o=n.findIndex(i=>i===t||i.startsWith(`${t}=`));if(o<0||n.includes("--")||!n[o]?.includes("=")&&o!==n.length-1&&n[o+1]?.startsWith("-")!==!0)return{};let r=Ae(n.filter((i,a)=>a!==o));return{retryCommand:A(r),suggestedRetryArgs:r}}function Ts(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},i=o[1],a=on(r.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=As(r,i);if(t==="update"&&(i==="--file"||i==="--doc"))return Cs(i,n,a);let d=Es(r),c=Ss(i,t,a,d,s),m=[s,`pm ${t??"<command>"} --help`].filter(p=>typeof p=="string");return x({code:"unknown_option",title:`Unknown option ${i}`,happened:`Commander does not recognize option ${i} for this command path.`,required:ks[d.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:i,value:i,examples:m,nextSteps:c,recovery:L(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:l,candidate_commands:d.otherCommands,candidate_commands_total:d.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:d.optionScope})})}function Os(e,t,n,o,r){let i=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return x({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:Cr([t.installCommand,...n]),nextSteps:Cr([i,...a]),recovery:L(r)})}function Rs(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=ne(t?.unknownCommandExamples),i=ne(t?.unknownCommandNextSteps),a=Ja(o),s=r??["pm --help"],l=i??["Verify spelling and active extensions, then rerun."],d=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),c=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!c||!d.has(c))?Os(o,a,s,l,t):x({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:l,recovery:L(t)})}function Is(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ne(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return x({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${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:[...r?[r]:[],`pm ${t} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:L(e,{allowed_values:o,suggested_retry:r})})}function $s(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=_s(o);if(!r)return null;let i=bs(o);return x({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} 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:[...i?[i]:[],'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:[...i?[`Replay with the value re-joined into one argument: ${i}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:L(n,i?{suggested_retry:i}:{})})}var Ps=new Set(["comments","docs","files","learnings","notes","test"]);function Ns(e,t,n){if(!/too many arguments/i.test(e)||!Ps.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>d===t),i=o[r+1],a=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(i?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let l=`pm ${t} ${s} --add <value>`;return x({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:[l,`pm ${t} --help`],recovery:L(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:l})})}var Ms=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"]),kr=new Set(["context","ctx"]);function Fs(e,t,n){if(!/too many arguments/i.test(e)||!kr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>kr.has(d)),i=r===-1?1:r+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let d=!1;for(let c of o.slice(i)){if(d){d=!1;continue}let m=c.split("=")[0];if(Ms.has(m)){d=!c.includes("=");continue}if(!c.startsWith("-")){s=c;break}}}if(!s)return null;let l=`pm get ${s}`;return x({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 ${l} 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:[l,`pm context --parent ${s}`],recovery:L(n,{suggested_retry:l})})}function rn(e,t,n,o){let r=st(e),i=xs(r,t,n,o)??vs(r,t,o)??Ts(r,t,o)??Rs(r,o)??Is(o)??Ns(r,t,o)??$s(r,t,o)??Fs(r,t,o);return i||x({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:L(o)})}function Or(e,t){let n=nn(e,t);return Ot(Sr(n),n.required).output}function Rr(e,t){return tn(nn(e,t))}function an(e,t,n){return en(nn(e,n),t)}function Ir(e,t,n,o){let r=rn(e,t,n,o);return Ot(Sr(r),r.required).output}function sn(e,t,n,o){return tn(rn(e,t,n,o))}function lt(e,t,n,o,r){return en(rn(e,t,n,r),o)}function $r(e,t){let n=Pr(e);return en(n,t)}function Pr(e){let t=st(e);return os(t)?x({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."]}):x({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 Nr(e){return tn(Pr(e))}import{Option as Ds}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]="99d39b7c-ec26-5c95-85c0-ac28112a6fe6")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Fr(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let i of t){if(i.layer!==o.layer||i.name!==o.name)continue;let a=_(i.command),s=a.split(" "),l=s.at(-1),d=s.slice(1).join(" "),c=d?`${s[0]}-${l} ${d}`:`${s[0]}-${l}`;if(l&&r===c){n.set(r,a);break}}}return n}function ln(e,t,n,o){if(!t||!n)return;let r,i=0;for(let[s,l]of e.entries()){if(l!==t)continue;let d=e.slice(s);for(let[c,m]of o.entries()){let p=c.split(" ");p.length>i&&p.every((u,g)=>d[g]===u)&&(r=m,i=p.length)}}let a=r?.flags.find(s=>s.long===n||s.short===n);if(a)return ct(a).takesValue}function T(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function B(e){return typeof e=="boolean"?e:void 0}function ct(e){let t=T(e.value_type)??T(e.type),n=T(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||B(e.required)===!0||B(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function Ls(e){if(B(e.visible)===!1)return null;let n=T(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=T(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",i=T(e.value_name),a=i?` <${i}>`:"",s=T(e.description)??"Extension-provided option.",l=[];B(e.required)===!0&&l.push("required"),B(e.enabled)===!1&&l.push("disabled");let d=l.length>0?` [${l.join(", ")}]`:"";return`${r}${n}${a} ${s}${d}`}function Dr(e){let t=[...new Set(e.map(Ls).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
8
8
  Extension-provided flags:
9
9
  ${t.join(`
10
- `)}`}function Lr(e){let t=new Map;for(let r of e){let i=_(r.target_command);if(i.length===0)continue;let a=t.get(i)??[];a.push(...r.flags),t.set(i,a)}let n=[...t.entries()].sort(([r],[i])=>r.localeCompare(i)),o=new Map;for(let[r,i]of n){let a=Dr(i);a&&o.set(r,a)}return o}function Ur(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Fr(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}function Ls(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 Us(e){let t=new Map;for(let n of e){let o=_(n.command);if(o.length===0)continue;let r=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,i=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:Ur(o,n.action),description:r,intent:i,examples:Fr(n.examples),failure_hints:Fr(n.failure_hints),arguments:Ls(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",source:{layer:n.layer,name:n.name,package:n.source_package}})}return t}function js(e){let t=new Map;for(let n of e){let o=_(n.target_command);if(o.length===0)continue;let r=t.get(o)??[];r.push(...n.flags),t.set(o,r)}return t}function qs(e,t,n){let o=new Set;for(let r of e){let i=_(r);i.length>0&&o.add(i)}for(let r of t.keys())o.add(r);for(let r of n.keys())o.add(r);return o}function Hs(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function jr(e,t,n,o=new Map){let r=Us(t),i=js(n),a=qs(e,r,i),s=new Map,c=[...a].sort((d,l)=>d.localeCompare(l));for(let d of c){let l=Hs(d,r,o)??r.get(d),m=i.get(d)??(l?i.get(l.command):void 0)??[];if(l){s.set(d,{...l,command:d,flags:m});continue}s.set(d,{command:d,action:Ur(d,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function zs(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function qr(e,t){for(let n of t.arguments)e.argument(zs(n),n.description??"Extension argument.")}function Hr(e){if(V(e.visible)===!1)return null;let n=A(e.long),o=A(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,i=n&&n.startsWith("--")&&n.length>2?n:null,a=[r,i].filter(s=>s!==null);return a.length>0?a:null}function Gs(e){let t=Hr(e);if(!t)return null;let{valueName:n}=ct(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Ws(e){let t=Hr(e);if(!t)return null;let{valueName:n}=ct(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function zr(e){let t=A(e.description)??"Extension-provided option.",n=[];V(e.required)===!0&&n.push("required"),V(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function Gr(e,t){let n=A(t.long),o=A(t.short);return e.options.some(r=>{let i=r;return n!==null&&i.long===n||o!==null&&i.short===o})}function cn(e,t){for(let n of t){if(Gr(e,n))continue;let o=Ws(n);if(!o)continue;let r=zr(n);if(n.list!==!0){e.option(o,r);continue}e.addOption(new Ms(o,r).argParser((i,a=[])=>[...Array.isArray(a)?a:[a],i]))}}function ln(e,t){return Dr(t.filter(n=>!Gr(e,n)))}function Vs(e){let t=Gs(e);if(!t)return null;let n=A(e.long),o=A(e.short),r=n&&n.startsWith("--")&&n.length>2?n:null,i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:a,valueName:s}=ct(e),c=V(e.required)===!0;return{flags:t,long:r,short:i,description:zr(e),takes_value:a,value_required:a,value_name:s,variadic:!1,required:c,aliases:[],alias_for:null}}function Wr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let r=Vs(o);!r||n.has(r.flags)||(n.add(r.flags),t.push(r))}return t}function Vr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(r=>r.flags));for(let r of t)o.has(r.flags)||(o.add(r.flags),n.push(r));return n}function Br(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:`
10
+ `)}`}function Lr(e){let t=new Map;for(let r of e){let i=_(r.target_command);if(i.length===0)continue;let a=t.get(i)??[];a.push(...r.flags),t.set(i,a)}let n=[...t.entries()].sort(([r],[i])=>r.localeCompare(i)),o=new Map;for(let[r,i]of n){let a=Dr(i);a&&o.set(r,a)}return o}function Ur(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Mr(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}function Us(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 js(e){let t=new Map;for(let n of e){let o=_(n.command);if(o.length===0)continue;let r=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,i=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:Ur(o,n.action),description:r,intent:i,examples:Mr(n.examples),failure_hints:Mr(n.failure_hints),arguments:Us(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",source:{layer:n.layer,name:n.name,package:n.source_package}})}return t}function qs(e){let t=new Map;for(let n of e){let o=_(n.target_command);if(o.length===0)continue;let r=t.get(o)??[];r.push(...n.flags),t.set(o,r)}return t}function Hs(e,t,n){let o=new Set;for(let r of e){let i=_(r);i.length>0&&o.add(i)}for(let r of t.keys())o.add(r);for(let r of n.keys())o.add(r);return o}function zs(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function jr(e,t,n,o=new Map){let r=js(t),i=qs(n),a=Hs(e,r,i),s=new Map,l=[...a].sort((d,c)=>d.localeCompare(c));for(let d of l){let c=zs(d,r,o)??r.get(d),m=i.get(d)??(c?i.get(c.command):void 0)??[];if(c){s.set(d,{...c,command:d,flags:m});continue}s.set(d,{command:d,action:Ur(d,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function Gs(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function qr(e,t){for(let n of t.arguments)e.argument(Gs(n),n.description??"Extension argument.")}function Hr(e){if(B(e.visible)===!1)return null;let n=T(e.long),o=T(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,i=n&&n.startsWith("--")&&n.length>2?n:null,a=[r,i].filter(s=>s!==null);return a.length>0?a:null}function Ws(e){let t=Hr(e);if(!t)return null;let{valueName:n}=ct(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Bs(e){let t=Hr(e);if(!t)return null;let{valueName:n}=ct(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function zr(e){let t=T(e.description)??"Extension-provided option.",n=[];B(e.required)===!0&&n.push("required"),B(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function Gr(e,t){let n=T(t.long),o=T(t.short);return e.options.some(r=>{let i=r;return n!==null&&i.long===n||o!==null&&i.short===o})}function cn(e,t){for(let n of t){if(Gr(e,n))continue;let o=Bs(n);if(!o)continue;let r=zr(n);if(n.list!==!0){e.option(o,r);continue}e.addOption(new Ds(o,r).argParser((i,a=[])=>[...Array.isArray(a)?a:[a],i]))}}function dn(e,t){return Dr(t.filter(n=>!Gr(e,n)))}function Vs(e){let t=Ws(e);if(!t)return null;let n=T(e.long),o=T(e.short),r=n&&n.startsWith("--")&&n.length>2?n:null,i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:a,valueName:s}=ct(e),l=B(e.required)===!0;return{flags:t,long:r,short:i,description:zr(e),takes_value:a,value_required:a,value_name:s,variadic:!1,required:l,aliases:[],alias_for:null}}function Wr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let r=Vs(o);!r||n.has(r.flags)||(n.add(r.flags),t.push(r))}return t}function Br(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(r=>r.flags));for(let r of t)o.has(r.flags)||(o.add(r.flags),n.push(r));return n}function Vr(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:`
11
11
  Extension command metadata:
12
12
  ${t.join(`
13
- `)}`}function dn(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 Oe(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:dn(o).includes(n))??null}function pe(e,t){let n=e;for(let o of t){let r=Oe(n,o);if(!r)return null;n=r}return n}var Kr=new WeakSet;function Jr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let r=t[o],i=Oe(n,r);if(i){n=i;continue}let a=n.command(r);Kr.add(a),o<t.length-1?(a.description("Extension-provided command group."),a.action(()=>{a.help()})):a.description("Extension-provided command path."),n=a}return n}function Bs(e,t){let n=e,o=[];for(let r of t){let i=Oe(n,r);if(!i)return null;if(o.push(r),!Kr.has(i))return{core_path:o.join(" "),extension_path:t.join(" ")};n=i}return null}function Ks(e,t,n,o){let r=t.split(" ").filter(s=>s.length>0),i=Bs(e,r);if(!i||i.core_path===t&&!n.has(t))return null;let a=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${i.extension_path}:core_owner=pm-cli:${i.core_path}:extension_owner=${a}`}function Yr(e,t,n,o,r){return[...new Set([...t,...n.keys()])].filter(i=>i.trim().length>0).sort((i,a)=>i.localeCompare(a)).filter(i=>{let a=Ks(e,i,o,n.get(i));return a?(r(a),!1):!0})}function Xr(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33842ea7-43c9-52a3-a9ec-75f190a5fd6f")}catch{}})();function Js(e,t){let n=we(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Ys(e){return we(e.status)?.toLowerCase()??"pending"}function Xs(e){return e.mandatory===!0}function Qs(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 ei(e){let t=[];return e.forEach((n,o)=>{if(!Xs(n.definition))return;let r=Ys(n.definition);r!=="applied"&&t.push({layer:n.layer,name:n.name,id:Js(n.definition,o),status:r})}),t.sort(Qs),t}function Qr(e){return Array.isArray(e)&&e.length>0}var Zs=new Set(["create","beads import","todos import"]),ec=new Set(["restore","update","close","delete","append","claim","release"]),tc=new Set(["comments","notes","learnings"]),nc=new Set(["files","docs","test"]),oc=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 mn(e,t){let n=t.force===!0;return Zs.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:ec.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:tc.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:nc.has(e)?{isMutation:Qr(t.add)||Qr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function rc(e,t,n){if(mn(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Io(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(r=>oc.has(r.trim().toLowerCase())):!1}function Zr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function ic(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let r=[];if(we(t[1])||r.push("source"),we(n.to)||r.push("--to"),r.length!==0)throw new v(`Schema migration requires ${r.join(", ")}.`,f.USAGE,{code:"schema_migration_input_required",required:r.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:r,suggested_flags:r.filter(i=>i.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function ac(e,t,n,o,r){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Zr(n.status)!==Zr(r.schema.workflow.in_progress_status))return;let i=t[0];if(!i)return;let a=J(r,Y()),s=await Ke(o,i,r.id_prefix,r.item_format,a.type_to_folder);if(!s)return;let c=await Ao(s,{schema:r.schema}),d=typeof n.assignee=="string"?n.assignee.trim():void 0;(d===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(d.toLowerCase())&&d)||y(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function pn(e,t,n,o,r){if(!rc(e,t,n)||(ic(e,t,n),!await q(H(r))))return;let i=await ce(r);o.json!==!0&&await ac(e,t,n,r,i.settings);let a=Ro({author:We(o.author,i.settings.author_default),payload:{command:e,args:t,options:n},settings:i.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)y(`warning:${s}`)}function ti(e,t,n){if(n.length===0)return;let o=mn(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let r=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),i=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new v(`Write command "${e}" blocked by unresolved mandatory extension migrations (${r.join(",")}). ${i}`,f.CONFLICT)}async function un(e,t,n,o){if(!mn(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await q(H(n)))return;let{settings:i,metadata:a,warnings:s}=await ce(n);for(let c of s)y(`warning:${c}`);if(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(Eo(i),await So(n,i,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let c=J(i,Y());await $o(n,i.item_format,"item_format:pre_mutation_sync",c.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]="adb5b95f-be2d-5bcf-b376-09f6094e0bda")}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]="8879d491-9158-548c-bfbd-8ab57d8eb936")}catch{}})();var Re=Jn.join("|"),sc={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"},cc={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"]}},ni=["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 lc(e,t){let n=cc[e];if(!n)return[];let o=D(t);for(let[r,i]of Object.entries(n))if(D(r)===o)return i;return[]}function fn(e,t,n){if(n.length===0)return e;if(t){let a=n.find(s=>s.declared_command_match===!0);return JSON.stringify({...JSON.parse(e),...a?{extension_command_failure:{code:"extension_command_activation_failed",extension:a.name,layer:a.layer,error:a.error,recovery_commands:a.recovery_commands??[]}}:{},failed_extensions:n},null,2)}let o=n.map(a=>`- ${a.layer}:${a.name}: ${a.error}`).join(`
13
+ `)}`}function mn(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 Re(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:mn(o).includes(n))??null}function pe(e,t){let n=e;for(let o of t){let r=Re(n,o);if(!r)return null;n=r}return n}var Kr=new WeakSet;function Jr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let r=t[o],i=Re(n,r);if(i){n=i;continue}let a=n.command(r);Kr.add(a),o<t.length-1?(a.description("Extension-provided command group."),a.action(()=>{a.help()})):a.description("Extension-provided command path."),n=a}return n}function Ks(e,t){let n=e,o=[];for(let r of t){let i=Re(n,r);if(!i)return null;if(o.push(r),!Kr.has(i))return{core_path:o.join(" "),extension_path:t.join(" ")};n=i}return null}function Js(e,t,n,o){let r=t.split(" ").filter(s=>s.length>0),i=Ks(e,r);if(!i||i.core_path===t&&!n.has(t))return null;let a=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${i.extension_path}:core_owner=pm-cli:${i.core_path}:extension_owner=${a}`}function Yr(e,t,n,o,r){return[...new Set([...t,...n.keys()])].filter(i=>i.trim().length>0).sort((i,a)=>i.localeCompare(a)).filter(i=>{let a=Js(e,i,o,n.get(i));return a?(r(a),!1):!0})}function Xr(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33842ea7-43c9-52a3-a9ec-75f190a5fd6f")}catch{}})();function Ys(e,t){let n=we(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Xs(e){return we(e.status)?.toLowerCase()??"pending"}function Zs(e){return e.mandatory===!0}function Qs(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 ei(e){let t=[];return e.forEach((n,o)=>{if(!Zs(n.definition))return;let r=Xs(n.definition);r!=="applied"&&t.push({layer:n.layer,name:n.name,id:Ys(n.definition,o),status:r})}),t.sort(Qs),t}function Zr(e){return Array.isArray(e)&&e.length>0}var el=new Set(["create","beads import","todos import"]),tl=new Set(["restore","update","close","delete","append","claim","release"]),nl=new Set(["comments","notes","learnings"]),ol=new Set(["files","docs","test"]),rl=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 pn(e,t){let n=t.force===!0;return el.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:tl.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:nl.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:ol.has(e)?{isMutation:Zr(t.add)||Zr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function il(e,t,n){if(pn(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return $o(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(r=>rl.has(r.trim().toLowerCase())):!1}function Qr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function al(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let r=[];if(we(t[1])||r.push("source"),we(n.to)||r.push("--to"),r.length!==0)throw new v(`Schema migration requires ${r.join(", ")}.`,f.USAGE,{code:"schema_migration_input_required",required:r.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:r,suggested_flags:r.filter(i=>i.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function sl(e,t,n,o,r){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Qr(n.status)!==Qr(r.schema.workflow.in_progress_status))return;let i=t[0];if(!i)return;let a=J(r,Y()),s=await Je(o,i,r.id_prefix,r.item_format,a.type_to_folder);if(!s)return;let l=await To(s,{schema:r.schema}),d=typeof n.assignee=="string"?n.assignee.trim():void 0;(d===void 0?l.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(d.toLowerCase())&&d)||y(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function un(e,t,n,o,r){if(!il(e,t,n)||(al(e,t,n),!await q(H(r))))return;let i=await le(r);o.json!==!0&&await sl(e,t,n,r,i.settings);let a=Io({author:Be(o.author,i.settings.author_default),payload:{command:e,args:t,options:n},settings:i.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)y(`warning:${s}`)}function ti(e,t,n){if(n.length===0)return;let o=pn(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let r=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),i=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new v(`Write command "${e}" blocked by unresolved mandatory extension migrations (${r.join(",")}). ${i}`,f.CONFLICT)}async function fn(e,t,n,o){if(!pn(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await q(H(n)))return;let{settings:i,metadata:a,warnings:s}=await le(n);for(let l of s)y(`warning:${l}`);if(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(So(i),await Ao(n,i,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let l=J(i,Y());await Po(n,i.item_format,"item_format:pre_mutation_sync",l.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]="adb5b95f-be2d-5bcf-b376-09f6094e0bda")}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]="8879d491-9158-548c-bfbd-8ab57d8eb936")}catch{}})();var Ie=Yn.join("|"),ll={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"},cl={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"]}},ni=["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 dl(e,t){let n=cl[e];if(!n)return[];let o=D(t);for(let[r,i]of Object.entries(n))if(D(r)===o)return i;return[]}function gn(e,t,n){if(n.length===0)return e;if(t){let a=n.find(s=>s.declared_command_match===!0);return JSON.stringify({...JSON.parse(e),...a?{extension_command_failure:{code:"extension_command_activation_failed",extension:a.name,layer:a.layer,error:a.error,recovery_commands:a.recovery_commands??[]}}:{},failed_extensions:n},null,2)}let o=n.map(a=>`- ${a.layer}:${a.name}: ${a.error}`).join(`
14
14
  `),r=n.find(a=>a.declared_command_match===!0);if(!r)return`${e}
15
15
  Extension activation failures:
16
16
  ${o}`;let i=(r.recovery_commands??[]).map(a=>`- ${a}`).join(`
@@ -21,11 +21,11 @@ ${i}`:""}
21
21
 
22
22
  ${e}
23
23
  Extension activation failures:
24
- ${o}`}function gn(e){return P(e).commandPathTokens[0]??k(e)??"<command>"}function dc(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let r=o.shift();if(!r)continue;let i=N($(r)),a=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!a&&n.add(i),o.push(...r.commands)}for(let r of t.keys()){let i=N(r),a=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!a&&n.add(i)}return[...n].sort((r,i)=>r.localeCompare(i))}function oi(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let r=n.split(" ");if(n===o)return 0;if(r.includes(o))return 1;if(r.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let i=o.length>=5?2:1,a=Number.POSITIVE_INFINITY;for(let s of r){let c=Ct(s,o,i);c!==null&&(a=Math.min(a,c))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function ri(e){return D(e).slice(2).replace(/-/g,"")}function hn(e){return R(e)}function mc(e){let t=e.split(" ")[0]?.trim().toLowerCase();if(!t)return null;let n=sc[t];return n?`If this command comes from an optional package, install it with: pm install ${n}`:null}function ii(e){let t=Ho(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function pc(e,t){let n=ii(e);if(n.length===0)return[];let o=[];for(let r of t.values()){let i=new Set,a=r.source;if(a)for(let c of[a.name,a.package]){let d=ii(c??"");d.length>0&&i.add(d)}if(i.size===0)continue;[...i].some(c=>c===n||c.includes(n)||n.includes(c))&&o.push(r.command)}return[...new Set(o)].sort((r,i)=>r.localeCompare(i))}function Ie(e,t){let n=new Set,o=t??Xe(e);for(let r of o){r.flag.startsWith("--")&&n.add(D(r.flag));for(let i of r.aliases??[])i.startsWith("--")&&n.add(D(i))}return[...n].sort((r,i)=>r.localeCompare(i))}function uc(e,t){if(!e.startsWith("--"))return[];let n=ri(e);if(n.length===0)return[];let o=n.length>=8?2:1,r=[];for(let i of t){let a=ri(i);if(a===n)continue;if(n.length>=3&&a.startsWith(n)){r.push({flag:i,rank:0,distance:a.length-n.length});continue}let s=Ct(n,a,o);s===null||s<=0||r.push({flag:i,rank:1,distance:s})}return r.sort((i,a)=>i.rank!==a.rank?i.rank-a.rank:i.distance!==a.distance?i.distance-a.distance:i.flag.localeCompare(a.flag)).map(i=>i.flag).slice(0,3)}var lt,fc=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 gc(){if(lt)return lt;let e=new Map;for(let t of Be)if(!fc.has(t))for(let n of Ie(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return lt=e,lt}function hc(e,t){if(!e.startsWith("--"))return[];let n=gc().get(D(e));if(!n)return[];let o=t?.trim().toLowerCase(),r=new Set(Ie(o));return n.filter(i=>i!==o).map(i=>({command:i,sharedFlagCount:Ie(i).filter(a=>r.has(a)).length})).sort((i,a)=>i.sharedFlagCount!==a.sharedFlagCount?a.sharedFlagCount-i.sharedFlagCount:i.command.localeCompare(a.command)).map(({command:i})=>i)}function yc(e,t,n){for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--"))continue;let i=r.indexOf("="),a=i>=0?r.slice(0,i):r;if(D(a)!==D(t))continue;let s=[...e];return s[o]=i>=0?`${n}${r.slice(i)}`:n,s}}function wc(e){let t=new Set(e.commandPaths),n=i=>Math.min(oi(i,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?oi(i,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,r=(i,a)=>{if(!Number.isFinite(a)||!t.has(i))return;let s=o.get(i);(s===void 0||a<s)&&o.set(i,a)};for(let i of e.commandPaths)r(i,n(i));for(let[i,a]of Object.entries(go))i!=="read"&&r(a,n(i));return[...o.entries()].sort(([i,a],[s,c])=>a!==c?a-c:i.localeCompare(s)).map(([i])=>i)}function _c(e){let t=rr(e.commandPaths,e.primaryToken),n=wc(e),o=pc(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return ai([...t,...n,...o])}function bc(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function xc(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help"])]:[...new Set(["pm --help",...n])]}function yn(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let r=N(o[1]);if(r.length===0)return;let i=dc(t,n);if(i.length===0)return;let a=r.split(" ")[0],s=_c({commandPaths:i,normalizedUnknown:r,primaryToken:a,extensionDescriptors:n}),c=bc(i),d=(s.length>0?s:c).slice(0,3),l=xc(d,s.length>0),m=mc(r),p=s.length>0?`Did you mean: ${d.join(", ")}?`:null;return{unknownCommandExamples:l,unknownCommandNextSteps:[...p?[p]:[],'Run "pm --help" to list commands available in this runtime, including active extensions.',"Use one of the suggested command paths above with --help to inspect valid flags and usage.",...m?[m]:[]]}}function ai(e){return Array.from(new Set(e))}function vc(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 Cc(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 kc(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 wn(e,t){if(t.length===0)return!0;let n=e;for(let[o,r]of t.entries()){let i=kc(n,r);if(!i){if(n.commands.some(s=>s.name()!=="help"))return!1;let a=n.registeredArguments;return a.length>0&&(a.at(-1)?.variadic===!0||t.length-o<=a.length)}n=i}return!0}async function Ec(e,t,n,o){try{let r=E(process.cwd(),e.path);if(!await q(H(r)))return{allowedTypes:Re};let i=await I(r),a=e.noExtensions?void 0:Y(),s=J(i,a),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let d=n.findIndex(m=>m===o),l=n[d+2];if(n[d+1]?.toLowerCase()==="add"&&l!==void 0&&!l.startsWith("-"))try{c=(await Ke(r,l,i.id_prefix,i.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Re,pmRoot:r,settings:i,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:Re}}}function Sc(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?ai([...lc(t,n[1]),...uc(n[1],Ie(t))]):void 0,r=n?hc(n[1],t):[],i=n!==null&&Ie(t).includes(D(n[1]));return{match:n,suggestions:o,otherCommands:r,scope:i?"declared_on_path":r.length>0?"declared_elsewhere":"declared_nowhere"}}function Ac(e,t,n){if(!t||!n||n.length===0)return;let o=yc(e,t[1],n[0]);return o?hn(o):void 0}function Tc(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Cc(vc(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=k(t);if(r)return nr(t,r,[o])}function Oc(e,t){if(!/too many arguments/i.test(e)||k(t)!=="schema")return;let n=Qo(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let i=`${o}-${r}`;if(!ni.includes(i))return;let a=[...t.slice(0,n+1),i,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...ni],suggestedRetryCommand:hn(a)}}async function $e(e,t,n,o={}){let i=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",a=et(process.argv.slice(2)).argv,s=z(a),c=k(a),d=hn(a),l=K(a),m=await Ec(s,i,a,c),p=m.allowedTypes,u=yn(i,t,n),g=Sc(i,c),w=Oc(i,a),h=w?.suggestedRetryCommand??Ac(a,g.match,g.suggestions)??Tc(i,a);return{message:i,commandName:c,allowedTypes:p,attemptedCommand:d,normalizedInvocationArgs:[...a],providedOptionFlags:l,unknownOptionSuggestions:g.suggestions,unknownOptionOtherCommands:g.otherCommands.length>0?g.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:g.otherCommands.length>0?g.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:g.otherCommands.length>12||void 0,unknownOptionScope:g.scope,suggestedRetryCommand:h,verifiedCollectionItemId:m.verifiedCollectionItemId,...w,...u,...o}}async function _n(e,t,n,o={}){let r=await $e(e,t,n,o),{message:i,commandName:a,allowedTypes:s,unknownCommandExamples:c,unknownCommandNextSteps:d,attemptedCommand:l,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:w,unknownOptionOtherCommandsTruncated:h,unknownOptionScope:C,unknownSubcommandPath:O,unknownSubcommandToken:j,unknownSubcommandAllowedValues:F,suggestedRetryCommand:re,verifiedCollectionItemId:bt,failedExtensions:je}=r,ye=Ir(i,a,s,{unknownCommandExamples:c,unknownCommandNextSteps:d,attemptedCommand:l,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:w,unknownOptionOtherCommandsTruncated:h,unknownOptionScope:C,unknownSubcommandPath:O,unknownSubcommandToken:j,unknownSubcommandAllowedValues:F,suggestedRetryCommand:re,verifiedCollectionItemId:bt,failedExtensions:je}),ie=await uo("help_format",{message:ye,command:a,allowed_types:s});return ie.handled&&typeof ie.result=="string"?ie.result:ye}async function bn(e,t,n,o=!1,r={}){let i=await $e(e,t,n,r),a=st(i.message,i.commandName,i.allowedTypes,f.USAGE,{unknownCommandExamples:i.unknownCommandExamples,unknownCommandNextSteps:i.unknownCommandNextSteps,attemptedCommand:i.attemptedCommand,normalizedInvocationArgs:i.normalizedInvocationArgs,providedOptionFlags:i.providedOptionFlags,unknownOptionSuggestions:i.unknownOptionSuggestions,unknownOptionOtherCommands:i.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:i.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:i.unknownOptionOtherCommandsTruncated,unknownOptionScope:i.unknownOptionScope,unknownSubcommandPath:i.unknownSubcommandPath,unknownSubcommandToken:i.unknownSubcommandToken,unknownSubcommandAllowedValues:i.unknownSubcommandAllowedValues,suggestedRetryCommand:i.suggestedRetryCommand,verifiedCollectionItemId:i.verifiedCollectionItemId,failedExtensions:i.failedExtensions});return JSON.stringify(o?it(a):a,null,2)}import ue from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function xn(e,t={},n=[]){let o={readSettings:I,loadExtensions:_e,activateExtensions:be,resolveImplicitPmRoot:Et,...t};try{let r=await o.readSettings(e),i=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(i);return[...i.failed,...a.failed].map(s=>{let c=(i.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),d=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(N).filter((p,u,g)=>p.length>0&&g.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),l=n.map(N),m=d.some(p=>l.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...d.length>0?{declared_commands:d}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function si(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await xn(t,n,o),i={readSettings:I,loadExtensions:_e,activateExtensions:be,resolveImplicitPmRoot:Et,...n};try{let a=i.resolveImplicitPmRoot(process.cwd());if(ue.resolve(a)===ue.resolve(t))return r;let[s,c]=await Promise.all([i.readSettings(t),i.readSettings(a)]),[d,l]=await Promise.all([i.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),i.loadExtensions({pmRoot:a,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(d.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(l.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,g)=>u.localeCompare(g));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${ue.resolve(t)} extension_discovery_root=${d.roots.project}; cwd_storage_root=${ue.resolve(a)} cwd_extension_discovery_root=${l.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 ${ue.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${ue.resolve(t)} install <package> --project".`})}catch{}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="43167bb0-7cc0-599f-8587-8583d398f1ad")}catch{}})();var ci={core:0,standard:1,full:2,internal:3};function li(e,t,n=!0){let o=t.get(e);if(o)return o;if(!n)return;let r=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(r.length===0)return;let i=r.reduce((s,c)=>ci[c.tier]<ci[s]?c.tier:s,"internal"),a=new Set(r.map(({family:s})=>s));return{tier:i,family:a.size===1?r[0].family:"extensions"}}function Rc(e,t){if(t.length===0)return e;let n=pe(e,t);if(n)return n;let o=t.join(" ");if(!Be.some(r=>r===o)&&!Do(o)&&!Ee(o))return null;for(let r=t.length-1;r>0;r-=1){let i=pe(e,t.slice(0,r));if(i)return i}return t.length===1?e:null}function Ic(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function di(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 $c(e){let t=new Map;for(let n of e){let o=n,r=di(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let i=t.get(r)??[];i.push(o.long.trim()),t.set(r,i)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,i)=>r.localeCompare(i)));return t}function Pc(e){return R(e)}function Nc(e){let t=e.options??[],n=$c(t);return t.map(o=>{let r=o,i=typeof r.flags=="string"?r.flags.trim():"",a=typeof r.description=="string"?r.description.trim():"",s=di(o),d=(s?n.get(s)??[]:[]).filter(h=>h!==r.long).map(h=>h.trim()).filter(h=>h.length>0),l=a.match(/^Alias for ([^ ]+)/i),m=l&&l[1]?l[1].trim():null,p=r.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),u=i.includes("<"),g=u||i.includes("["),w={flags:i,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:a,takes_value:g,value_required:u,value_name:Ic(i),variadic:r.variadic===!0,required:p,aliases:d,alias_for:m};return r.defaultValue!==void 0&&(w.default_value=r.defaultValue),w})}function Fc(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 r=o.alias_for,i=t.get(r);if(!i)continue;let a=o.long,s=new Set([...i.aliases??[],a]);i.aliases=[...s].sort((c,d)=>c.localeCompare(d))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Mc(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",i=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0||i?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:i}})}function Dc(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||(Z(i)??X(i.name()))!=="internal").map(i=>{let a=N($(i)),s=a.split(" ")[0],c=Z(i),d=li(a,t,c!==void 0),l=se.find(({alias:m})=>m===a);return{name:i.name().trim(),aliases:dn(i),description:i.description().trim(),tier:d?.tier??c??X(s),family:d?.family??Ze(s),...l?{alias_for:l.canonical,alias_lifecycle:l.lifecycle,...l.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((i,a)=>i.name.localeCompare(a.name))}function Lc(e,t,n){if(!n)return t;let o=n.examples??[],r=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"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function Uc(e,t){return e===void 0?null:t?.tier??X(e)}function jc(e,t){return e===void 0?null:t?.family??Ze(e)}function qc(e,t,n){if(!(t!==e||!n))return se.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function Hc(e,t,n,o,r=new Map,i=!1){if(!e){let s=Mc(t),c=Dc(t,r,i),d=new Set(c.map(({name:l})=>l));return{arguments:s,options:o,subcommands:[...c,...Je.filter(({parent:l,action:m})=>l===n&&!d.has(m)).map(({action:l,description:m})=>({name:l,aliases:[],description:m,tier:X(n.split(" ")[0]),family:Ze(n.split(" ")[0])}))].sort((l,m)=>l.name.localeCompare(m.name)),usage:[n,s.reduce((l,m)=>m.required?l.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):l,t.usage())].filter(l=>l.length>0).join(" ")}}let a=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:c,variadic:d,value_kind:l,polymorphic:m})=>({name:s,required:c,variadic:d,description:m?`Polymorphic ${l} value; inspect the action contract before mutation.`:`${l.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:c})=>s!==null&&a.has(s)||c.some(d=>a.has(d))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:c,variadic:d})=>{let l=d?`${s}...`:s;return c?`<${l}>`:`[${l}]`})].join(" ")}}function zc(e,t,n,o,r){let i=Kt(n),a=le(n),s=N($(t)),c=N(o.join(" ")),d=c.length>s.length?c:s,l=Ee(d),m=l?.command??d,p=m.length>0?m:void 0,u=p?.split(" ")[0],g=yr(p,i),w=p?r.get(p):void 0,h=p?li(p,r,Z(t)!==void 0):void 0,C=Lc(i,g,w),O=Fc(Vr(Nc(t),Wr(w))),j=Hc(l,t,m,O,r,a),F=qc(e,t,a);return{format:"pm_help_v1",detail_mode:i,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:Uc(u,h),capability_family:jc(u,h),description:l?.description??t.description(),usage:j.usage,intent:l?.description??C.intent,examples:l?[l.example]:C.examples,tips:l?[Ye(l.accepted_flags)]:C.tips,arguments:j.arguments,options:j.options,subcommands:j.subcommands,has_subcommands:j.subcommands.length>0,...F===void 0?{}:{command_aliases:F}}}async function mi(e,t,n){let o=z(t);if(!o.json)return!1;let r=P(t);if(!r.requested)return!1;let i=Rc(e,r.commandPathTokens);if(!i){if(!o.quiet){let a=`unknown command '${r.commandPathTokens.join(" ")}'`,s=yn(a,e,n),c=st(a,"help",Re,f.USAGE,{...s,attemptedCommand:Pc(t),normalizedInvocationArgs:[...t],providedOptionFlags:K(t)});y(JSON.stringify(c,null,2))}return process.exitCode=f.USAGE,!0}if(!o.quiet){let a=zc(e,i,t,r.commandPathTokens,n);ko(`${JSON.stringify(a,null,2)}
26
- `)}return process.exitCode=f.SUCCESS,!0}function Gc(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(`
27
- `)}function Wc(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)":"",r=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${r.length>0?r.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Vc(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let r of[...t.required_create_fields,...t.required_create_repeatables])o.add(r);return{progressive:n,strict:o}}function Bc(e,t,n,o){let r=new Set(n),i=o.filter(c=>!r.has(c)),a=c=>c.length>0?c.map(d=>kt("create",d)).join(", "):"none";e.push(` required in strict mode: ${a(i)}`);let s=i.map(Vo).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 Kc(e,t,n){let o=er(n);if(!o)return Gc(e,t);let r=Yn(o,t);if(!r){let w=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${w}`].join(`
28
- `)}let i=n.indexOf("--"),a=i<0?n:n.slice(0,i),s=a.findIndex(w=>w==="--create-mode"||w.startsWith("--create-mode=")),c=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],d=e==="create"&&c?.toLowerCase()==="strict",l=Vc(e,r),m=qe(r,e,l.progressive),p=qe(r,e,d?l.strict:l.progressive),u=w=>w.length>0?w.map(h=>kt(e,h)).join(", "):"none",g=["",`Type-aware option policies for ${r.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let w=qe(r,e,l.strict);Bc(g,r,m.required,w.required)}return Wc(g,r),p.errors.length>0&&g.push(` config errors: ${p.errors.join("; ")}`),g.join(`
29
- `)}function pi(e,t,n){let o=k(n);if(o!=="create"&&o!=="update")return;let r=Oe(e,o);r&&r.addHelpText("after",Kc(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]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function ui(e,t,n,o){if(n)return null;let r=e.some(a=>a==="--for"||a.startsWith("--for=")),i=k(e)==="contracts"&&e.includes("--full");return r||i?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f947c7f0-adf8-59da-8bc7-9cd746b05839")}catch{}})();var vn="PM_CLI_PACKAGE_ROOT",pt=Symbol.for("pm.readOutputInvocationProvenance");function $n(e,t){let n=Reflect.get(e,pt);n!==void 0&&Reflect.set(t,pt,n)}function bi(e,t,n){let o=_o(t,n);if(!o)return;let r=e;for(;r.parent;)r=r.parent;let i=r.rawArgs,a=new Set(K(i.slice(2))),s=wo.find(l=>l.command===o),c=Object.values(s.dimensions).flatMap(l=>l.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),d=Reflect.get(n,pt);Reflect.set(n,pt,{canonical_include_modes:d?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),$n(n,e)}function Yc(){return Bn(import.meta.url,["../.."])}(typeof process.env[vn]!="string"||process.env[vn]?.trim().length===0)&&(process.env[vn]=Yc());var ge=null,U=null;function Xc(e){ge=e}function Qc(e){T=e}var Zc=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"]),el=new Set(["parse","preflight","execute","unknown"]),tl=new Set(["usage","validation","conflict","runtime","unknown"]),Pe=null,oe=null,T=new Map,Pn=250,nl=new Set([f.USAGE,f.NOT_FOUND,f.CONFLICT]),ol=new Set(["1","true","yes","on"]),rl=ke(()=>import("./chunks/register-setup-33GNICLX.js")),il=ke(()=>import("./chunks/register-list-query-EUWM6VII.js")),al=ke(()=>import("./chunks/register-mutation-FD4HSAVU.js")),sl=ke(()=>import("./chunks/register-operations-HRMNFEC3.js"));function mt(e){return R(e)}function xi(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=>ee(o)??o))];return n.length>0?n:void 0}function cl(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=K(t),r=new Set(o.map(l=>ee(l)??l)),i=xi(e),a=t.find(l=>b.commands.some(m=>m.name()===l)),s=a?b.commands.find(l=>l.name()===a):void 0,c=new Set([...b.options,...s?.options??[]].flatMap(l=>l.flags.split(/[ ,|]+/).map(m=>ee(m)).filter(m=>m!==void 0))),d=i?.filter(l=>{let m=ee(l)??l;return r.has(m)?!1:c.has(m)||sn(t,a,m,T)!==void 0});return d&&d.length>0?d:void 0}function ll(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],i=r?ee(r):void 0,a=e.find(p=>b.commands.some(u=>u.name()===p)),s=a?b.commands.find(p=>p.name()===a):void 0,c=i?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(i)):void 0,d=sn(e,a,i,T),l=i?c?.isBoolean()===!0||d===!1?[i]:[i,"<value>"]:[],m=i?mt([...e,...l]):t;return m===t?void 0:m}function dl(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 r=e[o];r!=null&&(n[o]=r)}return n}function ml(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,...dl(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function vi(e,t,n){let o=Ve(t),r=o.includes("--explain"),i=e?.recovery,a=i&&o.includes("history-redact")?{...i,...i.attempted_command?{attempted_command:mt(o)}:{},...i.normalized_args?{normalized_args:[...o]}:{},...i.suggested_retry?{suggested_retry:mt(o)}:{},...i.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:i;if(a?.recovery_mode==="compact"&&!r)return{...e,recovery:a};let s=mt(o),c=K(o),d=cl(n,o,a),l=ll(o,s,d,a),m=ml({invocationArgv:o,attemptedCommand:s,providedFields:c,inferredMissing:d,suggestedRetry:l,existingRecovery:a});return{...e,recovery:m}}function fe(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function Ci(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Nn(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 ki(e){if(!e)return;let t=e.trim().toLowerCase();if(Zc.has(t))return t}function Ei(e){if(!e)return;let t=e.trim().toLowerCase();if(el.has(t))return t}function Si(e){if(!e)return;let t=e.trim().toLowerCase();if(tl.has(t))return t}function Ai(e){let t=fe(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(Ci(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=Nn(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let i=e?.run_results;if(Array.isArray(i)){let a=i.filter(s=>vt(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function Ti(e,t){if(!e)return t===f.USAGE?"invalid_command_usage":t===f.NOT_FOUND?"item_not_found":t===f.CONFLICT?"lock_conflict":t===f.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function Oi(){let e=vt(xe()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Nn(e,"exit_code","exitCode"),o=t??n??f.SUCCESS,r=Wo(o),i=fe(e,"error_code","errorCode")??Ti(r,o),a=Si(fe(e,"error_category","errorCategory"))??(r?void 0:xt(i)),s=r?void 0:Ai(e)??`command_exit_${o}`,c=ki(fe(e,"command_resolution","commandResolution"))??Rt({ok:r,errorCode:i,errorCategory:a}),d=Ei(fe(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:i,error_category:a,command_resolution:c,resolution_stage:d}}async function De(e){let t=U;U=null,await _r(t,e);let n=ge;if(ge=null,!n){ze();return}let o=[],r=mo();try{await br({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(i=>i.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await eo(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:xe(),affected:r}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{ze()}!n.globalOptions.json&&o.length>0&&y(`[pm] warning: afterCommand hook_warnings=${M(o)}`),n.profileEnabled&&o.length>0&&y(`profile:extensions hook_warnings=${M(o)}`)}async function Ri(){await To()}function Ii(e){return ol.has((process.env[e]??"").trim().toLowerCase())}function $i(e){return Ii("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!nl.has(Math.trunc(e))}async function ut(e){return $i(e.exit_code)?(await Ri(),Oo(e),!0):!1}async function Pi(e){let t=Q(e.error),n=Nr(t);e.bootstrapGlobal.json?y(JSON.stringify($r(t,f.GENERIC_FAILURE),null,2)):y(t),process.exitCode=f.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await Ri(),Pt(e.error);let i=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:f.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=i.errorCategory,r=i.commandResolution,ve(!1,t,{error_code:n.code,error_category:o,exit_code:f.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||y(`Failed to report error: ${Q(i)}`)}try{await De({ok:!1,error:t,exit_code:f.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${Q(i)}`)}try{await Ce()}catch(i){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${Q(i)}`)}}function fi(e,t,n,o){bi(e,t,o);let r=n.outputInclude;if(r===void 0)return;let{selectors:i,modes:a}=vo(t,r,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;$n(o,e);let s=xo(t);for(let d of a){let l=s.get(d),m=o[l];e.setOptionValueWithSource(l,m,"cli")}let c=i.length>0?i.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let d=e;d;d=d.parent)d.setOptionValueWithSource("outputInclude",c,"cli");Ft(e,n)}function Ne(e,t,n=[]){let r={...e.optsWithGlobals()};$n(e,r),delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let i=dr(t);for(let[a,s]of Object.entries(i))r[a]===void 0&&(r[a]=s);if(n.length>0){let a=sr(n),s=Xe($(e)).map(d=>({long:d.flag,short:d.short,aliases:d.aliases})),c={...i};for(let d of a)r[d]!==void 0&&(c[d]=r[d]);return Gt(c,[...s,...n],$(e)),lr(r,n,i)}return r}function En(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function ft(e,t,n){let o=En(e,t),r=[t],i=[];for(let a of n){if(a.startsWith("-"))break;r.push(a);let s=En(e,r.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function Fn(e){return e.arguments??[]}function gi(e){let t=Fn(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Ni(e,t){if(!e)return!1;let n=_(t);return e.importers.some(o=>_(`${o.importer} import`)===n)||e.exporters.some(o=>_(`${o.exporter} export`)===n)}function Fi(e,t){let n=Fn(e),o=n.filter(c=>c.required).length,i=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new v(`Missing required argument for extension command '${e.command}'. Usage: ${gi(e)}${s}`,f.USAGE);if(t.length>i){let c=t.slice(i).join(" ");throw new v(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${gi(e)}${s}`,f.USAGE)}}function pl(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function ul(e,t,n){if(n.length>0){Gt(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new v(`Unknown option '${o.map(pl).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,f.USAGE)}function Mi(e,t,n,o){e&&(Fi(e,t),ul(e,n,o))}var fl={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"},Cn=new Map;function Sn(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Di(e,t){return e.options.some(n=>n.long===t)}function Li(e,t){return e.options.some(n=>n.short===t)}function An(e,t,n,o){let r=t.trim();if(!r)return;let i=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Li(e,r))return;if(o){e.option(`${r} <value>`,`${i} (repeatable)`,Dt);return}e.option(`${r} <value>`,i);return}let a=r.startsWith("--")?r:`--${r}`;if(!Di(e,a)){if(o){e.option(`${a} <value>`,`${i} (repeatable)`,Dt);return}e.option(`${a} <value>`,i)}}async function Ui(e,t){let n=fl[e];if(!n)return[];let o=`${t}:${n}`,r=Cn.get(o);if(r)return r;if(!await q(H(t)))return Cn.set(o,[]),[];let i=await I(t),s=(At(i.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(l=>({long:`--${l}`,type:Sn(c.type),value_type:Sn(c.type)})));return Cn.set(o,s),s}async function ji(e,t){let n=z(t),o=E(process.cwd(),n.path);if(!await q(H(o)))return;let r=oe?.key===Ln(o)?oe.snapshot:null,i=r===null?await I(o):r.settings,a=At(i.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 d=pe(e,c.path.split(" "));if(d)for(let l of a.command_to_fields.get(c.command)??[]){let m=l.description??"";An(d,l.cli_flag,m,l.repeatable);for(let p of l.cli_aliases)An(d,p,`Alias for --${l.cli_flag}`,l.repeatable)}}}async function Mn(e,t,n,o,r){let i=k(n);if(!(i!=="create"&&i!=="update"))try{let a=r??await I(t),s=J(a,o);pi(e,s,n)}catch{}}function Tn(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function qi(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Dn(e){return e.some(t=>t==="--profile")}function Ln(e){return`pm-root:${e}`}function Hi(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Le(e){let t=_(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of Hi(e.commandArgs))o.push(...r.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n)]}function zi(e,t){let n=_(e);if(n.length===0)return!1;let o=Le(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function Un(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...S(n.commands),...S(n.command_handlers),...S(n.command_overrides),...S(n.flag_commands),...S(n.parser_overrides),...hi(n.preflight_ownership),...hi(n.renderer_ownership)]:[]}function S(e){return e??[]}function hi(e){return S(e).flatMap(t=>t.commands)}function gt(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Gi=new Set(["hooks","parser","preflight","renderers"]),Wi=new Set(["commands","schema","services","importers"]),gl=new Set(["reindex","search","search-advanced"]),hl=new Set(["--template"]);function Fe(e,t){for(let n of t)if(e.has(n))return!0;return!1}function Vi(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return gl.has(n??t)}function Bi(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 jn(e){return _(e.commandPath??"")==="create"&&Bi(e,hl)}function Ki(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function On(e,t){return e.some(n=>zi(n,t))||jn(t)&&Ki(e)}function Ji(e){return[S(e.hooks).length,(e.preflight_overrides??0)-S(e.preflight_ownership).length,S(e.item_types).length,S(e.item_fields).length,S(e.relationship_kinds).length,S(e.service_overrides).length,S(e.assurance_providers).length,S(e.renderer_overrides).length-S(e.renderer_ownership).length].some(n=>n>0)}function Yi(e,t){let n=e.activation?.commands??[];if(n.length>0)return On(n,t);let o=Un(e);if(On(o,t)||gt(e).has("search")&&Vi(t.commandPath))return!0;if(e.contributions)return Ji(e.contributions)}function qn(e,t){let n=Yi(e,t);if(n!==void 0)return n;let o=gt(e);return!!(Fe(o,Gi)||Fe(o,Wi))}function ht(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>qn(o,t)):e.effective.some(o=>{let r=gt(o);return Un(o).length>0||Fe(r,Gi)||Fe(r,Wi)||r.has("search")})}function Hn(e){let t=Le(e).filter(r=>r.split(" ").every(i=>!i.startsWith("-"))).sort((r,i)=>i.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=jn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Xi(e){return Hn(e)==="all"?void 0:t=>qn(t,e)}function Ue(e){let t=P(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...i]=t.commandPathTokens;return{commandPath:r,commandArgs:i,allowCommandPrefixMatch:!0}}let n=Xo(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Qi(e){let t=e.args.map(String);if(_($(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function Rn(e){for(let t of e)t.startsWith("settings_read_")&&y(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Zi(e,t){e.profile&&(y(`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&&y(`profile:extensions activation_warnings=${M(t.activationWarnings)}`))}function yt(e,t,n){if(!e)return;let o=_(n.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function wt(e,t=ce){let n=Ln(e);if(oe?.key===n)return oe.snapshot;try{let o=Date.now(),{settings:r,warnings:i}=await t(e),a=await to({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return oe={key:n,snapshot:s},s}catch{return oe={key:n,snapshot:null},null}}async function he(e,t,n=I){let o=t?Hn(t):"all",r=qi(e,o);if(Pe?.key===r)return Pe.snapshot;try{let i=await n(e),a=await _e({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Xi(t):void 0}),s=await be({...a,loaded:a.loaded}),c=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,g)=>u.localeCompare(g)),d=Lr(s.registrations.flags),l=Mr(s.commands.handlers,s.registrations.commands),m=jr(c,s.registrations.commands,s.registrations.flags,l),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:i,commandHandlers:c,commandFlagHelp:d,commandDescriptors:m,commandAliases:l,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:u,module:g})=>({name:u,module:g}))};return Pe={key:r,snapshot:p},p}catch{return Pe={key:r,snapshot:null},null}}async function ea(e){let t=Se(e);if(t.noExtensions){let a=E(process.cwd(),t.path);return await q(H(a))&&Rn((await ce(a)).warnings),null}let n=E(process.cwd(),t.path),o=await wt(n);if(!o)return null;Rn(o.settingsReadWarnings);let r={commandPath:$(e),commandArgs:Qi(e)};if(!ht(o.discovery,r))return yt(t.profile,o,r),null;let i=await he(n,r);return i?(Zi(t,i),{hooks:i.hooks,commands:i.commands,parsers:i.parsers,preflight:i.preflight,services:i.services,renderers:i.renderers,registrations:i.registrations,pmRoot:n}):null}async function ta(e){let t=await he(e);return t?new Map(t.commandDescriptors):T}async function na(e,t){return(await zo({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function oa(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return Lo(e,Yo.forActiveExtensionHost({pmRoot:e,author:n}))}async function ra(e,t,n,o=[]){let r=$(e),i=Wt(e.args.map(String),o),a={...t},s={...n},c=E(process.cwd(),n.path),d=await Ge({command:r,args:i,options:a,global:s,pm_root:c});n.profile&&d.warnings.length>0&&y(`profile:extensions parser_warnings=${M(d.warnings)}`),i=d.context.args,a=d.context.options,s=d.context.global,Mi(T.get(_(r)),i,a,o),ae(void 0),He({command:r,args:i,options:{...a},global:{...s},pm_root:c});let l=await St({command:r,args:i,options:a,global:s,pm_root:c,sdk:oa(c,s)});if(s.profile&&l.warnings.length>0&&y(`profile:extensions command_handler_warnings=${M(l.warnings)}`),!l.handled){if(l.warnings.length>0){let m=l.warnings[0],p=l.errorMessage?.trim(),u=p?` ${p}`:"";throw new v(`Command "${r}" failed in extension handler (${m}).${u}`,f.GENERIC_FAILURE,{code:l.errorCode??"command_failed",nextSteps:l.remediation?[l.remediation]:void 0})}throw new v(`Command "${r}" is provided by extensions and is not currently available.`,f.NOT_FOUND)}return l.exitCode!==void 0&&(process.exitCode=l.exitCode),ae(l.result),l.result}var yi=Symbol("pm.wrappedActionHandler");function yl(e,t){let n=e[e.length-1];return n instanceof In?n:t}function wi(e,t,n){e&&n.length>0&&y(`profile:extensions ${t}=${M(n)}`)}function wl(e){let t=T.get(_(e.commandPath));if(!t||!Ni(e.activeRegistrations,e.commandPath))return;let n=Fn(t).length===0?mr(e.commandArgs):Wt(e.commandArgs,e.extensionFlagDefinitions);Fi(t,n)}function _l(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 ia(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[yi]!==!0){let r=o._actionHandler;o._actionHandler=async function(...a){let s=yl(a,n),c=Date.now();Mt(s);let d=Se(s),l=$(s),m=E(process.cwd(),d.path),p=s.args.map(String),u=Y(),g=u?ft(u,l,p):[],w=await Ui(l,m),h=Ne(s,p,[...g,...w]),C=await Ge({command:l,args:p,options:h,global:d,pm_root:m});wi(d.profile,"parser_warnings",C.warnings),p=C.context.args,h=C.context.options,d=C.context.global,wl({activeRegistrations:u,commandPath:l,commandArgs:p,extensionFlagDefinitions:g}),d=await jo(d),Ft(s,d),_l(s,a,p),Qe(s,h),ae(void 0),He({command:l,args:p,options:{...h},global:{...d},pm_root:m});let O=await St({command:l,args:p,options:h,global:d,pm_root:m,sdk:oa(m,d)});if(wi(d.profile,"command_handler_warnings",O.warnings),O.handled){ae(O.result),Ot(O.result,{...d,command:l,commandArgs:p,commandOptions:h,pmRoot:m}),d.profile&&y(`profile:command=${l} took_ms=${Date.now()-c}`);return}return await r.apply(this,a)},o[yi]=!0}for(let r of n.commands)t(r)};t(e)}async function dt(e){T=new Map,B({overrides:[]}),e&&await Mn(e.rootProgram,e.pmRoot,e.invocationArgv,Qn(),e.settings)}function bl(e,t,n,o){if(t?.flags&&t.flags.length>0){cn(e,t.flags);let r=ln(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function aa(e,t,n){let o={core:0,standard:1,full:2,internal:3},r=(i,a)=>{let s=a.join(" "),c=[...n.entries()].filter(([l])=>l===s||l.startsWith(`${s} `)).map(([,l])=>l),d=c.length===0?"standard":c.reduce((l,m)=>o[m.tier]<o[l]?m.tier:l,"internal");ur(i,d);for(let l of i.commands)r(l,[...a,l.name()])};for(let i of e.commands)t.has(i.name())||r(i,[i.name()])}async function sa(e,t){let n=z(t),o=E(process.cwd(),n.path);if(n.noExtensions){await dt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await wt(o),i=Ue(t);if(!r){await dt();return}if(!ht(r.discovery,i)){await dt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),yt(Dn(t),r,i);return}let a=await he(o,i);if(!a){await dt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}B(a.services),T=new Map(a.commandDescriptors),await Mn(e,o,t,a.registrations,a.settings);let s=Yr(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,l=>Xr(a.activationWarnings,y,l)),c=new Set(e.commands.map(l=>l.name())),d=l=>{let m=l.split(" ").filter(O=>O.length>0),p=a.commandDescriptors.get(l),u=pe(e,m),g=a.commandFlagHelp.get(l),w=p?Br(p):null;if(u){bl(u,p,g,w);return}let h=Jr(e,m);p?.description&&h.description(p.description);let C=g;p&&(qr(h,p),p.flags.length>0&&(cn(h,p.flags),C=ln(h,p.flags)??void 0)),C&&h.addHelpText("after",C),w&&h.addHelpText("after",w),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...O)=>{let j=O[O.length-1],F=j instanceof In?j:h,re=Se(F),bt=Date.now(),je=ft(a.registrations,l,F.args.map(String)),ye=Ne(F,F.args.map(String),je),ie=await ra(F,ye,re,je);await qo(re,ie),Ot(ie,{...re,command:l,commandArgs:F.args.map(String),commandOptions:ye,pmRoot:o}),re.profile&&y(`profile:command=${l} took_ms=${Date.now()-bt}`)})};for(let l of s)d(l);aa(e,c,a.commandDescriptors)}var Me=Kn(import.meta.url,["../.."])??"0.0.0",b=Ht(Me);function ca(e){e.hook("preAction",async(t,n)=>{ge=null,U=null,ze(),Mt(n);let o=n.optsWithGlobals(),r=Se(n),i=$(n),a=n.args.map(String),s=Ne(n,a),c={...r};bo(i,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession,outputCursor:o.outputCursor}),fi(n,i,c,s),await Po(i,c);let d=E(process.cwd(),r.path),l=await ea(n);if(!l){ge=no({commandName:i,commandArgs:a,commandOptions:s,globalOptions:c,pmRoot:d}),U=await Nt({command:i,pm_version:Me,args:a,options:s,global:c,pm_root:d}),It(i,a,s,{source_context:U?.source_context,source_context_source:U?.source_context_source}),$t(i),await un(i,s,d,Tn()),await pn(i,a,s,c,d);return}oo(l.hooks),ro(l.commands),io(l.parsers),ao(l.preflight),B(l.services),so(l.renderers),co(l.registrations);let m=ft(l.registrations,i,a);s=Ne(n,a,m),fi(n,i,c,s);let p=await Ge({command:i,args:a,options:s,global:c,pm_root:l.pmRoot});c.profile&&p.warnings.length>0&&y(`profile:extensions parser_warnings=${M(p.warnings)}`),a=p.context.args,s=p.context.options,c=p.context.global,Qe(n,s);let u=await po({command:i,args:a,options:s,global:c,pm_root:l.pmRoot,decision:Tn()});c.profile&&u.warnings.length>0&&y(`profile:extensions preflight_warnings=${M(u.warnings)}`),a=u.context.args,s=u.context.options,c=u.context.global,Qe(n,s);let g=u.decision;await un(i,s,l.pmRoot,g),await pn(i,a,s,c,l.pmRoot);let w=g.run_extension_migrations?await na(l.registrations.migrations,l.pmRoot):[];c.profile&&w.length>0&&y(`profile:extensions migration_warnings=${M(w)}`);let h=ei(l.registrations.migrations);ge={hooks:l.hooks,commandName:i,commandArgs:a,commandOptions:{...s},globalOptions:{...c},pmRoot:l.pmRoot,profileEnabled:!!c.profile,migrationBlockers:h},ae(void 0),He({command:i,args:a,options:{...s},global:{...c},pm_root:l.pmRoot}),U=await Nt({command:i,pm_version:Me,args:a,options:s,global:c,pm_root:l.pmRoot}),It(i,a,s,{source_context:U?.source_context,source_context_source:U?.source_context_source}),$t(i);let C=await Zn(l.hooks,{command:i,args:a,options:{...s},global:{...c},pm_root:l.pmRoot});c.profile&&C.length>0&&y(`profile:extensions hook_warnings=${M(C)}`),g.enforce_mandatory_migration_gate&&ti(i,s,h)}),e.hook("postAction",async()=>{let t=Oi();ve(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await De(t)})}ca(b);var xl=new Set(["--version","-V"]),vl=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),la=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"]),da=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),Cl=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),kl=new Set(["claim","close-task","pause-task","release","start-task","test"]),kn={setup:!0,listQuery:!0,mutation:!0,operation:!0},El=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 _t(e){return e.some(t=>xl.has(t))}function ma(e){if(_t(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return kn;let t=k(e);if(!t)return kn;let n=t.trim().toLowerCase();return vl.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:la.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:da.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Cl.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:kn}function pa(e){return e.length===0||P(e).requested||e.includes("--explain")&&k(e)===void 0}var _i=Symbol("pmCliIdempotentTopLevelRegistration");function ua(e){let t=e;if(t[_i])return;t[_i]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let i=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===i||a.aliases().includes(i))?new In(i):n(o,...r)})}async function Sl(e,t){if(ua(e),t.setup){let{registerSetupCommands:n}=await rl();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await il(),o=typeof t.targetCommandName=="string"&&la.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await al();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await sl();n(e)}}function fa(e,t){return _t(t)?!1:le(t)||P(t).requested?!0:!!k(t)}function ga(e){if(_t(e))return!1;let t=k(e);return t?El.has(t):!1}function Al(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(d=>{let l=d.indexOf("=");return l>=0?d.slice(0,l):d}).find(d=>d==="--literal"||d==="--regex"||d==="--replacement"),i=r?e.argv.map(d=>{let l=d.indexOf("=");return(l>=0?d.slice(0,l):d)===o?l>=0?`${r}${d.slice(l)}`:r:d}):e.argv,a=Ve(i),s=r&&n>=0?`${o}=[redacted]`:t,c=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:c,sourceDisplay:s}}function ha(e){let t=e.commandName;if(!t)return;let n=e.trace.find(d=>d.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(d=>d.length>0),r=o.length>0?o.join(" "):"the canonical flag",i=da.has(t)||kl.has(t),a=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",c=Al({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new v(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,f.USAGE,{code:a,examples:[R(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:R(c.argv)}})}function Tl(e){return async t=>{let n=xt(t.errorCode),o=Rt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await Fo({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Me,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 ya(e){if(e.bootstrapGlobal.noExtensions)return;let t=Ue(e.invocationArgv),n=await wt(e.bootstrapPmRoot);if(n&&ht(n.discovery,t)){let o=await he(e.bootstrapPmRoot,t);wa(o);return}n&&yt(Dn(e.invocationArgv),n,t),B({overrides:[]})}function wa(e){if(!e){B({overrides:[]});return}B(e.services)}async function zn(e){ve(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await De({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 _a(){ve(!0,void 0,{exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await De({ok:!0,exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=f.SUCCESS}async function ba(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof v)&&(jt(e.error)||!n))return!1;let o=Q(e.error),r=e.error instanceof v?e.error.exitCode:Ut(t),i=e.error instanceof v?e.error.context:void 0,a=vi(i,e.invocationArgv,o),s=Rr(o,a),c=e.bootstrapGlobal.lean?it(rn(o,r,a)):rn(o,r,a),d=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?Co(c,u=>`${JSON.stringify(u,null,2)}
30
- `):c,null,2):Or(o,a);y(d);let{errorCategory:l,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await ut({command:e.attemptedCommand,error_code:s.code,error_category:l,exit_code:r,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:U?.source_context});return await zn({errorMessage:o,exitCode:r,classificationCode:s.code,errorCategory:l,commandResolution:m,resolutionStage:"execute"}),p&&(Pt(qt(e.error,o)),await Ce(Pn)),process.exitCode=r,!0}async function xa(e,t){let n=gn(e.invocationArgv),o=`unknown command '${n}'`,r=E(process.cwd(),e.bootstrapGlobal.path),i=await ta(r),a=Ue(e.invocationArgv),s=await xn(r,{},Le(a)),c=await $e({message:o},b,i,{failedExtensions:s}),d=an(c.message,c.commandName,c.allowedTypes,{unknownCommandExamples:c.unknownCommandExamples,unknownCommandNextSteps:c.unknownCommandNextSteps,attemptedCommand:c.attemptedCommand,normalizedInvocationArgs:c.normalizedInvocationArgs,providedOptionFlags:c.providedOptionFlags,unknownOptionSuggestions:c.unknownOptionSuggestions,suggestedRetryCommand:c.suggestedRetryCommand,failedExtensions:s}),{errorCategory:l,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:d.code,errorMessage:d.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await ut({command:n,error_code:d.code,error_category:l,exit_code:f.USAGE,error_message:d.detail,command_resolution:m,resolution_stage:"parse"}),u=e.jsonErrors?await bn({message:o},b,i,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await _n({message:o},b,i,{failedExtensions:s}),g=fn(u,e.jsonErrors,s);await zn({errorMessage:o,exitCode:f.USAGE,classificationCode:d.code,errorCategory:l,commandResolution:m,resolutionStage:"parse"}),y(g),p&&await Ce(Pn),process.exitCode=f.USAGE}async function va(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let r=P(e.invocationArgv);return r.requested&&!wn(b,r.commandPathTokens)?(await xa(e,t),!0):(await _a(),!0)}async function Ca(e,t){let n=await $e(e.error,b,T),o=an(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:r,commandResolution:i}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),a=await ut({command:e.attemptedCommand,error_code:o.code,error_category:r,exit_code:f.USAGE,error_message:o.detail,command_resolution:i,resolution_stage:"parse",source_context:U?.source_context}),s=e.jsonErrors?await bn(e.error,b,T,e.bootstrapGlobal.lean===!0):await _n(e.error,b,T),c=await si(o.code,e.bootstrapPmRoot,{},Le(Ue(e.invocationArgv))),d=fn(s,e.jsonErrors,c);await zn({errorMessage:n.message,exitCode:f.USAGE,classificationCode:o.code,errorCategory:r,commandResolution:i,resolutionStage:"parse"}),y(d),a&&await Ce(Pn),process.exitCode=f.USAGE}function ka(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 Ea(e){let t=e.error.code,n=String(e.error.message??"");if(!await va(e,t,n)){if(t==="commander.version"){await _a();return}await Ca(e,t)}}async function Gn(e){let t=z(e.invocationArgv),n=E(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:k(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:Tl({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await ya({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await ba(o,Lt(e.error))){if(ka(e.error)){await Ea(o);return}await Pi({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}async function Ol(e){b=Ht(Me),ca(b),Pe=null,oe=null,T=new Map,lo();let t=[...e],n,o;try{let r=et(e);t=r.argv;let i=[process.argv[0],process.argv[1],...t],a=t.length===0,s=z(t);if(s.authorMissingValue)throw new v("--author requires a non-empty value.",f.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});n=or(s.author),ha(r),o=Zo(t);let c=ma(t);if(await Sl(b,c),pa(t)&&wr(b,t),fa(b,t)?await sa(b,t):(T=new Map,B({overrides:[]})),ga(t)&&await ji(b,t),ia(b),await mi(b,t,T))return;let m=P(t);if(m.requested&&!wn(b,m.commandPathTokens))throw new Jc(f.USAGE,"commander.helpDisplayed","(outputHelp)");if(a||le(t)&&k(t)===void 0){b.outputHelp();return}let p=await I(E(process.cwd(),s.path)),u=await ui(t,E(process.cwd(),s.path),s.noExtensions,he);await Uo({pmRoot:E(process.cwd(),s.path),packages:u?.contextIntentPackages},()=>fo(p.agent_identity.harness_signals,()=>b.parseAsync(i),{probesEnabled:p.agent_identity?.probes_enabled}))}catch(r){await Gn({error:r,invocationArgv:t})}finally{o?.(),n?.()}}async function am(e=process.argv.slice(2)){try{await Mo(process.env,()=>Ol(e))}catch(t){await Gn({error:t,invocationArgv:[...e]})}}var sm={activationCommandMatchesProbe:zi,applyDynamicExtensionRootHelpVisibility:aa,bootstrapProfileEnabled:Dn,buildBootstrapActivationProbe:Ue,buildPostActionTelemetryOutcome:Oi,buildPmCliRecoveryContext:vi,buildRuntimeExtensionDiscoverySnapshotCacheKey:Ln,buildRuntimeExtensionActivationScope:Hn,buildRuntimeExtensionSnapshotCacheKey:qi,buildRuntimeExtensionFilterForProbe:Xi,addRuntimeFieldOption:An,collectActivationCommandCandidates:Le,collectExtensionFlagDefinitionsForCommand:En,collectExtensionFlagDefinitionsForInvocation:ft,collectLeadingCommandArgs:Hi,collectParsedActivationCommandArgs:Qi,collectRuntimeFieldLooseFlagDefinitionsForCommand:Ui,commandHasLongOption:Di,commandHasShortOption:Li,commandPathNeedsSearchExtensions:Vi,commandPathNeedsTemplateExtensions:jn,describeUnknownError:Q,defaultPreflightDecision:Tn,discoveryNeedsActivationForProbe:ht,emitExtensionProfile:Zi,emitExtensionSkippedProfile:yt,emitSettingsReadWarnings:Rn,ensureIdempotentTopLevelCommandRegistration:ua,enforceExplicitRetryForFlagTypos:ha,envFlagEnabled:Ii,executeRegisteredRuntimeMigrations:na,extractCommandScopedOptions:Ne,extensionActivationCommands:Un,extensionCapabilities:gt,extensionNeedsActivationForProbe:qn,extensionProvidesTemplatesRuntime:Ki,hasAnyCapability:Fe,hasGlobalExtensionContributions:Ji,handleGenericRunPmCliError:Pi,handleRunPmCliCommanderError:Ea,handleRunPmCliError:Gn,handleRunPmCliHelpDisplayError:va,handleRunPmCliKnownError:ba,handleRunPmCliCommanderUsageError:Ca,handleUnknownHelpCommandError:xa,inferMissingFieldsFromErrorMessage:xi,inferPostActionErrorCode:Ti,inferPostActionFailureMessage:Ai,invocationRequestsVersion:_t,isCommanderError:jt,loadRuntimeExtensionCommandDescriptorsForRecovery:ta,loadRuntimeExtensionDiscoverySnapshot:wt,loadRuntimeExtensionSnapshot:he,maybeLoadRuntimeExtensions:ea,maybeAttachCreateUpdatePolicyHelpText:Mn,maybeLogHandledCliErrorToSentry:ut,matchesStaticExtensionCommand:On,normalizeTelemetryCommandResolution:ki,normalizeTelemetryErrorCategory:Si,normalizeTelemetryResolutionStage:Ei,normalizeThrownExitCode:Ut,probeUsesAnyFlag:Bi,prepareExtensionServicesForRunPmCliError:ya,readRecordBoolean:Ci,readRecordNumber:Nn,readRecordString:fe,recordCliReadOutputInvocationProvenance:bi,registerDynamicExtensionCommandPaths:sa,registerRuntimeSchemaFieldFlags:ji,resolveCoreCommandRegistrationSelection:ma,resolveStaticExtensionActivationDecision:Yi,resolveUnknownHelpToken:gn,readThrownExitCode:Lt,runAndClearAfterCommandHooks:De,runRequiredExtensionCommand:ra,shouldAttachRichHelpTextForInvocation:pa,shouldLogHandledErrorToSentry:$i,shouldRegisterDynamicExtensionPaths:fa,shouldRegisterRuntimeSchemaFlags:ga,shouldHandleRunPmCliCommanderError:ka,setActiveExtensionHookContextForTest:Xc,setActiveRuntimeExtensionCommandDescriptorsForTest:Qc,setRecoveredExtensionServices:wa,toLooseFieldDefinitionType:Sn,isImporterOrExporterCommandPath:Ni,validateDynamicExtensionCommandInvocation:Mi,wrapProgramActionsForExtensionHandlers:ia,wrapThrownErrorForSentry:qt};export{sm as _testOnly,am as runPmCli};
24
+ ${o}`}function hn(e){return P(e).commandPathTokens[0]??k(e)??"<command>"}function ml(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let r=o.shift();if(!r)continue;let i=N($(r)),a=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!a&&n.add(i),o.push(...r.commands)}for(let r of t.keys()){let i=N(r),a=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!a&&n.add(i)}return[...n].sort((r,i)=>r.localeCompare(i))}function oi(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let r=n.split(" ");if(n===o)return 0;if(r.includes(o))return 1;if(r.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let i=o.length>=5?2:1,a=Number.POSITIVE_INFINITY;for(let s of r){let l=kt(s,o,i);l!==null&&(a=Math.min(a,l))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function ri(e){return D(e).slice(2).replace(/-/g,"")}function yn(e){return A(e)}function pl(e){let t=e.split(" ")[0]?.trim().toLowerCase();if(!t)return null;let n=ll[t];return n?`If this command comes from an optional package, install it with: pm install ${n}`:null}function ii(e){let t=zo(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function ul(e,t){let n=ii(e);if(n.length===0)return[];let o=[];for(let r of t.values()){let i=new Set,a=r.source;if(a)for(let l of[a.name,a.package]){let d=ii(l??"");d.length>0&&i.add(d)}if(i.size===0)continue;[...i].some(l=>l===n||l.includes(n)||n.includes(l))&&o.push(r.command)}return[...new Set(o)].sort((r,i)=>r.localeCompare(i))}function $e(e,t){let n=new Set,o=t??Ze(e);for(let r of o){r.flag.startsWith("--")&&n.add(D(r.flag));for(let i of r.aliases??[])i.startsWith("--")&&n.add(D(i))}return[...n].sort((r,i)=>r.localeCompare(i))}function fl(e,t){if(!e.startsWith("--"))return[];let n=ri(e);if(n.length===0)return[];let o=n.length>=8?2:1,r=[];for(let i of t){let a=ri(i);if(a===n)continue;if(n.length>=3&&a.startsWith(n)){r.push({flag:i,rank:0,distance:a.length-n.length});continue}let s=kt(n,a,o);s===null||s<=0||r.push({flag:i,rank:1,distance:s})}return r.sort((i,a)=>i.rank!==a.rank?i.rank-a.rank:i.distance!==a.distance?i.distance-a.distance:i.flag.localeCompare(a.flag)).map(i=>i.flag).slice(0,3)}var dt,gl=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 hl(){if(dt)return dt;let e=new Map;for(let t of Ke)if(!gl.has(t))for(let n of $e(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return dt=e,dt}function yl(e,t){if(!e.startsWith("--"))return[];let n=hl().get(D(e));if(!n)return[];let o=t?.trim().toLowerCase(),r=new Set($e(o));return n.filter(i=>i!==o).map(i=>({command:i,sharedFlagCount:$e(i).filter(a=>r.has(a)).length})).sort((i,a)=>i.sharedFlagCount!==a.sharedFlagCount?a.sharedFlagCount-i.sharedFlagCount:i.command.localeCompare(a.command)).map(({command:i})=>i)}function wl(e,t,n){for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--"))continue;let i=r.indexOf("="),a=i>=0?r.slice(0,i):r;if(D(a)!==D(t))continue;let s=[...e];return s[o]=i>=0?`${n}${r.slice(i)}`:n,s}}function _l(e){let t=new Set(e.commandPaths),n=i=>Math.min(oi(i,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?oi(i,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,r=(i,a)=>{if(!Number.isFinite(a)||!t.has(i))return;let s=o.get(i);(s===void 0||a<s)&&o.set(i,a)};for(let i of e.commandPaths)r(i,n(i));for(let[i,a]of Object.entries(ho))i!=="read"&&r(a,n(i));return[...o.entries()].sort(([i,a],[s,l])=>a!==l?a-l:i.localeCompare(s)).map(([i])=>i)}function bl(e){let t=rr(e.commandPaths,e.primaryToken),n=_l(e),o=ul(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return ai([...t,...n,...o])}function xl(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function vl(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help"])]:[...new Set(["pm --help",...n])]}function wn(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let r=N(o[1]);if(r.length===0)return;let i=ml(t,n);if(i.length===0)return;let a=r.split(" ")[0],s=bl({commandPaths:i,normalizedUnknown:r,primaryToken:a,extensionDescriptors:n}),l=xl(i),d=(s.length>0?s:l).slice(0,3),c=vl(d,s.length>0),m=pl(r),p=s.length>0?`Did you mean: ${d.join(", ")}?`:null;return{unknownCommandExamples:c,unknownCommandNextSteps:[...p?[p]:[],'Run "pm --help" to list commands available in this runtime, including active extensions.',"Use one of the suggested command paths above with --help to inspect valid flags and usage.",...m?[m]:[]]}}function ai(e){return Array.from(new Set(e))}function Cl(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 kl(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 El(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 _n(e,t){if(t.length===0)return!0;let n=e;for(let[o,r]of t.entries()){let i=El(n,r);if(!i){if(n.commands.some(s=>s.name()!=="help"))return!1;let a=n.registeredArguments;return a.length>0&&(a.at(-1)?.variadic===!0||t.length-o<=a.length)}n=i}return!0}async function Sl(e,t,n,o){try{let r=E(process.cwd(),e.path);if(!await q(H(r)))return{allowedTypes:Ie};let i=await I(r),a=e.noExtensions?void 0:Y(),s=J(i,a),l;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let d=n.findIndex(m=>m===o),c=n[d+2];if(n[d+1]?.toLowerCase()==="add"&&c!==void 0&&!c.startsWith("-"))try{l=(await Je(r,c,i.id_prefix,i.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Ie,pmRoot:r,settings:i,typeToFolder:s.type_to_folder,verifiedCollectionItemId:l}}catch{return{allowedTypes:Ie}}}function Al(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?ai([...dl(t,n[1]),...fl(n[1],$e(t))]):void 0,r=n?yl(n[1],t):[],i=n!==null&&$e(t).includes(D(n[1]));return{match:n,suggestions:o,otherCommands:r,scope:i?"declared_on_path":r.length>0?"declared_elsewhere":"declared_nowhere"}}function Tl(e,t,n){if(!t||!n||n.length===0)return;let o=wl(e,t[1],n[0]);return o?yn(o):void 0}function Ol(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?kl(Cl(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=k(t);if(r)return nr(t,r,[o])}function Rl(e,t){if(!/too many arguments/i.test(e)||k(t)!=="schema")return;let n=Zo(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let i=`${o}-${r}`;if(!ni.includes(i))return;let a=[...t.slice(0,n+1),i,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...ni],suggestedRetryCommand:yn(a)}}async function Pe(e,t,n,o={}){let i=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",a=tt(process.argv.slice(2)).argv,s=z(a),l=k(a),d=yn(a),c=K(a),m=await Sl(s,i,a,l),p=m.allowedTypes,u=wn(i,t,n),g=Al(i,l),w=Rl(i,a),h=w?.suggestedRetryCommand??Tl(a,g.match,g.suggestions)??Ol(i,a);return{message:i,commandName:l,allowedTypes:p,attemptedCommand:d,normalizedInvocationArgs:[...a],providedOptionFlags:c,unknownOptionSuggestions:g.suggestions,unknownOptionOtherCommands:g.otherCommands.length>0?g.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:g.otherCommands.length>0?g.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:g.otherCommands.length>12||void 0,unknownOptionScope:g.scope,suggestedRetryCommand:h,verifiedCollectionItemId:m.verifiedCollectionItemId,...w,...u,...o}}async function bn(e,t,n,o={}){let r=await Pe(e,t,n,o),{message:i,commandName:a,allowedTypes:s,unknownCommandExamples:l,unknownCommandNextSteps:d,attemptedCommand:c,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:w,unknownOptionOtherCommandsTruncated:h,unknownOptionScope:C,unknownSubcommandPath:R,unknownSubcommandToken:j,unknownSubcommandAllowedValues:M,suggestedRetryCommand:re,verifiedCollectionItemId:xt,failedExtensions:qe}=r,ye=Ir(i,a,s,{unknownCommandExamples:l,unknownCommandNextSteps:d,attemptedCommand:c,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:w,unknownOptionOtherCommandsTruncated:h,unknownOptionScope:C,unknownSubcommandPath:R,unknownSubcommandToken:j,unknownSubcommandAllowedValues:M,suggestedRetryCommand:re,verifiedCollectionItemId:xt,failedExtensions:qe}),ie=await fo("help_format",{message:ye,command:a,allowed_types:s});return ie.handled&&typeof ie.result=="string"?ie.result:ye}async function xn(e,t,n,o=!1,r={}){let i=await Pe(e,t,n,r),a=lt(i.message,i.commandName,i.allowedTypes,f.USAGE,{unknownCommandExamples:i.unknownCommandExamples,unknownCommandNextSteps:i.unknownCommandNextSteps,attemptedCommand:i.attemptedCommand,normalizedInvocationArgs:i.normalizedInvocationArgs,providedOptionFlags:i.providedOptionFlags,unknownOptionSuggestions:i.unknownOptionSuggestions,unknownOptionOtherCommands:i.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:i.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:i.unknownOptionOtherCommandsTruncated,unknownOptionScope:i.unknownOptionScope,unknownSubcommandPath:i.unknownSubcommandPath,unknownSubcommandToken:i.unknownSubcommandToken,unknownSubcommandAllowedValues:i.unknownSubcommandAllowedValues,suggestedRetryCommand:i.suggestedRetryCommand,verifiedCollectionItemId:i.verifiedCollectionItemId,failedExtensions:i.failedExtensions});return JSON.stringify(o?at(a):a,null,2)}import ue from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function vn(e,t={},n=[]){let o={readSettings:I,loadExtensions:_e,activateExtensions:be,resolveImplicitPmRoot:St,...t};try{let r=await o.readSettings(e),i=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(i);return[...i.failed,...a.failed].map(s=>{let l=(i.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),d=[...l?.contributions?.commands??[],...l?.contributions?.command_handlers??[],...l?.activation?.commands??[]].map(N).filter((p,u,g)=>p.length>0&&g.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),c=n.map(N),m=d.some(p=>c.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...d.length>0?{declared_commands:d}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function si(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await vn(t,n,o),i={readSettings:I,loadExtensions:_e,activateExtensions:be,resolveImplicitPmRoot:St,...n};try{let a=i.resolveImplicitPmRoot(process.cwd());if(ue.resolve(a)===ue.resolve(t))return r;let[s,l]=await Promise.all([i.readSettings(t),i.readSettings(a)]),[d,c]=await Promise.all([i.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),i.loadExtensions({pmRoot:a,settings:l,cwd:process.cwd(),noExtensions:!1})]),m=new Set(d.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(c.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,g)=>u.localeCompare(g));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${ue.resolve(t)} extension_discovery_root=${d.roots.project}; cwd_storage_root=${ue.resolve(a)} cwd_extension_discovery_root=${c.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 ${ue.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${ue.resolve(t)} install <package> --project".`})}catch{}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="43167bb0-7cc0-599f-8587-8583d398f1ad")}catch{}})();var li={core:0,standard:1,full:2,internal:3};function ci(e,t,n=!0){let o=t.get(e);if(o)return o;if(!n)return;let r=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(r.length===0)return;let i=r.reduce((s,l)=>li[l.tier]<li[s]?l.tier:s,"internal"),a=new Set(r.map(({family:s})=>s));return{tier:i,family:a.size===1?r[0].family:"extensions"}}function Il(e,t){if(t.length===0)return e;let n=pe(e,t);if(n)return n;let o=t.join(" ");if(!Ke.some(r=>r===o)&&!Lo(o)&&!Ee(o))return null;for(let r=t.length-1;r>0;r-=1){let i=pe(e,t.slice(0,r));if(i)return i}return t.length===1?e:null}function $l(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function di(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 Pl(e){let t=new Map;for(let n of e){let o=n,r=di(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let i=t.get(r)??[];i.push(o.long.trim()),t.set(r,i)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,i)=>r.localeCompare(i)));return t}function Nl(e){return A(e)}function Ml(e){let t=e.options??[],n=Pl(t);return t.map(o=>{let r=o,i=typeof r.flags=="string"?r.flags.trim():"",a=typeof r.description=="string"?r.description.trim():"",s=di(o),d=(s?n.get(s)??[]:[]).filter(h=>h!==r.long).map(h=>h.trim()).filter(h=>h.length>0),c=a.match(/^Alias for ([^ ]+)/i),m=c&&c[1]?c[1].trim():null,p=r.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),u=i.includes("<"),g=u||i.includes("["),w={flags:i,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:a,takes_value:g,value_required:u,value_name:$l(i),variadic:r.variadic===!0,required:p,aliases:d,alias_for:m};return r.defaultValue!==void 0&&(w.default_value=r.defaultValue),w})}function Fl(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 r=o.alias_for,i=t.get(r);if(!i)continue;let a=o.long,s=new Set([...i.aliases??[],a]);i.aliases=[...s].sort((l,d)=>l.localeCompare(d))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Dl(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",i=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0||i?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:i}})}function Ll(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||(Q(i)??X(i.name()))!=="internal").map(i=>{let a=N($(i)),s=a.split(" ")[0],l=Q(i),d=ci(a,t,l!==void 0),c=se.find(({alias:m})=>m===a);return{name:i.name().trim(),aliases:mn(i),description:i.description().trim(),tier:d?.tier??l??X(s),family:d?.family??et(s),...c?{alias_for:c.canonical,alias_lifecycle:c.lifecycle,...c.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((i,a)=>i.name.localeCompare(a.name))}function Ul(e,t,n){if(!n)return t;let o=n.examples??[],r=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"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function jl(e,t){return e===void 0?null:t?.tier??X(e)}function ql(e,t){return e===void 0?null:t?.family??et(e)}function Hl(e,t,n){if(!(t!==e||!n))return se.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function zl(e,t,n,o,r=new Map,i=!1){if(!e){let s=Dl(t),l=Ll(t,r,i),d=new Set(l.map(({name:c})=>c));return{arguments:s,options:o,subcommands:[...l,...Ye.filter(({parent:c,action:m})=>c===n&&!d.has(m)).map(({action:c,description:m})=>({name:c,aliases:[],description:m,tier:X(n.split(" ")[0]),family:et(n.split(" ")[0])}))].sort((c,m)=>c.name.localeCompare(m.name)),usage:[n,s.reduce((c,m)=>m.required?c.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):c,t.usage())].filter(c=>c.length>0).join(" ")}}let a=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:l,variadic:d,value_kind:c,polymorphic:m})=>({name:s,required:l,variadic:d,description:m?`Polymorphic ${c} value; inspect the action contract before mutation.`:`${c.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:l})=>s!==null&&a.has(s)||l.some(d=>a.has(d))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:l,variadic:d})=>{let c=d?`${s}...`:s;return l?`<${c}>`:`[${c}]`})].join(" ")}}function Gl(e,t,n,o,r){let i=Jt(n),a=ce(n),s=N($(t)),l=N(o.join(" ")),d=l.length>s.length?l:s,c=Ee(d),m=c?.command??d,p=m.length>0?m:void 0,u=p?.split(" ")[0],g=yr(p,i),w=p?r.get(p):void 0,h=p?ci(p,r,Q(t)!==void 0):void 0,C=Ul(i,g,w),R=Fl(Br(Ml(t),Wr(w))),j=zl(c,t,m,R,r,a),M=Hl(e,t,a);return{format:"pm_help_v1",detail_mode:i,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:jl(u,h),capability_family:ql(u,h),description:c?.description??t.description(),usage:j.usage,intent:c?.description??C.intent,examples:c?[c.example]:C.examples,tips:c?[Xe(c.accepted_flags)]:C.tips,arguments:j.arguments,options:j.options,subcommands:j.subcommands,has_subcommands:j.subcommands.length>0,...M===void 0?{}:{command_aliases:M}}}async function mi(e,t,n){let o=z(t);if(!o.json)return!1;let r=P(t);if(!r.requested)return!1;let i=Il(e,r.commandPathTokens);if(!i){if(!o.quiet){let a=`unknown command '${r.commandPathTokens.join(" ")}'`,s=wn(a,e,n),l=lt(a,"help",Ie,f.USAGE,{...s,attemptedCommand:Nl(t),normalizedInvocationArgs:[...t],providedOptionFlags:K(t)});y(JSON.stringify(l,null,2))}return process.exitCode=f.USAGE,!0}if(!o.quiet){let a=Gl(e,i,t,r.commandPathTokens,n);Eo(`${JSON.stringify(a,null,2)}
26
+ `)}return process.exitCode=f.SUCCESS,!0}function Wl(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(`
27
+ `)}function Bl(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)":"",r=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${r.length>0?r.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Vl(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let r of[...t.required_create_fields,...t.required_create_repeatables])o.add(r);return{progressive:n,strict:o}}function Kl(e,t,n,o){let r=new Set(n),i=o.filter(l=>!r.has(l)),a=l=>l.length>0?l.map(d=>Et("create",d)).join(", "):"none";e.push(` required in strict mode: ${a(i)}`);let s=i.map(Vo).filter(l=>l!==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 Jl(e,t,n){let o=er(n);if(!o)return Wl(e,t);let r=Xn(o,t);if(!r){let w=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${w}`].join(`
28
+ `)}let i=n.indexOf("--"),a=i<0?n:n.slice(0,i),s=a.findIndex(w=>w==="--create-mode"||w.startsWith("--create-mode=")),l=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],d=e==="create"&&l?.toLowerCase()==="strict",c=Vl(e,r),m=He(r,e,c.progressive),p=He(r,e,d?c.strict:c.progressive),u=w=>w.length>0?w.map(h=>Et(e,h)).join(", "):"none",g=["",`Type-aware option policies for ${r.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let w=He(r,e,c.strict);Kl(g,r,m.required,w.required)}return Bl(g,r),p.errors.length>0&&g.push(` config errors: ${p.errors.join("; ")}`),g.join(`
29
+ `)}function pi(e,t,n){let o=k(n);if(o!=="create"&&o!=="update")return;let r=Re(e,o);r&&r.addHelpText("after",Jl(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]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function ui(e,t,n,o){if(n)return null;let r=e.some(a=>a==="--for"||a.startsWith("--for=")),i=k(e)==="contracts"&&e.includes("--full");return r||i?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f947c7f0-adf8-59da-8bc7-9cd746b05839")}catch{}})();var Cn="PM_CLI_PACKAGE_ROOT",ut=Symbol.for("pm.readOutputInvocationProvenance");function Pn(e,t){let n=Reflect.get(e,ut);n!==void 0&&Reflect.set(t,ut,n)}function bi(e,t,n){let o=bo(t,n);if(!o)return;let r=e;for(;r.parent;)r=r.parent;let i=r.rawArgs,a=new Set(K(i.slice(2))),s=_o.find(c=>c.command===o),l=Object.values(s.dimensions).flatMap(c=>c.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),d=Reflect.get(n,ut);Reflect.set(n,ut,{canonical_include_modes:d?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),Pn(n,e)}function Xl(){return Kn(import.meta.url,["../.."])}(typeof process.env[Cn]!="string"||process.env[Cn]?.trim().length===0)&&(process.env[Cn]=Xl());var ge=null,U=null;function Zl(e){ge=e}function Ql(e){O=e}var ec=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"]),tc=new Set(["parse","preflight","execute","unknown"]),nc=new Set(["usage","validation","conflict","runtime","unknown"]),Ne=null,oe=null,O=new Map,Nn=250,oc=new Set([f.USAGE,f.NOT_FOUND,f.CONFLICT]),rc=new Set(["1","true","yes","on"]),ic=ke(()=>import("./chunks/register-setup-OQERLLWE.js")),ac=ke(()=>import("./chunks/register-list-query-J35ZPQQ5.js")),sc=ke(()=>import("./chunks/register-mutation-J6XJJOGU.js")),lc=ke(()=>import("./chunks/register-operations-AE3JEMFT.js"));function pt(e){return A(e)}function xi(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=>ee(o)??o))];return n.length>0?n:void 0}function cc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=K(t),r=new Set(o.map(c=>ee(c)??c)),i=xi(e),a=t.find(c=>b.commands.some(m=>m.name()===c)),s=a?b.commands.find(c=>c.name()===a):void 0,l=new Set([...b.options,...s?.options??[]].flatMap(c=>c.flags.split(/[ ,|]+/).map(m=>ee(m)).filter(m=>m!==void 0))),d=i?.filter(c=>{let m=ee(c)??c;return r.has(m)?!1:l.has(m)||ln(t,a,m,O)!==void 0});return d&&d.length>0?d:void 0}function dc(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],i=r?ee(r):void 0,a=e.find(p=>b.commands.some(u=>u.name()===p)),s=a?b.commands.find(p=>p.name()===a):void 0,l=i?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(i)):void 0,d=ln(e,a,i,O),c=i?l?.isBoolean()===!0||d===!1?[i]:[i,"<value>"]:[],m=i?pt([...e,...c]):t;return m===t?void 0:m}function mc(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 r=e[o];r!=null&&(n[o]=r)}return n}function pc(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,...mc(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function vi(e,t,n){let o=Ve(t),r=o.includes("--explain"),i=e?.recovery,a=i&&o.includes("history-redact")?{...i,...i.attempted_command?{attempted_command:pt(o)}:{},...i.normalized_args?{normalized_args:[...o]}:{},...i.suggested_retry?{suggested_retry:pt(o)}:{},...i.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:i;if(a?.recovery_mode==="compact"&&!r)return{...e,recovery:a};let s=pt(o),l=K(o),d=cc(n,o,a),c=dc(o,s,d,a),m=pc({invocationArgv:o,attemptedCommand:s,providedFields:l,inferredMissing:d,suggestedRetry:c,existingRecovery:a});return{...e,recovery:m}}function fe(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function Ci(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Mn(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 ki(e){if(!e)return;let t=e.trim().toLowerCase();if(ec.has(t))return t}function Ei(e){if(!e)return;let t=e.trim().toLowerCase();if(tc.has(t))return t}function Si(e){if(!e)return;let t=e.trim().toLowerCase();if(nc.has(t))return t}function Ai(e){let t=fe(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(Ci(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=Mn(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let i=e?.run_results;if(Array.isArray(i)){let a=i.filter(s=>Ct(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function Ti(e,t){if(!e)return t===f.USAGE?"invalid_command_usage":t===f.NOT_FOUND?"item_not_found":t===f.CONFLICT?"lock_conflict":t===f.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function Oi(){let e=Ct(xe()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Mn(e,"exit_code","exitCode"),o=t??n??f.SUCCESS,r=Bo(o),i=fe(e,"error_code","errorCode")??Ti(r,o),a=Si(fe(e,"error_category","errorCategory"))??(r?void 0:vt(i)),s=r?void 0:Ai(e)??`command_exit_${o}`,l=ki(fe(e,"command_resolution","commandResolution"))??It({ok:r,errorCode:i,errorCategory:a}),d=Ei(fe(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:i,error_category:a,command_resolution:l,resolution_stage:d}}async function Le(e){let t=U;U=null,await _r(t,e);let n=ge;if(ge=null,!n){Ge();return}let o=[],r=po();try{await br({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(i=>i.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await to(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:xe(),affected:r}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{Ge()}!n.globalOptions.json&&o.length>0&&y(`[pm] warning: afterCommand hook_warnings=${F(o)}`),n.profileEnabled&&o.length>0&&y(`profile:extensions hook_warnings=${F(o)}`)}async function Ri(){await Oo()}function Ii(e){return rc.has((process.env[e]??"").trim().toLowerCase())}function $i(e){return Ii("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!oc.has(Math.trunc(e))}async function ft(e){return $i(e.exit_code)?(await Ri(),Ro(e),!0):!1}async function Pi(e){let t=Z(e.error),n=Nr(t);e.bootstrapGlobal.json?y(JSON.stringify($r(t,f.GENERIC_FAILURE),null,2)):y(t),process.exitCode=f.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await Ri(),Nt(e.error);let i=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:f.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=i.errorCategory,r=i.commandResolution,ve(!1,t,{error_code:n.code,error_category:o,exit_code:f.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||y(`Failed to report error: ${Z(i)}`)}try{await Le({ok:!1,error:t,exit_code:f.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${Z(i)}`)}try{await Ce()}catch(i){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${Z(i)}`)}}function fi(e,t,n,o){bi(e,t,o);let r=n.outputInclude;if(r===void 0)return;let{selectors:i,modes:a}=Co(t,r,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;Pn(o,e);let s=vo(t);for(let d of a){let c=s.get(d),m=o[c];e.setOptionValueWithSource(c,m,"cli")}let l=i.length>0?i.join(","):void 0;l===void 0?delete n.outputInclude:n.outputInclude=l;for(let d=e;d;d=d.parent)d.setOptionValueWithSource("outputInclude",l,"cli");Ft(e,n)}function Me(e,t,n=[]){let r={...e.optsWithGlobals()};Pn(e,r),delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let i=dr(t);for(let[a,s]of Object.entries(i))r[a]===void 0&&(r[a]=s);if(n.length>0){let a=sr(n),s=Ze($(e)).map(d=>({long:d.flag,short:d.short,aliases:d.aliases})),l={...i};for(let d of a)r[d]!==void 0&&(l[d]=r[d]);return Wt(l,[...s,...n],$(e)),cr(r,n,i)}return r}function Sn(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function gt(e,t,n){let o=Sn(e,t),r=[t],i=[];for(let a of n){if(a.startsWith("-"))break;r.push(a);let s=Sn(e,r.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function Fn(e){return e.arguments??[]}function gi(e){let t=Fn(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Ni(e,t){if(!e)return!1;let n=_(t);return e.importers.some(o=>_(`${o.importer} import`)===n)||e.exporters.some(o=>_(`${o.exporter} export`)===n)}function Mi(e,t){let n=Fn(e),o=n.filter(l=>l.required).length,i=n.some(l=>l.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new v(`Missing required argument for extension command '${e.command}'. Usage: ${gi(e)}${s}`,f.USAGE);if(t.length>i){let l=t.slice(i).join(" ");throw new v(`Too many arguments for extension command '${e.command}': ${l}. Usage: ${gi(e)}${s}`,f.USAGE)}}function uc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function fc(e,t,n){if(n.length>0){Wt(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new v(`Unknown option '${o.map(uc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,f.USAGE)}function Fi(e,t,n,o){e&&(Mi(e,t),fc(e,n,o))}var gc={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"},kn=new Map;function An(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Di(e,t){return e.options.some(n=>n.long===t)}function Li(e,t){return e.options.some(n=>n.short===t)}function Tn(e,t,n,o){let r=t.trim();if(!r)return;let i=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Li(e,r))return;if(o){e.option(`${r} <value>`,`${i} (repeatable)`,Lt);return}e.option(`${r} <value>`,i);return}let a=r.startsWith("--")?r:`--${r}`;if(!Di(e,a)){if(o){e.option(`${a} <value>`,`${i} (repeatable)`,Lt);return}e.option(`${a} <value>`,i)}}async function Ui(e,t){let n=gc[e];if(!n)return[];let o=`${t}:${n}`,r=kn.get(o);if(r)return r;if(!await q(H(t)))return kn.set(o,[]),[];let i=await I(t),s=(Tt(i.schema).command_to_fields.get(n)??[]).flatMap(l=>[l.cli_flag,...l.cli_aliases].map(c=>({long:`--${c}`,type:An(l.type),value_type:An(l.type)})));return kn.set(o,s),s}async function ji(e,t){let n=z(t),o=E(process.cwd(),n.path);if(!await q(H(o)))return;let r=oe?.key===Un(o)?oe.snapshot:null,i=r===null?await I(o):r.settings,a=Tt(i.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 l of s){let d=pe(e,l.path.split(" "));if(d)for(let c of a.command_to_fields.get(l.command)??[]){let m=c.description??"";Tn(d,c.cli_flag,m,c.repeatable);for(let p of c.cli_aliases)Tn(d,p,`Alias for --${c.cli_flag}`,c.repeatable)}}}async function Dn(e,t,n,o,r){let i=k(n);if(!(i!=="create"&&i!=="update"))try{let a=r??await I(t),s=J(a,o);pi(e,s,n)}catch{}}function On(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function qi(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Ln(e){return e.some(t=>t==="--profile")}function Un(e){return`pm-root:${e}`}function Hi(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Ue(e){let t=_(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of Hi(e.commandArgs))o.push(...r.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n)]}function zi(e,t){let n=_(e);if(n.length===0)return!1;let o=Ue(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function jn(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...S(n.commands),...S(n.command_handlers),...S(n.command_overrides),...S(n.flag_commands),...S(n.parser_overrides),...hi(n.preflight_ownership),...hi(n.renderer_ownership)]:[]}function S(e){return e??[]}function hi(e){return S(e).flatMap(t=>t.commands)}function ht(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Gi=new Set(["hooks","parser","preflight","renderers"]),Wi=new Set(["commands","schema","services","importers"]),hc=new Set(["reindex","search","search-advanced"]),yc=new Set(["--template"]);function Fe(e,t){for(let n of t)if(e.has(n))return!0;return!1}function Bi(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return hc.has(n??t)}function Vi(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 qn(e){return _(e.commandPath??"")==="create"&&Vi(e,yc)}function Ki(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function Rn(e,t){return e.some(n=>zi(n,t))||qn(t)&&Ki(e)}function Ji(e){return[S(e.hooks).length,(e.preflight_overrides??0)-S(e.preflight_ownership).length,S(e.item_types).length,S(e.item_fields).length,S(e.relationship_kinds).length,S(e.service_overrides).length,S(e.assurance_providers).length,S(e.renderer_overrides).length-S(e.renderer_ownership).length].some(n=>n>0)}function Yi(e,t){let n=e.activation?.commands??[];if(n.length>0)return Rn(n,t);let o=jn(e);if(Rn(o,t)||ht(e).has("search")&&Bi(t.commandPath))return!0;if(e.contributions)return Ji(e.contributions)}function Hn(e,t){let n=Yi(e,t);if(n!==void 0)return n;let o=ht(e);return!!(Fe(o,Gi)||Fe(o,Wi))}function yt(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>Hn(o,t)):e.effective.some(o=>{let r=ht(o);return jn(o).length>0||Fe(r,Gi)||Fe(r,Wi)||r.has("search")})}function zn(e){let t=Ue(e).filter(r=>r.split(" ").every(i=>!i.startsWith("-"))).sort((r,i)=>i.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=qn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Xi(e){return zn(e)==="all"?void 0:t=>Hn(t,e)}function je(e){let t=P(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...i]=t.commandPathTokens;return{commandPath:r,commandArgs:i,allowCommandPrefixMatch:!0}}let n=Ae(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Zi(e){let t=e.args.map(String);if(_($(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function In(e){for(let t of e)t.startsWith("settings_read_")&&y(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Qi(e,t){e.profile&&(y(`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&&y(`profile:extensions activation_warnings=${F(t.activationWarnings)}`))}function wt(e,t,n){if(!e)return;let o=_(n.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function _t(e,t=le){let n=Un(e);if(oe?.key===n)return oe.snapshot;try{let o=Date.now(),{settings:r,warnings:i}=await t(e),a=await no({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return oe={key:n,snapshot:s},s}catch{return oe={key:n,snapshot:null},null}}async function he(e,t,n=I){let o=t?zn(t):"all",r=qi(e,o);if(Ne?.key===r)return Ne.snapshot;try{let i=await n(e),a=await _e({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Xi(t):void 0}),s=await be({...a,loaded:a.loaded}),l=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,g)=>u.localeCompare(g)),d=Lr(s.registrations.flags),c=Fr(s.commands.handlers,s.registrations.commands),m=jr(l,s.registrations.commands,s.registrations.flags,c),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:i,commandHandlers:l,commandFlagHelp:d,commandDescriptors:m,commandAliases:c,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:u,module:g})=>({name:u,module:g}))};return Ne={key:r,snapshot:p},p}catch{return Ne={key:r,snapshot:null},null}}async function ea(e){let t=Se(e);if(t.noExtensions){let a=E(process.cwd(),t.path);return await q(H(a))&&In((await le(a)).warnings),null}let n=E(process.cwd(),t.path),o=await _t(n);if(!o)return null;In(o.settingsReadWarnings);let r={commandPath:$(e),commandArgs:Zi(e)};if(!yt(o.discovery,r))return wt(t.profile,o,r),null;let i=await he(n,r);return i?(Qi(t,i),{hooks:i.hooks,commands:i.commands,parsers:i.parsers,preflight:i.preflight,services:i.services,renderers:i.renderers,registrations:i.registrations,pmRoot:n}):null}async function ta(e){let t=await he(e);return t?new Map(t.commandDescriptors):O}async function na(e,t){return(await Go({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function oa(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return Uo(e,Xo.forActiveExtensionHost({pmRoot:e,author:n}))}async function ra(e,t,n,o=[]){let r=$(e),i=Bt(e.args.map(String),o),a={...t},s={...n},l=E(process.cwd(),n.path),d=await We({command:r,args:i,options:a,global:s,pm_root:l});n.profile&&d.warnings.length>0&&y(`profile:extensions parser_warnings=${F(d.warnings)}`),i=d.context.args,a=d.context.options,s=d.context.global,Fi(O.get(_(r)),i,a,o),ae(void 0),ze({command:r,args:i,options:{...a},global:{...s},pm_root:l});let c=await At({command:r,args:i,options:a,global:s,pm_root:l,sdk:oa(l,s)});if(s.profile&&c.warnings.length>0&&y(`profile:extensions command_handler_warnings=${F(c.warnings)}`),!c.handled){if(c.warnings.length>0){let m=c.warnings[0],p=c.errorMessage?.trim(),u=p?` ${p}`:"";throw new v(`Command "${r}" failed in extension handler (${m}).${u}`,f.GENERIC_FAILURE,{code:c.errorCode??"command_failed",nextSteps:c.remediation?[c.remediation]:void 0})}throw new v(`Command "${r}" is provided by extensions and is not currently available.`,f.NOT_FOUND)}return c.exitCode!==void 0&&(process.exitCode=c.exitCode),ae(c.result),c.result}var yi=Symbol("pm.wrappedActionHandler");function wc(e,t){let n=e[e.length-1];return n instanceof $n?n:t}function wi(e,t,n){e&&n.length>0&&y(`profile:extensions ${t}=${F(n)}`)}function _c(e){let t=O.get(_(e.commandPath));if(!t||!Ni(e.activeRegistrations,e.commandPath))return;let n=Fn(t).length===0?mr(e.commandArgs):Bt(e.commandArgs,e.extensionFlagDefinitions);Mi(t,n)}function bc(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 ia(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[yi]!==!0){let r=o._actionHandler;o._actionHandler=async function(...a){let s=wc(a,n),l=Date.now();Dt(s);let d=Se(s),c=$(s),m=E(process.cwd(),d.path),p=s.args.map(String),u=Y(),g=u?gt(u,c,p):[],w=await Ui(c,m),h=Me(s,p,[...g,...w]),C=await We({command:c,args:p,options:h,global:d,pm_root:m});wi(d.profile,"parser_warnings",C.warnings),p=C.context.args,h=C.context.options,d=C.context.global,_c({activeRegistrations:u,commandPath:c,commandArgs:p,extensionFlagDefinitions:g}),d=await qo(d),Ft(s,d),bc(s,a,p),Qe(s,h),ae(void 0),ze({command:c,args:p,options:{...h},global:{...d},pm_root:m});let R=await At({command:c,args:p,options:h,global:d,pm_root:m,sdk:oa(m,d)});if(wi(d.profile,"command_handler_warnings",R.warnings),R.handled){ae(R.result),Rt(R.result,{...d,command:c,commandArgs:p,commandOptions:h,pmRoot:m}),d.profile&&y(`profile:command=${c} took_ms=${Date.now()-l}`);return}return await r.apply(this,a)},o[yi]=!0}for(let r of n.commands)t(r)};t(e)}async function mt(e){O=new Map,V({overrides:[]}),e&&await Dn(e.rootProgram,e.pmRoot,e.invocationArgv,Qn(),e.settings)}function xc(e,t,n,o){if(t?.flags&&t.flags.length>0){cn(e,t.flags);let r=dn(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function aa(e,t,n){let o={core:0,standard:1,full:2,internal:3},r=(i,a)=>{let s=a.join(" "),l=[...n.entries()].filter(([c])=>c===s||c.startsWith(`${s} `)).map(([,c])=>c),d=l.length===0?"standard":l.reduce((c,m)=>o[m.tier]<o[c]?m.tier:c,"internal");ur(i,d);for(let c of i.commands)r(c,[...a,c.name()])};for(let i of e.commands)t.has(i.name())||r(i,[i.name()])}async function sa(e,t){let n=z(t),o=E(process.cwd(),n.path);if(n.noExtensions){await mt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await _t(o),i=je(t);if(!r){await mt();return}if(!yt(r.discovery,i)){await mt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),wt(Ln(t),r,i);return}let a=await he(o,i);if(!a){await mt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}V(a.services),O=new Map(a.commandDescriptors),await Dn(e,o,t,a.registrations,a.settings);let s=Yr(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,c=>Xr(a.activationWarnings,y,c)),l=new Set(e.commands.map(c=>c.name())),d=c=>{let m=c.split(" ").filter(R=>R.length>0),p=a.commandDescriptors.get(c),u=pe(e,m),g=a.commandFlagHelp.get(c),w=p?Vr(p):null;if(u){xc(u,p,g,w);return}let h=Jr(e,m);p?.description&&h.description(p.description);let C=g;p&&(qr(h,p),p.flags.length>0&&(cn(h,p.flags),C=dn(h,p.flags)??void 0)),C&&h.addHelpText("after",C),w&&h.addHelpText("after",w),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...R)=>{let j=R[R.length-1],M=j instanceof $n?j:h,re=Se(M),xt=Date.now(),qe=gt(a.registrations,c,M.args.map(String)),ye=Me(M,M.args.map(String),qe),ie=await ra(M,ye,re,qe);await Ho(re,ie),Rt(ie,{...re,command:c,commandArgs:M.args.map(String),commandOptions:ye,pmRoot:o}),re.profile&&y(`profile:command=${c} took_ms=${Date.now()-xt}`)})};for(let c of s)d(c);aa(e,l,a.commandDescriptors)}var De=Jn(import.meta.url,["../.."])??"0.0.0",b=zt(De);function la(e){e.hook("preAction",async(t,n)=>{ge=null,U=null,Ge(),Dt(n);let o=n.optsWithGlobals(),r=Se(n),i=$(n),a=n.args.map(String),s=Me(n,a),l={...r};xo(i,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession,outputCursor:o.outputCursor}),fi(n,i,l,s),await No(i,l);let d=E(process.cwd(),r.path),c=await ea(n);if(!c){ge=oo({commandName:i,commandArgs:a,commandOptions:s,globalOptions:l,pmRoot:d}),U=await Mt({command:i,pm_version:De,args:a,options:s,global:l,pm_root:d}),$t(i,a,s,{source_context:U?.source_context,source_context_source:U?.source_context_source}),Pt(i),await fn(i,s,d,On()),await un(i,a,s,l,d);return}ro(c.hooks),io(c.commands),ao(c.parsers),so(c.preflight),V(c.services),lo(c.renderers),co(c.registrations);let m=gt(c.registrations,i,a);s=Me(n,a,m),fi(n,i,l,s);let p=await We({command:i,args:a,options:s,global:l,pm_root:c.pmRoot});l.profile&&p.warnings.length>0&&y(`profile:extensions parser_warnings=${F(p.warnings)}`),a=p.context.args,s=p.context.options,l=p.context.global,Qe(n,s);let u=await uo({command:i,args:a,options:s,global:l,pm_root:c.pmRoot,decision:On()});l.profile&&u.warnings.length>0&&y(`profile:extensions preflight_warnings=${F(u.warnings)}`),a=u.context.args,s=u.context.options,l=u.context.global,Qe(n,s);let g=u.decision;await fn(i,s,c.pmRoot,g),await un(i,a,s,l,c.pmRoot);let w=g.run_extension_migrations?await na(c.registrations.migrations,c.pmRoot):[];l.profile&&w.length>0&&y(`profile:extensions migration_warnings=${F(w)}`);let h=ei(c.registrations.migrations);ge={hooks:c.hooks,commandName:i,commandArgs:a,commandOptions:{...s},globalOptions:{...l},pmRoot:c.pmRoot,profileEnabled:!!l.profile,migrationBlockers:h},ae(void 0),ze({command:i,args:a,options:{...s},global:{...l},pm_root:c.pmRoot}),U=await Mt({command:i,pm_version:De,args:a,options:s,global:l,pm_root:c.pmRoot}),$t(i,a,s,{source_context:U?.source_context,source_context_source:U?.source_context_source}),Pt(i);let C=await eo(c.hooks,{command:i,args:a,options:{...s},global:{...l},pm_root:c.pmRoot});l.profile&&C.length>0&&y(`profile:extensions hook_warnings=${F(C)}`),g.enforce_mandatory_migration_gate&&ti(i,s,h)}),e.hook("postAction",async()=>{let t=Oi();ve(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await Le(t)})}la(b);var vc=new Set(["--version","-V"]),Cc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),ca=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"]),da=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),kc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Ec=new Set(["claim","close-task","pause-task","release","start-task","test"]),En={setup:!0,listQuery:!0,mutation:!0,operation:!0},Sc=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 bt(e){return e.some(t=>vc.has(t))}function ma(e){if(bt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return En;let t=k(e);if(!t)return En;let n=t.trim().toLowerCase();return Cc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:ca.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:da.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:kc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:En}function pa(e){return e.length===0||P(e).requested||e.includes("--explain")&&k(e)===void 0}var _i=Symbol("pmCliIdempotentTopLevelRegistration");function ua(e){let t=e;if(t[_i])return;t[_i]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let i=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===i||a.aliases().includes(i))?new $n(i):n(o,...r)})}async function Ac(e,t){if(ua(e),t.setup){let{registerSetupCommands:n}=await ic();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await ac(),o=typeof t.targetCommandName=="string"&&ca.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await sc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await lc();n(e)}}function fa(e,t){return bt(t)?!1:ce(t)||P(t).requested?!0:!!k(t)}function ga(e){if(bt(e))return!1;let t=k(e);return t?Sc.has(t):!1}function Tc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(d=>{let c=d.indexOf("=");return c>=0?d.slice(0,c):d}).find(d=>d==="--literal"||d==="--regex"||d==="--replacement"),i=r?e.argv.map(d=>{let c=d.indexOf("=");return(c>=0?d.slice(0,c):d)===o?c>=0?`${r}${d.slice(c)}`:r:d}):e.argv,a=Ve(i),s=r&&n>=0?`${o}=[redacted]`:t,l=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:l,sourceDisplay:s}}function ha(e){let t=e.commandName;if(!t)return;let n=e.trace.find(d=>d.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(d=>d.length>0),r=o.length>0?o.join(" "):"the canonical flag",i=da.has(t)||Ec.has(t),a=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",l=Tc({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new v(`Refusing to auto-correct ${s} ${l.sourceDisplay} to ${l.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,f.USAGE,{code:a,examples:[A(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:A(l.argv)}})}function Oc(e){return async t=>{let n=vt(t.errorCode),o=It({ok:!1,errorCode:t.errorCode,errorCategory:n});return await Fo({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:De,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 ya(e){if(e.bootstrapGlobal.noExtensions)return;let t=je(e.invocationArgv),n=await _t(e.bootstrapPmRoot);if(n&&yt(n.discovery,t)){let o=await he(e.bootstrapPmRoot,t);wa(o);return}n&&wt(Ln(e.invocationArgv),n,t),V({overrides:[]})}function wa(e){if(!e){V({overrides:[]});return}V(e.services)}async function Gn(e){ve(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Le({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 _a(){ve(!0,void 0,{exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Le({ok:!0,exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=f.SUCCESS}async function ba(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof v)&&(qt(e.error)||!n))return!1;let o=Z(e.error),r=e.error instanceof v?e.error.exitCode:jt(t),i=e.error instanceof v?e.error.context:void 0,a=vi(i,e.invocationArgv,o),s=Rr(o,a),l=e.bootstrapGlobal.lean?at(an(o,r,a)):an(o,r,a),d=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?ko(l,u=>`${JSON.stringify(u,null,2)}
30
+ `):l,null,2):Or(o,a);y(d);let{errorCategory:c,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await ft({command:e.attemptedCommand,error_code:s.code,error_category:c,exit_code:r,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:U?.source_context});return await Gn({errorMessage:o,exitCode:r,classificationCode:s.code,errorCategory:c,commandResolution:m,resolutionStage:"execute"}),p&&(Nt(Ht(e.error,o)),await Ce(Nn)),process.exitCode=r,!0}async function xa(e,t){let n=hn(e.invocationArgv),o=`unknown command '${n}'`,r=E(process.cwd(),e.bootstrapGlobal.path),i=await ta(r),a=je(e.invocationArgv),s=await vn(r,{},Ue(a)),l=await Pe({message:o},b,i,{failedExtensions:s}),d=sn(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:s}),{errorCategory:c,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:d.code,errorMessage:d.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await ft({command:n,error_code:d.code,error_category:c,exit_code:f.USAGE,error_message:d.detail,command_resolution:m,resolution_stage:"parse"}),u=e.jsonErrors?await xn({message:o},b,i,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await bn({message:o},b,i,{failedExtensions:s}),g=gn(u,e.jsonErrors,s);await Gn({errorMessage:o,exitCode:f.USAGE,classificationCode:d.code,errorCategory:c,commandResolution:m,resolutionStage:"parse"}),y(g),p&&await Ce(Nn),process.exitCode=f.USAGE}async function va(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let r=P(e.invocationArgv);return r.requested&&!_n(b,r.commandPathTokens)?(await xa(e,t),!0):(await _a(),!0)}async function Ca(e,t){let n=await Pe(e.error,b,O),o=sn(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:r,commandResolution:i}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),a=await ft({command:e.attemptedCommand,error_code:o.code,error_category:r,exit_code:f.USAGE,error_message:o.detail,command_resolution:i,resolution_stage:"parse",source_context:U?.source_context}),s=e.jsonErrors?await xn(e.error,b,O,e.bootstrapGlobal.lean===!0):await bn(e.error,b,O),l=await si(o.code,e.bootstrapPmRoot,{},Ue(je(e.invocationArgv))),d=gn(s,e.jsonErrors,l);await Gn({errorMessage:n.message,exitCode:f.USAGE,classificationCode:o.code,errorCategory:r,commandResolution:i,resolutionStage:"parse"}),y(d),a&&await Ce(Nn),process.exitCode=f.USAGE}function ka(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 Ea(e){let t=e.error.code,n=String(e.error.message??"");if(!await va(e,t,n)){if(t==="commander.version"){await _a();return}await Ca(e,t)}}async function Wn(e){let t=z(e.invocationArgv),n=E(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:k(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:Oc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await ya({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await ba(o,Ut(e.error))){if(ka(e.error)){await Ea(o);return}await Pi({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}async function Rc(e){b=zt(De),la(b),Ne=null,oe=null,O=new Map,mo();let t=[...e],n,o;try{let r=tt(e);t=r.argv;let i=[process.argv[0],process.argv[1],...t],a=t.length===0,s=z(t);if(s.authorMissingValue)throw new v("--author requires a non-empty value.",f.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});n=or(s.author),ha(r),o=Qo(t);let l=ma(t);if(await Ac(b,l),pa(t)&&wr(b,t),fa(b,t)?await sa(b,t):(O=new Map,V({overrides:[]})),ga(t)&&await ji(b,t),ia(b),await mi(b,t,O))return;let m=P(t);if(m.requested&&!_n(b,m.commandPathTokens))throw new Yl(f.USAGE,"commander.helpDisplayed","(outputHelp)");if(a||ce(t)&&k(t)===void 0){b.outputHelp();return}let p=await I(E(process.cwd(),s.path)),u=await ui(t,E(process.cwd(),s.path),s.noExtensions,he);await jo({pmRoot:E(process.cwd(),s.path),packages:u?.contextIntentPackages},()=>go(p.agent_identity.harness_signals,()=>b.parseAsync(i),{probesEnabled:p.agent_identity?.probes_enabled}))}catch(r){await Wn({error:r,invocationArgv:t})}finally{o?.(),n?.()}}async function lm(e=process.argv.slice(2)){try{await Do(process.env,()=>Rc(e))}catch(t){await Wn({error:t,invocationArgv:[...e]})}}var cm={activationCommandMatchesProbe:zi,applyDynamicExtensionRootHelpVisibility:aa,bootstrapProfileEnabled:Ln,buildBootstrapActivationProbe:je,buildPostActionTelemetryOutcome:Oi,buildPmCliRecoveryContext:vi,buildRuntimeExtensionDiscoverySnapshotCacheKey:Un,buildRuntimeExtensionActivationScope:zn,buildRuntimeExtensionSnapshotCacheKey:qi,buildRuntimeExtensionFilterForProbe:Xi,addRuntimeFieldOption:Tn,collectActivationCommandCandidates:Ue,collectExtensionFlagDefinitionsForCommand:Sn,collectExtensionFlagDefinitionsForInvocation:gt,collectLeadingCommandArgs:Hi,collectParsedActivationCommandArgs:Zi,collectRuntimeFieldLooseFlagDefinitionsForCommand:Ui,commandHasLongOption:Di,commandHasShortOption:Li,commandPathNeedsSearchExtensions:Bi,commandPathNeedsTemplateExtensions:qn,describeUnknownError:Z,defaultPreflightDecision:On,discoveryNeedsActivationForProbe:yt,emitExtensionProfile:Qi,emitExtensionSkippedProfile:wt,emitSettingsReadWarnings:In,ensureIdempotentTopLevelCommandRegistration:ua,enforceExplicitRetryForFlagTypos:ha,envFlagEnabled:Ii,executeRegisteredRuntimeMigrations:na,extractCommandScopedOptions:Me,extensionActivationCommands:jn,extensionCapabilities:ht,extensionNeedsActivationForProbe:Hn,extensionProvidesTemplatesRuntime:Ki,hasAnyCapability:Fe,hasGlobalExtensionContributions:Ji,handleGenericRunPmCliError:Pi,handleRunPmCliCommanderError:Ea,handleRunPmCliError:Wn,handleRunPmCliHelpDisplayError:va,handleRunPmCliKnownError:ba,handleRunPmCliCommanderUsageError:Ca,handleUnknownHelpCommandError:xa,inferMissingFieldsFromErrorMessage:xi,inferPostActionErrorCode:Ti,inferPostActionFailureMessage:Ai,invocationRequestsVersion:bt,isCommanderError:qt,loadRuntimeExtensionCommandDescriptorsForRecovery:ta,loadRuntimeExtensionDiscoverySnapshot:_t,loadRuntimeExtensionSnapshot:he,maybeLoadRuntimeExtensions:ea,maybeAttachCreateUpdatePolicyHelpText:Dn,maybeLogHandledCliErrorToSentry:ft,matchesStaticExtensionCommand:Rn,normalizeTelemetryCommandResolution:ki,normalizeTelemetryErrorCategory:Si,normalizeTelemetryResolutionStage:Ei,normalizeThrownExitCode:jt,probeUsesAnyFlag:Vi,prepareExtensionServicesForRunPmCliError:ya,readRecordBoolean:Ci,readRecordNumber:Mn,readRecordString:fe,recordCliReadOutputInvocationProvenance:bi,registerDynamicExtensionCommandPaths:sa,registerRuntimeSchemaFieldFlags:ji,resolveCoreCommandRegistrationSelection:ma,resolveStaticExtensionActivationDecision:Yi,resolveUnknownHelpToken:hn,readThrownExitCode:Ut,runAndClearAfterCommandHooks:Le,runRequiredExtensionCommand:ra,shouldAttachRichHelpTextForInvocation:pa,shouldLogHandledErrorToSentry:$i,shouldRegisterDynamicExtensionPaths:fa,shouldRegisterRuntimeSchemaFlags:ga,shouldHandleRunPmCliCommanderError:ka,setActiveExtensionHookContextForTest:Zl,setActiveRuntimeExtensionCommandDescriptorsForTest:Ql,setRecoveredExtensionServices:wa,toLooseFieldDefinitionType:An,isImporterOrExporterCommandPath:Ni,validateDynamicExtensionCommandInvocation:Fi,wrapProgramActionsForExtensionHandlers:ia,wrapThrownErrorForSentry:Ht};export{cm as _testOnly,lm as runPmCli};
31
31
  //# sourceMappingURL=main.js.map