@unbrained/pm-cli 2026.10.23 → 2026.10.24

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 (137) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +21 -0
  3. package/dist/cli/error-guidance.js +2 -2
  4. package/dist/cli-bundle/bundle-manifest.json +1 -1
  5. package/dist/cli-bundle/chunks/{chunk-MTRYEVZR.js → chunk-3VI4XDP2.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-AAX7CNL7.js → chunk-4PNAUT2E.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-2UX2TAN2.js → chunk-CDR5ES7Q.js} +54 -54
  8. package/dist/cli-bundle/chunks/chunk-CNEUJHA4.js +2 -0
  9. package/dist/cli-bundle/chunks/{chunk-AXGFNNI3.js → chunk-CSE47ZAN.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-ZEI3DC5E.js → chunk-FASDGYQC.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-5DKCD4KV.js → chunk-HZNFNETE.js} +35 -34
  12. package/dist/cli-bundle/chunks/{chunk-KY34HTT2.js → chunk-KGZGXC7T.js} +29 -29
  13. package/dist/cli-bundle/chunks/{chunk-REXCO5AG.js → chunk-MA7SNKYK.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-ZNDYAZZ6.js → chunk-TZYQ4JDZ.js} +3 -3
  15. package/dist/cli-bundle/chunks/{chunk-F76ZUP73.js → chunk-URZB3USE.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-UY5UHI4I.js +2 -0
  17. package/dist/cli-bundle/chunks/{chunk-MMVX5L32.js → chunk-VPMQEVU6.js} +14 -14
  18. package/dist/cli-bundle/chunks/{chunk-ZMJF5HQW.js → chunk-VSSHB6XI.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-5V4HU6GK.js → chunk-YEI4N4A6.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-HDKY2YX3.js → chunk-Z62RXNHW.js} +2 -2
  21. package/dist/cli-bundle/chunks/{mutation-admission-P6LOBNLO.js → mutation-admission-NVTBZ7DH.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-list-query-JOB65KDN.js → register-list-query-2FE6K7FQ.js} +2 -2
  23. package/dist/cli-bundle/chunks/{register-mutation-QMNIN3RJ.js → register-mutation-KZXQUZUH.js} +2 -2
  24. package/dist/cli-bundle/chunks/{register-operations-Z4VET3I7.js → register-operations-BOCBWNKJ.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-setup-GNKWL3VL.js → register-setup-P3VLCTDY.js} +2 -2
  26. package/dist/cli-bundle/chunks/{stage-FW5OXCCR.js → stage-WRDTMCCF.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-LEHGCPZ6.js → chunk-3QYTS4OY.js} +4 -4
  28. package/dist/cli-bundle/focused-chunks/{chunk-I2USTQNQ.js → chunk-5MKNVJCM.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-CGL36F6I.js → chunk-6HJCSHBG.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-OMXMYTEX.js → chunk-7RQOFHMH.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/chunk-AGCEWJ27.js +21 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-BM652VCB.js → chunk-CEEOWDB7.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-NSMZY6IK.js → chunk-ES2NGVHZ.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/chunk-GXAXDPD4.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-P7DPS5M4.js → chunk-IUAYTD2S.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-DWQMYLFM.js → chunk-JYXA4JIP.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-XIZYJDYW.js → chunk-NFFPNMTH.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-MLET6I3I.js → chunk-NX7TVNUM.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-UNTCCJPL.js → chunk-POLMFGPQ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-ZHMF34DT.js → chunk-RSEGFZTY.js} +52 -52
  41. package/dist/cli-bundle/focused-chunks/{chunk-4MNUQCGR.js → chunk-RVUGTIIU.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-6GTZ24YV.js → chunk-SBJ2IKTH.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-EDXTOAXP.js → chunk-SHUPX6G2.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-KI5YFKNN.js → chunk-TAHSXKAT.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/chunk-X5YRJMAY.js +2 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-XTYEASIY.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-ZMWLV2CE.js +91 -0
  48. package/dist/cli-bundle/focused-chunks/{mutation-admission-HTFAIHJL.js → mutation-admission-PB6YFY7S.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{stage-X3BUGEJT.js → stage-MQE4PFWT.js} +2 -2
  50. package/dist/cli-bundle/main.js +21 -21
  51. package/dist/cli-bundle/sdk-authoring.js +1 -1
  52. package/dist/cli-bundle/sdk-contracts.js +1 -1
  53. package/dist/cli-bundle/sdk-core.js +24 -24
  54. package/dist/cli-bundle/sdk-governance.js +1 -1
  55. package/dist/cli-bundle/sdk-graph.js +1 -1
  56. package/dist/cli-bundle/sdk-merge.js +53 -53
  57. package/dist/cli-bundle/sdk-query.js +1 -1
  58. package/dist/cli-bundle/sdk-runtime.js +1 -1
  59. package/dist/cli-bundle/sdk-testing.js +1 -1
  60. package/dist/cli-bundle/sdk.js +9 -9
  61. package/dist/core/checkpoint/mutation-checkpoint.d.ts +6 -3
  62. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  63. package/dist/core/checkpoint/mutation-context.d.ts +10 -0
  64. package/dist/core/checkpoint/mutation-context.js +2 -0
  65. package/dist/core/store/item-store.js +1 -1
  66. package/dist/sdk/agent/command-recovery.d.ts +1 -0
  67. package/dist/sdk/agent/command-recovery.js +1 -1
  68. package/dist/sdk/agent/linked-resource-recovery.d.ts +13 -0
  69. package/dist/sdk/agent/linked-resource-recovery.js +2 -0
  70. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  71. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +3 -2
  72. package/dist/sdk/core.d.ts +1 -1
  73. package/dist/sdk/core.js +1 -1
  74. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  75. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  76. package/dist/sdk/index.d.ts +1 -0
  77. package/dist/sdk/index.js +1 -1
  78. package/dist/sdk/lifecycle/checkpoint-rollback.d.ts +7 -0
  79. package/dist/sdk/lifecycle/checkpoint-rollback.js +2 -0
  80. package/dist/sdk/lifecycle/close-many.d.ts +1 -1
  81. package/dist/sdk/lifecycle/close-many.js +1 -1
  82. package/dist/sdk/lifecycle/update-many.d.ts +1 -1
  83. package/dist/sdk/lifecycle/update-many.js +1 -1
  84. package/dist/sdk/public-surface.json +1 -1
  85. package/dist/sdk/query/context.d.ts +2 -1
  86. package/dist/sdk/query/context.js +1 -1
  87. package/dist/sdk/query/get.d.ts +2 -1
  88. package/dist/sdk/query/get.js +1 -1
  89. package/dist/sdk/query/list.d.ts +2 -1
  90. package/dist/sdk/query/list.js +1 -1
  91. package/dist/sdk/query/search/types.d.ts +2 -1
  92. package/dist/sdk/query.d.ts +1 -0
  93. package/dist/sdk/query.js +1 -1
  94. package/dist/sdk/read-output-contracts.d.ts +10 -2
  95. package/dist/sdk/read-output-contracts.js +1 -1
  96. package/dist/sdk/runtime-input.js +1 -1
  97. package/dist/sdk/runtime-primitives.d.ts +1 -0
  98. package/dist/sdk/runtime-primitives.js +1 -1
  99. package/dist/sdk/runtime.d.ts +10 -10
  100. package/dist/sdk/runtime.js +1 -1
  101. package/dist/sdk/test/batch.js +2 -2
  102. package/dist/sdk/test/entry.d.ts +5 -1
  103. package/dist/sdk/test/entry.js +2 -1
  104. package/dist/sdk/test/execution.js +2 -2
  105. package/docs/COMMANDS.md +21 -2
  106. package/docs/READ_OUTPUT_CONTRACTS.md +15 -0
  107. package/docs/SDK.md +45 -0
  108. package/docs/TESTING.md +28 -0
  109. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +5 -3
  110. package/marketplace.json +1 -1
  111. package/package.json +1 -1
  112. package/packages/pm-beads/package.json +1 -1
  113. package/packages/pm-calendar/package.json +1 -1
  114. package/packages/pm-command-kit/package.json +1 -1
  115. package/packages/pm-digital-twin/package.json +1 -1
  116. package/packages/pm-governance-audit/package.json +1 -1
  117. package/packages/pm-guide-shell/package.json +1 -1
  118. package/packages/pm-kanban/package.json +1 -1
  119. package/packages/pm-lifecycle-hooks/package.json +1 -1
  120. package/packages/pm-linked-test-adapters/package.json +1 -1
  121. package/packages/pm-search-advanced/package.json +1 -1
  122. package/packages/pm-templates/package.json +1 -1
  123. package/packages/pm-todos/package.json +1 -1
  124. package/packages/pm-vcs/package.json +1 -1
  125. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  126. package/plugins/pm-claude/package.json +1 -1
  127. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  128. package/plugins/pm-codex/package.json +1 -1
  129. package/plugins/pm-codex/plugin.json +1 -1
  130. package/runtime-dependencies.json +1 -1
  131. package/dist/cli-bundle/chunks/chunk-2LTGJ5DL.js +0 -2
  132. package/dist/cli-bundle/chunks/chunk-QSY55FTA.js +0 -2
  133. package/dist/cli-bundle/focused-chunks/chunk-FO4U3FIP.js +0 -91
  134. package/dist/cli-bundle/focused-chunks/chunk-GXKP56W7.js +0 -2
  135. package/dist/cli-bundle/focused-chunks/chunk-JDN34LEZ.js +0 -2
  136. package/dist/cli-bundle/focused-chunks/chunk-Z5LDTMZ3.js +0 -2
  137. package/dist/cli-bundle/focused-chunks/chunk-ZR6ZKQUK.js +0 -20
@@ -1,10 +1,10 @@
1
- import"./chunks/chunk-DEZPZOQ7.js";import{A as yi,C as _i,D as wn,a as sn,d as N,e as D,f as A,g as K,h as x,i as Fa,n as Ge,o as La,p as Ha,t as za,u as ui,v as fi,w as gi,x as _n,z as hi}from"./chunks/chunk-REXCO5AG.js";import{a as de,b as ln,c as cn,d as dn,e as mn}from"./chunks/chunk-3S5FLCG7.js";import{Ta as pi,f as Aa,i as Da}from"./chunks/chunk-2UX2TAN2.js";import"./chunks/chunk-HDKY2YX3.js";import"./chunks/chunk-ZNDYAZZ6.js";import{F as li,b as ai,d as xt,g as ii,h as ri,i as J,j as si,md as mi,rc as di}from"./chunks/chunk-KY34HTT2.js";import"./chunks/chunk-QSY55FTA.js";import{ea as ci,g as Ma}from"./chunks/chunk-5V4HU6GK.js";import{a as $a}from"./chunks/chunk-MMVX5L32.js";import"./chunks/chunk-4D25HF3V.js";import{$d as ke,Ae as ei,Be as ti,Bf as Ct,Cf as kt,Df as hn,Ef as Ve,Ff as E,Gf as ni,H as _t,Hf as yn,I as Pa,Lf as L,Rb as Na,Sb as ne,Sd as Ga,Td as un,Ub as ja,Ud as bt,Vb as Ua,Vd as Wa,W as wt,Wd as Va,Xb as qa,Xd as Ba,Y as He,Yd as Ka,Z as vt,Zd as fn,Zf as oi,_d as Ja,ce as Ya,de as Xa,ja as ze,oe as We,re as Za,ue as Qa,ze as gn}from"./chunks/chunk-5DKCD4KV.js";import"./chunks/chunk-RUKSEZE7.js";import"./chunks/chunk-ZEI3DC5E.js";import"./chunks/chunk-IB7UB5TE.js";import{$b as we,A as Zo,Aa as B,Ai as Ia,Cd as C,D as Fe,Db as en,Dd as qe,Hc as ca,Ic as da,J as Xt,Jc as ma,Kc as pa,Kf as Sa,Lc as te,Lf as be,Mc as ua,N as Qo,Nc as nn,Nf as rn,Ob as oa,Oc as se,Of as _,Pc as fa,Qc as ut,Tc as ve,Uc as le,Xb as ee,Xc as ga,Yc as ft,_b as aa,ac as tn,bc as pt,be as _a,cd as on,ce as an,d as R,dd as gt,ed as ha,f as q,fc as ia,fd as ya,fh as Ta,g as I,gh as Oa,hb as Le,hc as ra,i as W,if as xa,j as Yt,k as H,l as Yo,ma as Zt,mf as Ea,og as pn,oh as ht,pa as re,pe as wa,qe as va,ra as ea,re as ba,sa as mt,se as Ca,si as yt,te as ka,uc as sa,va as Qt,vc as je,vi as Ra,wa as ta,xa as S,xc as Ue,yc as la,yf as ce,yi as Ce,z as Xo,za as na,zi as $}from"./chunks/chunk-F76ZUP73.js";import"./chunks/chunk-ZDVTXLA6.js";import"./chunks/chunk-VS565KBX.js";import{A as g,B as dt,C as b,E as V}from"./chunks/chunk-R7KWBFM2.js";import"./chunks/chunk-XAWE4EAK.js";import{Command as jo,CommanderError as zr}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="50318c14-8c1c-50f3-95d0-fd9ea3f0bb69")}catch{}})();function j(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function me(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return j(t)}function Y(e){let t=new Set,n=[];for(let o of e){let a=me(o);a&&(t.has(a)||n.push(a),t.add(a))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0b95b409-ef2c-59da-a628-16a2cb4f0ea6")}catch{}})();var vn=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),Et=new Set(["--full","--brief","--compact"]);function Cs(e,t){return!!(e.flag==="--pm-path"||e.value_name||e.list||e.value_type==="number"||e.value_type==="string"||t.has(e.flag))}function ks(e){let t=ne(x([...e])),n=new Set([...ja,...Ua,...qa].flatMap(r=>r.keys.map(s=>`--${s.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),o=new Map([...ze,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,r.flag]))),a=new Map([...ze,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,Cs(r,n)])));for(let r of vn)a.set(r,!0);for(let r of Et)a.set(r,!1);let i=new Map;for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="--")break;if(!s.startsWith("-"))continue;let l=s.split("=")[0];if(!a.has(l)&&!s.includes("="))return;i.set(r,o.get(l)??l),a.get(l)&&!s.includes("=")&&(r+=1)}return i}function wi(e,t,n){let o=new Set;for(let[a,i]of t)n.has(i)&&(o.add(a),vn.has(i)&&!e[a].includes("=")&&o.add(a+1));return e.filter((a,i)=>!o.has(i))}function xs(e,t){let n=t.find(a=>Et.has(a));if(n===void 0)return;let o=[...new Set(e.values())].filter(a=>Et.has(a));return o.length===1?o[0]:n}function vi(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,a={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return a;let i=ks(e);if(!i)return a;let r;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return a;let l=[...i].find(([c,d])=>d==="--fields")?.[0]??-1;if(l<0)return a;r=wi(e,i,new Set(["--fields"])),r.splice(l,0,"--fields",o[s+1])}else{let s=xs(i,o);if(s===void 0||![...i.values()].includes(s))return a;let l=new Set([...vn,...Et].filter(c=>c!==s));r=wi(e,i,l)}return{...n,suggested_retry:C(r),suggested_retry_args:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afa4a7a0-d9de-529d-92dd-3e9704ea00d2")}catch{}})();async function bi(e,t){await ei(e,{ok:t.ok,error:t.error,result:le(),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 Ci(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await xa({pmRoot:e.pmRoot,result:le()})}catch(o){t=o}let n=await $(e.pmRoot);if(await Ea({pmRoot:e.pmRoot,author:ht(e.author,n.author_default),itemIds:e.itemIds,intent:e.intent}),t!==void 0)throw t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dacf3952-3ae1-57fa-840a-c8a43cf855a5")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5efa5c0f-8a74-5b20-bc2d-0016fe62411b")}catch{}})();var ki=new WeakMap;function St(e,t){ki.set(e,t)}function pe(e){return ki.get(e)}function xi(e){return e.length>0?[e[0]]:[]}function Es(e){let t=["","Intent:",` ${e.why}`],n=xi(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
- `)}function Ss(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(`
3
- `)}function Ei(e,t){return t==="detailed"?Ss(e):Es(e)}function M(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var As={cal:"calendar",ctx:"context"};function Ts(e,t){return e.commands.find(n=>n.name()===t)??null}function Os(e,t){let n=e;for(let o of t){let a=Ts(n,o);if(!a)return null;n=a}return n}function bn(e,t,n,o){let a=Os(e,t.split(" ").filter(i=>i.length>0));a&&a.addHelpText("after",Ei(n,o))}function Cn(e){return e.includes("--explain")?"detailed":"compact"}function oe(e){return e.includes("--all")||e.includes("--explain")}var ue={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm package install ./my-package --project","pm package install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm package install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm package upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm package install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm package install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm package install ./my-extension --project","pm package --install --project ./my-extension","pm package doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list --all --limit 50","pm list --all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status in_progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list --blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm package install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"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 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:["pm claim pm-a1b2 --start",'pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of R){let n=ue[e];n&&(ue[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var xe={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},Si=W.filter(e=>e.lifecycle==="deprecated");for(let e of Si){let t=ue[e.alias];ue[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[xe,...Object.values(ue)])e.examples=e.examples.map(t=>{for(let n of Si){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Rs(e){let t=M(e??"");return t?As[t]??t:""}function kn(e){let t=Rs(e);return t?ue[t]??xe:xe}function Ai(e,t){let n=kn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:xi(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Is(){let e=W.filter(({lifecycle:n})=>n==="permanent"),t=W.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(`
4
- `)}function $s(e,t,n,o){let a=new Set(ii);e.configureHelp({visibleCommands(r){let s=t.visibleCommands(r);return n?s.filter(l=>(pe(l)??J(l.name()))!=="internal"):r!==e?s:s.filter(l=>o.has(l))},visibleOptions(r){let s=t.visibleOptions(r);return r!==e||n?s:s.filter(l=>a.has(l.flags))}});let i=e.options.filter(r=>r.long==="--output-cursor");for(let r of e.commands.flatMap(s=>[s,...s.commands]))["list","search","context"].includes(r.name())&&r.configureHelp({visibleOptions:s=>[...t.visibleOptions(s),...i]})}function Ps(e,t,n,o){let a=new Set(si("core")),i=e.createHelp();i.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let r=()=>`${i.formatHelp(e,i)}${o}
5
- `,s=t.visibleCommands(e);for(let l of s)pe(l)===void 0&&(l.name()==="help"||a.has(l.name()))&&n.add(l);for(let l of s)pe(l)==="core"&&(n.add(l),ri(r()).within_budget||n.delete(l))}function Ti(e,t=process.argv.slice(2)){let n=e.createHelp(),o=oe(t),a=new Set;$s(e,n,o,a);let i=Cn(t),r=Ei(xe,i);e.addHelpText("after",r),o&&e.addHelpText("after",Is()),Ps(e,n,a,r);for(let[d,m]of Object.entries(ue))bn(e,d,m,i);let s=M(A(t).commandPathTokens.join(" ")),l=He(s);if(l){bn(e,l.parent,{why:l.description,examples:[l.example],tips:[`Action path: pm ${l.command}`,vt(l.accepted_flags)]},i);return}let c=wt.filter(({parent:d})=>d===s);c.length>0&&bn(e,s,{why:`Dispatches one declared positional action: ${c.map(({action:d})=>d).join("|")}.`,examples:c.map(({example:d})=>d),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]="2efeb172-b440-5df6-ad48-4c54087835e0")}catch{}})();function xn(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:a}of R){if(t&&!R.some(c=>c.canonical.startsWith(`${o} `)))continue;let i=e.commands.findIndex(c=>c.name()===n);if(i<0)continue;let r=e.commands[i],s=e;for(let c of a.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===c)??s.command(c).description(`Discover ${c} operations.`);let l=a[a.length-1];if(s.commands.some(c=>c.name()===l))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(i,1),r.name(l),St(r,J(o)),s.enablePositionalOptions(),s.addCommand(r)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66e52448-b814-50c5-894e-42e54244a442")}catch{}})();function Ot(e){let{why:t,title:n,...o}=e;return o}var Ds=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Ms(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Ds.has(e.code)}function Pi(e){return`urn:pm-cli:error:${e}`}function k(e){return{...e,type:Pi(e.code)}}var Ee={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Oi={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Ri={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},At={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Ns={guide:Ee,shell:Ee,completion:Ee,"completion-statuses":Ee,"completion-tags":Ee,"completion-types":Ee,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Oi,cal:Oi,reindex:Ri,"search-advanced":Ri,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":At,"dedupe-audit":At,"dedupe-merge":At,normalize:At};function Fs(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Ns[t]}function En(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Ls(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 js(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 Sn(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function Di(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")?[...e]:void 0}function X(e,t,n){if(t==="normalized_args"||t==="suggested_retry_args"){let a=Di(n);a&&(e[t]=a);return}if(t==="parsed_positionals"){if(!Array.isArray(n))return;let a=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);a.length>0&&(e.parsed_positionals=a);return}let o=Ls(n);o&&(e[t]=o)}function Us(e,t){if(!$a(t))return;let{requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:a,minimum_status:i,basis:r,reason:s}=t;e.token_budget={requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:a,minimum_status:i,basis:r,reason:s}}var Mi=["retry_after_ms","waited_ms","owner_handoffs"];function qs(e,t){for(let n of Mi)typeof t[n]=="number"&&e.push(` ${n}: ${t[n]}`)}function Hs(e,t){for(let n of Mi){let o=t[n];typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&(e[n]=o)}}function Se(e){if(!e||typeof e!="object")return;let t={};Us(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Sn(t,"attempted_command",e.attempted_command),X(t,"normalized_args",e.normalized_args),X(t,"parsed_positionals",e.parsed_positionals),X(t,"provided_fields",e.provided_fields),X(t,"missing",e.missing),X(t,"missing_required_fields",e.missing_required_fields),X(t,"suggested_flags",e.suggested_flags),X(t,"allowed_values",e.allowed_values),X(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),Sn(t,"suggested_retry",e.suggested_retry),X(t,"suggested_retry_args",e.suggested_retry_args),Hs(t,e);let n=js(e.fallback_candidates);return n&&(t.fallback_candidates=n),Sn(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function An(e,t,n){n&&e.push(` ${t}: ${n}`)}function fe(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function zs(e){let t=Se(e);if(!t)return[];let n=["Recovery bundle:"];if(t.token_budget){let o=t.token_budget;n.push(` requested_token_budget: ${o.requested_tokens}`,` feasible_token_budget: ${o.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${o.minimum_feasible_tokens??"not established"}`)}if(An(n,"suggested_retry",t.suggested_retry),An(n,"attempted_command",t.attempted_command),fe(n,"normalized_args",t.attempted_command?void 0:t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(fe(n,"provided_fields",t.provided_fields,", "),fe(n,"missing",t.missing,", "),fe(n,"missing_required_fields",t.missing_required_fields,", "),fe(n,"suggested_flags",t.suggested_flags,", "),fe(n,"allowed_values",t.allowed_values,", "),fe(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}`),qs(n,t),An(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 Ni(e){let t=[`Error: ${e.title}`,"","What is required:",` ${e.required}`];e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...En("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(...En("Examples:",e.examples))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...En("Verification errors:",e.verificationErrors)));let n=zs(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
6
- `)}function Gs(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId)}function Fi(e,t){return t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),Gs(e,t),Ms(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 Ws(e,t){if(e.flag)return e.flag;let n=o=>{let a=o.split("=",1)[0];return D([a]).length>0&&!["--help","--no-changed-fields","--version"].includes(a)&&t.some(i=>i===a||i.startsWith(`${a}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(o=>o[0]).find(o=>n(o))}function Vs(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(i=>i===n||i.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let a=t.indexOf(n);return t[a+1]}}function Bs(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=D(e.recovery?.normalized_args??[]),o=q(n),a=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,i=Ws(e,a),r=Vs(e,a,i);return{surface:i??e.recovery?.missing?.[0]??_n(a)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Ks(e,t){return Fi({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Bs(e,t),...e.changed===!1?{changed:!1}:{}},e)}function On(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 _a(Ks(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function Rn(e){return Fi({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function Rt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Js(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 ge(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 Ii(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Ys(e){return _n(e?.normalized_args)}function Xs(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 Zs(e,t){let n=e?.normalized_args,o=e?.provided_fields,a=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!a))for(let i of o){let r=n.findIndex(s=>s===i);if(r>=0&&r<n.length-1&&!n[r+1]?.startsWith("-")){let s=[...n];return s[r+1]=a,C(s)}}}function Qs(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Tt(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function el(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function ae(e,t,n){if(!n)return e;let o=Rt(t),a=Tt(n.code,e.code),i=Tt(n.type,Pi(a)),r=ge(n.examples)??e.examples,s=ge(n.nextSteps)??e.nextSteps,l=ge(n.verification_errors)??e.verificationErrors,c=e.code==="command_failed"&&n.code?Qs(o):void 0,d=Se(n.recovery),m=d&&e.recovery?Se({...e.recovery,...d}):d??e.recovery;return{...e,code:a,changed:n.changed,type:i,title:c??e.title,happened:o.length>0?o:e.happened,required:Tt(n.required,e.required),why:Tt(n.why,e.why),examples:r,nextSteps:s,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:el(n,m)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,availableDependencies:n.available_dependencies,recovery:m}}function tl(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 a=o[1],i=ta(process.cwd(),a);return ae(k(i?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${a}, 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 nl(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let a=o[1],i=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(a),r=i?`The item ID "${a}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${a}" exists in the active tracker scope.`;return ae(k({code:"item_not_found",title:"Item ID not found",flag:"id",value:a,happened:r,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps: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 ol(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ae(k({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 al(e,t,n){if(!t.includes("is locked"))return null;let o=Di(n?.recovery?.normalized_args),a=o?C(o):void 0,i=ae(k({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:a?[a]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(i.recovery={...i.recovery,suggested_retry:a,suggested_retry_args:[...o]}),i}function il(e,t,n){let o=t.match(/^Missing required option /),a=t.match(/^Missing required options /);if(!o&&!a)return null;let i=!!a,r=i?null:t.replace(/^Missing required option\s+/,"").trim(),s=r??"",l=r?`Pass ${r} with a valid value before running the command.`:"Provide the required option for this command invocation.";return ae(k({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 rl(e,t,n){return t.startsWith("No update flags provided")?ae(k({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 sl(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=Se(n?.recovery),a=Ys(o),i=a?`pm ${a} --help`:"pm <command> --help",r=Xs(t),s=Se({...o,allowed_values:o?.allowed_values??r}),l=Zs(o,r),c=l?[l,i]:[i,"pm contracts --command <command> --flags-only --json"],d=r.length>0?[`Allowed values: ${r.join("|")}`,`Run "${i}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return ae(k({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:c,nextSteps:d,recovery:s}),e,n)}function In(e,t){let n=Rt(e);return(tl(e,n,t)??nl(e,n,t)??ol(e,n,t)??al(e,n,t)??il(e,n,t)??rl(e,n,t)??sl(e,n,t))||ae(k({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 ll(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 cl(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function dl(e){if(!(!Array.isArray(e)||e.length===0))return C(e)}function $n(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 U(e,t={}){let n=$n(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,a=typeof e?.attemptedCommand=="string"?e.attemptedCommand:dl(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Se({attempted_command:a,normalized_args:o,provided_fields:n,suggested_retry:i,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Tn(e,t){return!t||e.includes(t)?e:[...e,t]}var ml=new Set(["--add","--add-json","--remove"]),pl=new Set(["command","cmd","path"]);function ul(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(ml.has(o))return o}}function fl(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 a=e[o];if(a!=="--add"&&a!=="--remove")continue;let i=e[o+1];if(typeof i!="string"||!pl.has(i))return;let r=[];for(let c=o+2;c<e.length;c+=1){let d=e[c];if(d.startsWith("--")&&d.length>2)break;r.push(d)}if(r.length<2)return;let s=`${i}=${r.join(" ")}`,l=[...e.slice(0,o+1),s,...e.slice(o+2+r.length)];return C(l)}}function gl(e,t,n,o){let a=e.match(/required option '([^']+)' not specified/);if(!a)return null;let i=cl(a[1]),r=i.startsWith("--type"),s=o?.suggestedRetryCommand,l=$n(o?.providedOptionFlags),c=[i],d=ll(t,i,n),m=s?Tn(d,s):d,p=r?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Tn(p,`Replay with preserved arguments: ${s}`):p,f=l&&l.length>0?Tn(u,`Already provided options: ${l.join(", ")}`):u;return k({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:r?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:U(o,{missing:c})})}function hl(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let a=o[1];return k({code:"missing_required_argument",title:`Missing required argument ${a}`,happened:`Command invocation omitted positional argument ${a}.`,required:`Provide ${a} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:U(n,{missing:[a]})})}function yl(e,t,n){return k({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:U(t,{suggested_flags:n})})}var _l={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 wl(e){let t=ge(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function vl(e,t,n,o,a){let i=o.otherCommands.slice(0,3),r=o.candidateTotal-i.length,s=r>0?` and ${String(r)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i.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,a?`Replay with suggested correction: ${a}`:void 0].filter(l=>typeof l=="string")}function bl(e,t,n){let o=ui(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:C(o),suggestedRetryArgs:o}:["--full","--depth","--toon"].includes(t.split("=",1)[0])?{}:void 0}function Cl(e,t,n){if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=bl(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(fi(t))return{};let a=e.normalizedInvocationArgs;if(a===void 0)return{};if(a.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let i=a.findIndex(s=>s===t||s.startsWith(`${t}=`));if(i<0||a.includes("--")||!a[i]?.includes("=")&&i!==a.length-1&&a[i+1]?.startsWith("-")!==!0)return{};let r=D(a.filter((s,l)=>l!==i));return{retryCommand:C(r),suggestedRetryArgs:r}}function kl(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let a=n??{},i=o[1],r=$n(a.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=Cl(a,i,t);if(t==="update"&&(i==="--file"||i==="--doc"))return yl(i,n,r);let c=wl(a),d=vl(i,t,r,c,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(i.split("=",1)[0])&&d.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${H(t)?.canonical??t} --help`:"pm --help --all"].filter(p=>typeof p=="string");return k({code:"unknown_option",title:`Unknown option ${i}`,happened:`Commander does not recognize option ${i} for this command path.`,required:_l[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:i,value:i,examples:m,nextSteps:d,recovery:U(n,{suggested_flags:r.length>0?r:void 0,suggested_retry:s,suggested_retry_args:l,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:a.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function xl(e,t,n,o,a){let i=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,r=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return k({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:Ii([t.installCommand,...n]),nextSteps:Ii([i,...r]),recovery:U(a)})}function El(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],a=ge(t?.unknownCommandExamples),i=ge(t?.unknownCommandNextSteps),r=Fs(o),s=a??["pm --help"],l=i??["Verify spelling and active extensions, then rerun."],c=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=r?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return r&&(!d||!c.has(d))?xl(o,r,s,l,t):k({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:U(t)})}function Sl(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ge(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let a=e?.suggestedRetryCommand;return k({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...a?[a]:[],`pm ${H(t)?.canonical??t} --help`],nextSteps:a?[`Retry with the declared hyphenated action: ${a}`]:["Choose one value from recovery.allowed_values."],recovery:U(e,{allowed_values:o,suggested_retry:a})})}function Al(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,a=ul(o);if(!a)return null;let i=fl(o);return k({code:"linked_test_value_not_quoted",title:`Linked-test ${a} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${a} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${a} 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:U(n,i?{suggested_retry:i}:{})})}var Tl=new Set(["comments","docs","files","learnings","notes","test"]);function Ol(e,t,n){if(!/too many arguments/i.test(e)||!Tl.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],a=o.findIndex(c=>c===t),i=o[a+1],r=o[a+2],s=n?.verifiedCollectionItemId?.trim();if(i?.toLowerCase()!=="add"||!r||r.startsWith("-")||!s||s.toLowerCase()!==r.toLowerCase())return null;let l=`pm ${t} ${s} --add <value>`;return k({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:U(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:l})})}var Rl=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"]),$i=new Set(["context","ctx"]);function Il(e,t,n){if(!/too many arguments/i.test(e)||!$i.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],a=o.findIndex(c=>$i.has(c)),i=a===-1?1:a+1,r=e.match(/got \d+:\s*(\S+)/i),s=r?r[1].replace(/\.$/,""):void 0;if(s===void 0){let c=!1;for(let d of o.slice(i)){if(c){c=!1;continue}let m=d.split("=")[0];if(Rl.has(m)){c=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let l=`pm get ${s}`;return k({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:U(n,{suggested_retry:l})})}function Pn(e,t,n,o){let a=Rt(e);return(gl(a,t,n,o)??hl(a,t,o)??kl(a,t,o)??El(a,o)??Sl(o)??Ol(a,t,o)??Al(a,t,o)??Il(a,t,o))||k({code:"invalid_command_usage",title:"Invalid command usage",happened:a,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:U(o)})}function Li(e,t){let n=In(e,t);return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&n.title==="Tracker is not initialized"&&n.recovery?.suggested_retry_args?[`Error: ${n.title}`,`Run: ${C(n.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
7
- `):an(Ni(n),n.required).output}function ji(e,t){return Rn(In(e,t))}function Dn(e,t,n){return On(In(e,n),t)}function Ui(e,t,n,o){let a=Pn(e,t,n,o);return an(Ni(a),a.required).output}function Mn(e,t,n,o){return Rn(Pn(e,t,n,o))}function It(e,t,n,o,a){return On(Pn(e,t,n,a),o)}function qi(e,t){let n=Hi(e);return On(n,t)}function Hi(e){let t=Rt(e);return Js(t)?k({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."]}):k({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 zi(e){return Rn(Hi(e))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4647d40c-70a2-5ffe-a91f-d43e9c522114")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3c73e79-571d-5a1b-94cd-db8c1b8ca7a4")}catch{}})();var Be=Qo.join("|"),$l={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"},Pl={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"]}},Gi=["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=Pl[e];if(!n)return[];let o=j(t);for(let[a,i]of Object.entries(n))if(j(a)===o)return i;return[]}function Nn(e,t,n){if(n.length===0)return e;if(t){let r=n.find(d=>d.declared_command_match===!0),{token_accounting:s,...l}=JSON.parse(e),c={...l,...r?{extension_command_failure:{code:"extension_command_activation_failed",extension:r.name,layer:r.layer,error:r.error,recovery_commands:r.recovery_commands??[]}}:{},failed_extensions:n};return JSON.stringify(s===void 0?c:ce(c,d=>`${JSON.stringify(d,null,2)}
1
+ import"./chunks/chunk-DEZPZOQ7.js";import{A as _i,C as wi,D as wn,a as sn,d as N,e as D,f as A,g as K,h as x,i as Fa,n as Ge,o as La,p as Ha,t as za,u as fi,v as gi,w as hi,x as _n,z as yi}from"./chunks/chunk-MA7SNKYK.js";import{a as de,b as ln,c as cn,d as dn,e as mn}from"./chunks/chunk-3S5FLCG7.js";import{Ta as ui,f as Aa,i as Da}from"./chunks/chunk-CDR5ES7Q.js";import"./chunks/chunk-Z62RXNHW.js";import"./chunks/chunk-TZYQ4JDZ.js";import{F as ci,b as ii,d as xt,g as ri,h as si,i as J,j as li,md as pi,rc as mi}from"./chunks/chunk-KGZGXC7T.js";import"./chunks/chunk-UY5UHI4I.js";import{ea as di,g as Ma}from"./chunks/chunk-YEI4N4A6.js";import{a as $a}from"./chunks/chunk-VPMQEVU6.js";import"./chunks/chunk-4D25HF3V.js";import{$d as Wa,Ae as Qa,Dc as Ga,De as ei,I as _t,Ie as gn,J as Pa,Je as ti,Ke as ni,Kf as Ct,Lf as kt,Mf as hn,Nf as Ve,Of as E,Pf as oi,Qf as yn,Sb as Na,Tb as ne,Uf as j,Vb as ja,Wb as Ua,X as wt,Yb as qa,Z as He,_ as vt,ae as un,be as bt,ce as Va,de as Ba,ee as Ka,fe as Ja,ge as fn,gg as ai,he as Ya,ie as ke,ka as ze,le as Xa,me as Za,xe as We}from"./chunks/chunk-HZNFNETE.js";import"./chunks/chunk-RUKSEZE7.js";import"./chunks/chunk-FASDGYQC.js";import"./chunks/chunk-IB7UB5TE.js";import{$b as we,A as Zo,Aa as B,Ai as Ia,Cd as b,D as Fe,Db as en,Dd as qe,Hc as ca,Ic as da,J as Xt,Jc as ma,Kc as pa,Kf as Sa,Lc as te,Lf as be,Mc as ua,N as Qo,Nc as nn,Nf as rn,Ob as oa,Oc as se,Of as _,Pc as fa,Qc as ut,Tc as ve,Uc as le,Xb as ee,Xc as ga,Yc as ft,_b as aa,ac as tn,bc as pt,be as _a,cd as on,ce as an,d as R,dd as gt,ed as ha,f as q,fc as ia,fd as ya,fh as Ta,g as I,gh as Oa,hb as Le,hc as ra,i as W,if as xa,j as Yt,k as H,l as Yo,ma as Zt,mf as Ea,og as pn,oh as ht,pa as re,pe as wa,qe as va,ra as ea,re as ba,sa as mt,se as Ca,si as yt,te as ka,uc as sa,va as Qt,vc as je,vi as Ra,wa as ta,xa as S,xc as Ue,yc as la,yf as ce,yi as Ce,z as Xo,za as na,zi as $}from"./chunks/chunk-URZB3USE.js";import"./chunks/chunk-ZDVTXLA6.js";import"./chunks/chunk-VS565KBX.js";import{A as g,B as dt,C,E as V}from"./chunks/chunk-R7KWBFM2.js";import"./chunks/chunk-XAWE4EAK.js";import{Command as jo,CommanderError as Gr}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="50318c14-8c1c-50f3-95d0-fd9ea3f0bb69")}catch{}})();function U(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function me(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return U(t)}function Y(e){let t=new Set,n=[];for(let o of e){let a=me(o);a&&(t.has(a)||n.push(a),t.add(a))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0b95b409-ef2c-59da-a628-16a2cb4f0ea6")}catch{}})();var vn=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),Et=new Set(["--full","--brief","--compact"]);function ks(e,t){return!!(e.flag==="--pm-path"||e.value_name||e.list||e.value_type==="number"||e.value_type==="string"||t.has(e.flag))}function xs(e){let t=ne(x([...e])),n=new Set([...ja,...Ua,...qa].flatMap(r=>r.keys.map(s=>`--${s.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),o=new Map([...ze,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,r.flag]))),a=new Map([...ze,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,ks(r,n)])));for(let r of vn)a.set(r,!0);for(let r of Et)a.set(r,!1);let i=new Map;for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="--")break;if(!s.startsWith("-"))continue;let l=s.split("=")[0];if(!a.has(l)&&!s.includes("="))return;i.set(r,o.get(l)??l),a.get(l)&&!s.includes("=")&&(r+=1)}return i}function vi(e,t,n){let o=new Set;for(let[a,i]of t)n.has(i)&&(o.add(a),vn.has(i)&&!e[a].includes("=")&&o.add(a+1));return e.filter((a,i)=>!o.has(i))}function Es(e,t){let n=t.find(a=>Et.has(a));if(n===void 0)return;let o=[...new Set(e.values())].filter(a=>Et.has(a));return o.length===1?o[0]:n}function bi(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,a={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return a;let i=xs(e);if(!i)return a;let r;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return a;let l=[...i].find(([c,d])=>d==="--fields")?.[0]??-1;if(l<0)return a;r=vi(e,i,new Set(["--fields"])),r.splice(l,0,"--fields",o[s+1])}else{let s=Es(i,o);if(s===void 0||![...i.values()].includes(s))return a;let l=new Set([...vn,...Et].filter(c=>c!==s));r=vi(e,i,l)}return{...n,suggested_retry:b(r),suggested_retry_args:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="afa4a7a0-d9de-529d-92dd-3e9704ea00d2")}catch{}})();async function Ci(e,t){await ti(e,{ok:t.ok,error:t.error,result:le(),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 ki(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await xa({pmRoot:e.pmRoot,result:le()})}catch(o){t=o}let n=await $(e.pmRoot);if(await Ea({pmRoot:e.pmRoot,author:ht(e.author,n.author_default),itemIds:e.itemIds,intent:e.intent}),t!==void 0)throw t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dacf3952-3ae1-57fa-840a-c8a43cf855a5")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5efa5c0f-8a74-5b20-bc2d-0016fe62411b")}catch{}})();var xi=new WeakMap;function St(e,t){xi.set(e,t)}function pe(e){return xi.get(e)}function Ei(e){return e.length>0?[e[0]]:[]}function Ss(e){let t=["","Intent:",` ${e.why}`],n=Ei(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
+ `)}function As(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(`
3
+ `)}function Si(e,t){return t==="detailed"?As(e):Ss(e)}function M(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var Ts={cal:"calendar",ctx:"context"};function Os(e,t){return e.commands.find(n=>n.name()===t)??null}function Rs(e,t){let n=e;for(let o of t){let a=Os(n,o);if(!a)return null;n=a}return n}function bn(e,t,n,o){let a=Rs(e,t.split(" ").filter(i=>i.length>0));a&&a.addHelpText("after",Si(n,o))}function Cn(e){return e.includes("--explain")?"detailed":"compact"}function oe(e){return e.includes("--all")||e.includes("--explain")}var ue={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm package install ./my-package --project","pm package install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm package install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm package upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm package install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm package install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm package install ./my-extension --project","pm package --install --project ./my-extension","pm package doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list --all --limit 50","pm list --all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status in_progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list --blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm package install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"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 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:["pm claim pm-a1b2 --start",'pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of R){let n=ue[e];n&&(ue[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var xe={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},Ai=W.filter(e=>e.lifecycle==="deprecated");for(let e of Ai){let t=ue[e.alias];ue[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[xe,...Object.values(ue)])e.examples=e.examples.map(t=>{for(let n of Ai){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Is(e){let t=M(e??"");return t?Ts[t]??t:""}function kn(e){let t=Is(e);return t?ue[t]??xe:xe}function Ti(e,t){let n=kn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Ei(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function $s(){let e=W.filter(({lifecycle:n})=>n==="permanent"),t=W.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(`
4
+ `)}function Ps(e,t,n,o){let a=new Set(ri);e.configureHelp({visibleCommands(r){let s=t.visibleCommands(r);return n?s.filter(l=>(pe(l)??J(l.name()))!=="internal"):r!==e?s:s.filter(l=>o.has(l))},visibleOptions(r){let s=t.visibleOptions(r);return r!==e||n?s:s.filter(l=>a.has(l.flags))}});let i=e.options.filter(r=>r.long==="--output-cursor");for(let r of e.commands.flatMap(s=>[s,...s.commands]))["list","search","context"].includes(r.name())&&r.configureHelp({visibleOptions:s=>[...t.visibleOptions(s),...i]})}function Ds(e,t,n,o){let a=new Set(li("core")),i=e.createHelp();i.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let r=()=>`${i.formatHelp(e,i)}${o}
5
+ `,s=t.visibleCommands(e);for(let l of s)pe(l)===void 0&&(l.name()==="help"||a.has(l.name()))&&n.add(l);for(let l of s)pe(l)==="core"&&(n.add(l),si(r()).within_budget||n.delete(l))}function Oi(e,t=process.argv.slice(2)){let n=e.createHelp(),o=oe(t),a=new Set;Ps(e,n,o,a);let i=Cn(t),r=Si(xe,i);e.addHelpText("after",r),o&&e.addHelpText("after",$s()),Ds(e,n,a,r);for(let[d,m]of Object.entries(ue))bn(e,d,m,i);let s=M(A(t).commandPathTokens.join(" ")),l=He(s);if(l){bn(e,l.parent,{why:l.description,examples:[l.example],tips:[`Action path: pm ${l.command}`,vt(l.accepted_flags)]},i);return}let c=wt.filter(({parent:d})=>d===s);c.length>0&&bn(e,s,{why:`Dispatches one declared positional action: ${c.map(({action:d})=>d).join("|")}.`,examples:c.map(({example:d})=>d),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]="2efeb172-b440-5df6-ad48-4c54087835e0")}catch{}})();function xn(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:a}of R){if(t&&!R.some(c=>c.canonical.startsWith(`${o} `)))continue;let i=e.commands.findIndex(c=>c.name()===n);if(i<0)continue;let r=e.commands[i],s=e;for(let c of a.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===c)??s.command(c).description(`Discover ${c} operations.`);let l=a[a.length-1];if(s.commands.some(c=>c.name()===l))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(i,1),r.name(l),St(r,J(o)),s.enablePositionalOptions(),s.addCommand(r)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="90da2526-967a-5412-bf21-e7e34b5f8f2c")}catch{}})();function Ot(e){let{why:t,title:n,...o}=e;return o}var Ms=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Ns(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Ms.has(e.code)}function Di(e){return`urn:pm-cli:error:${e}`}function k(e){return{...e,type:Di(e.code)}}var Ee={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Ri={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Ii={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},At={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Fs={guide:Ee,shell:Ee,completion:Ee,"completion-statuses":Ee,"completion-tags":Ee,"completion-types":Ee,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Ri,cal:Ri,reindex:Ii,"search-advanced":Ii,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":At,"dedupe-audit":At,"dedupe-merge":At,normalize:At};function Ls(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Fs[t]}function En(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function js(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 Us(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 Sn(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function Mi(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")?[...e]:void 0}function X(e,t,n){if(t==="normalized_args"||t==="suggested_retry_args"){let a=Mi(n);a&&(e[t]=a);return}if(t==="parsed_positionals"){if(!Array.isArray(n))return;let a=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);a.length>0&&(e.parsed_positionals=a);return}let o=js(n);o&&(e[t]=o)}function qs(e,t){if(!$a(t))return;let{requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:a,minimum_status:i,basis:r,reason:s}=t;e.token_budget={requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:a,minimum_status:i,basis:r,reason:s}}var Ni=["retry_after_ms","waited_ms","owner_handoffs"];function Hs(e,t){for(let n of Ni)typeof t[n]=="number"&&e.push(` ${n}: ${t[n]}`)}function zs(e,t){for(let n of Ni){let o=t[n];typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&(e[n]=o)}}function Se(e){if(!e||typeof e!="object")return;let t={};qs(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Sn(t,"attempted_command",e.attempted_command),X(t,"normalized_args",e.normalized_args),X(t,"parsed_positionals",e.parsed_positionals),X(t,"provided_fields",e.provided_fields),X(t,"missing",e.missing),X(t,"missing_required_fields",e.missing_required_fields),X(t,"suggested_flags",e.suggested_flags),X(t,"allowed_values",e.allowed_values),X(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),Sn(t,"suggested_retry",e.suggested_retry),X(t,"suggested_retry_args",e.suggested_retry_args),zs(t,e);let n=Us(e.fallback_candidates);return n&&(t.fallback_candidates=n),Sn(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function An(e,t,n){n&&e.push(` ${t}: ${n}`)}function fe(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function Gs(e){let t=Se(e);if(!t)return[];let n=["Recovery bundle:"];if(t.token_budget){let o=t.token_budget;n.push(` requested_token_budget: ${o.requested_tokens}`,` feasible_token_budget: ${o.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${o.minimum_feasible_tokens??"not established"}`)}if(An(n,"suggested_retry",t.suggested_retry),An(n,"attempted_command",t.attempted_command),fe(n,"normalized_args",t.attempted_command?void 0:t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(fe(n,"provided_fields",t.provided_fields,", "),fe(n,"missing",t.missing,", "),fe(n,"missing_required_fields",t.missing_required_fields,", "),fe(n,"suggested_flags",t.suggested_flags,", "),fe(n,"allowed_values",t.allowed_values,", "),fe(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}`),Hs(n,t),An(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 Fi(e){let t=[`Error: ${e.title}`,"","What is required:",` ${e.required}`];e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...En("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(...En("Examples:",e.examples))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...En("Verification errors:",e.verificationErrors)));let n=Gs(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
6
+ `)}function Ws(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId)}function Li(e,t){return t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),Ws(e,t),Ns(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 Vs(e,t){if(e.flag)return e.flag;let n=o=>{let a=o.split("=",1)[0];return D([a]).length>0&&!["--help","--no-changed-fields","--version"].includes(a)&&t.some(i=>i===a||i.startsWith(`${a}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(o=>o[0]).find(o=>n(o))}function Bs(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(i=>i===n||i.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let a=t.indexOf(n);return t[a+1]}}function Ks(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=D(e.recovery?.normalized_args??[]),o=q(n),a=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,i=Vs(e,a),r=Bs(e,a,i);return{surface:i??e.recovery?.missing?.[0]??_n(a)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Js(e,t){return Li({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Ks(e,t),...e.changed===!1?{changed:!1}:{}},e)}function On(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 _a(Js(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function Rn(e){return Li({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function Rt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Ys(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 ge(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 $i(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Xs(e){return _n(e?.normalized_args)}function Zs(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 Qs(e,t){let n=e?.normalized_args,o=e?.provided_fields,a=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!a))for(let i of o){let r=n.findIndex(s=>s===i);if(r>=0&&r<n.length-1&&!n[r+1]?.startsWith("-")){let s=[...n];return s[r+1]=a,b(s)}}}function el(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Tt(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function tl(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function ae(e,t,n){if(!n)return e;let o=Rt(t),a=Tt(n.code,e.code),i=Tt(n.type,Di(a)),r=ge(n.examples)??e.examples,s=ge(n.nextSteps)??e.nextSteps,l=ge(n.verification_errors)??e.verificationErrors,c=e.code==="command_failed"&&n.code?el(o):void 0,d=Se(n.recovery),m=d&&e.recovery?Se({...e.recovery,...d}):d??e.recovery;return{...e,code:a,changed:n.changed,type:i,title:c??e.title,happened:o.length>0?o:e.happened,required:Tt(n.required,e.required),why:Tt(n.why,e.why),examples:r,nextSteps:s,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:tl(n,m)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,availableDependencies:n.available_dependencies,recovery:m}}function nl(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 a=o[1],i=ta(process.cwd(),a);return ae(k(i?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${a}, 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 ol(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let a=o[1],i=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(a),r=i?`The item ID "${a}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${a}" exists in the active tracker scope.`;return ae(k({code:"item_not_found",title:"Item ID not found",flag:"id",value:a,happened:r,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps: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 al(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ae(k({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 il(e,t,n){if(!t.includes("is locked"))return null;let o=Mi(n?.recovery?.normalized_args),a=o?b(o):void 0,i=ae(k({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:a?[a]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(i.recovery={...i.recovery,suggested_retry:a,suggested_retry_args:[...o]}),i}function rl(e,t,n){let o=t.match(/^Missing required option /),a=t.match(/^Missing required options /);if(!o&&!a)return null;let i=!!a,r=i?null:t.replace(/^Missing required option\s+/,"").trim(),s=r??"",l=r?`Pass ${r} with a valid value before running the command.`:"Provide the required option for this command invocation.";return ae(k({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 sl(e,t,n){return t.startsWith("No update flags provided")?ae(k({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 ll(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=Se(n?.recovery),a=Xs(o),i=a?`pm ${a} --help`:"pm <command> --help",r=Zs(t),s=Se({...o,allowed_values:o?.allowed_values??r}),l=Qs(o,r),c=l?[l,i]:[i,"pm contracts --command <command> --flags-only --json"],d=r.length>0?[`Allowed values: ${r.join("|")}`,`Run "${i}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return ae(k({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:c,nextSteps:d,recovery:s}),e,n)}function In(e,t){let n=Rt(e);return(nl(e,n,t)??ol(e,n,t)??al(e,n,t)??il(e,n,t)??rl(e,n,t)??sl(e,n,t)??ll(e,n,t))||ae(k({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 cl(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 dl(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function ml(e){if(!(!Array.isArray(e)||e.length===0))return b(e)}function $n(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 F(e,t={}){let n=$n(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,a=typeof e?.attemptedCommand=="string"?e.attemptedCommand:ml(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Se({attempted_command:a,normalized_args:o,provided_fields:n,suggested_retry:i,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Tn(e,t){return!t||e.includes(t)?e:[...e,t]}var pl=new Set(["--add","--add-json","--remove"]),ul=new Set(["command","cmd","path"]);function fl(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(pl.has(o))return o}}function gl(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 a=e[o];if(a!=="--add"&&a!=="--remove")continue;let i=e[o+1];if(typeof i!="string"||!ul.has(i))return;let r=[];for(let c=o+2;c<e.length;c+=1){let d=e[c];if(d.startsWith("--")&&d.length>2)break;r.push(d)}if(r.length<2)return;let s=`${i}=${r.join(" ")}`,l=[...e.slice(0,o+1),s,...e.slice(o+2+r.length)];return b(l)}}function hl(e,t,n,o){let a=e.match(/required option '([^']+)' not specified/);if(!a)return null;let i=dl(a[1]),r=i.startsWith("--type"),s=o?.suggestedRetryCommand,l=$n(o?.providedOptionFlags),c=[i],d=cl(t,i,n),m=s?Tn(d,s):d,p=r?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Tn(p,`Replay with preserved arguments: ${s}`):p,f=l&&l.length>0?Tn(u,`Already provided options: ${l.join(", ")}`):u;return k({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:r?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:F(o,{missing:c})})}function yl(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let a=o[1];return k({code:"missing_required_argument",title:`Missing required argument ${a}`,happened:`Command invocation omitted positional argument ${a}.`,required:`Provide ${a} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:F(n,{missing:[a]})})}function _l(e,t,n){return k({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:F(t,{suggested_flags:n})})}var wl={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 vl(e){let t=ge(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function bl(e,t,n,o,a){let i=o.otherCommands.slice(0,3),r=o.candidateTotal-i.length,s=r>0?` and ${String(r)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i.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,a?`Replay with suggested correction: ${a}`:void 0].filter(l=>typeof l=="string")}function Cl(e,t,n){let o=fi(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:b(o),suggestedRetryArgs:o}:["--full","--depth","--toon"].includes(t.split("=",1)[0])?{}:void 0}function kl(e,t,n){if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=Cl(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(gi(t))return{};let a=e.normalizedInvocationArgs;if(a===void 0)return{};if(a.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let i=a.findIndex(s=>s===t||s.startsWith(`${t}=`));if(i<0||a.includes("--")||!a[i]?.includes("=")&&i!==a.length-1&&a[i+1]?.startsWith("-")!==!0)return{};let r=D(a.filter((s,l)=>l!==i));return{retryCommand:b(r),suggestedRetryArgs:r}}function xl(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let a=n??{},i=o[1],r=$n(a.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=kl(a,i,t);if(t==="update"&&(i==="--file"||i==="--doc"))return _l(i,n,r);let c=vl(a),d=bl(i,t,r,c,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(i.split("=",1)[0])&&d.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${H(t)?.canonical??t} --help`:"pm --help --all"].filter(p=>typeof p=="string");return k({code:"unknown_option",title:`Unknown option ${i}`,happened:`Commander does not recognize option ${i} for this command path.`,required:wl[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:i,value:i,examples:m,nextSteps:d,recovery:F(n,{suggested_flags:r.length>0?r:void 0,suggested_retry:s,suggested_retry_args:l,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:a.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function El(e,t,n,o,a){let i=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,r=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return k({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:$i([t.installCommand,...n]),nextSteps:$i([i,...r]),recovery:F(a)})}function Sl(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],a=ge(t?.unknownCommandExamples),i=ge(t?.unknownCommandNextSteps),r=Ls(o),s=a??["pm --help"],l=i??["Verify spelling and active extensions, then rerun."],c=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=r?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return r&&(!d||!c.has(d))?El(o,r,s,l,t):k({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:F(t)})}function Al(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ge(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let a=e?.suggestedRetryCommand;return k({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...a?[a]:[],`pm ${H(t)?.canonical??t} --help`],nextSteps:a?[`Retry with the declared hyphenated action: ${a}`]:["Choose one value from recovery.allowed_values."],recovery:F(e,{allowed_values:o,suggested_retry:a})})}function Tl(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,a=fl(o);if(!a)return null;let i=gl(o);return k({code:"linked_test_value_not_quoted",title:`Linked-test ${a} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${a} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${a} 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:F(n,i?{suggested_retry:i}:{})})}var Ol=new Set(["comments","docs","files","learnings","notes","test"]);function Rl(e,t,n){if(!/too many arguments/i.test(e))return null;let o=Ga(t,n?.normalizedInvocationArgs??[]);if(!o)return null;let a=o.retryArgs?b(o.retryArgs):void 0,i=b(o.templateArgs??["test",o.itemId,"--add",`command=<actual command>,${o.value}`]);return k({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:a?`Retry the explicit collection mutation: ${a}`:`Supply the actual command and its metadata together, for example ${i}.`,examples:[a??i],recovery:F(n,{suggested_retry:a,suggested_retry_args:o.retryArgs})})}function Il(e,t,n){if(!/too many arguments/i.test(e)||!Ol.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],a=o.findIndex(c=>c===t),i=o[a+1],r=o[a+2],s=n?.verifiedCollectionItemId?.trim();if(i?.toLowerCase()!=="add"||!r||r.startsWith("-")||!s||s.toLowerCase()!==r.toLowerCase())return null;let l=`pm ${t} ${s} --add <value>`;return k({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:F(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:l})})}var $l=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"]),Pi=new Set(["context","ctx"]);function Pl(e,t,n){if(!/too many arguments/i.test(e)||!Pi.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],a=o.findIndex(c=>Pi.has(c)),i=a===-1?1:a+1,r=e.match(/got \d+:\s*(\S+)/i),s=r?r[1].replace(/\.$/,""):void 0;if(s===void 0){let c=!1;for(let d of o.slice(i)){if(c){c=!1;continue}let m=d.split("=")[0];if($l.has(m)){c=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let l=`pm get ${s}`;return k({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:F(n,{suggested_retry:l})})}function Pn(e,t,n,o){let a=Rt(e);return(hl(a,t,n,o)??yl(a,t,o)??xl(a,t,o)??Sl(a,o)??Al(o)??Il(a,t,o)??Tl(a,t,o)??Rl(a,t,o)??Pl(a,t,o))||k({code:"invalid_command_usage",title:"Invalid command usage",happened:a,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:F(o)})}function ji(e,t){let n=In(e,t);return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&n.title==="Tracker is not initialized"&&n.recovery?.suggested_retry_args?[`Error: ${n.title}`,`Run: ${b(n.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
7
+ `):an(Fi(n),n.required).output}function Ui(e,t){return Rn(In(e,t))}function Dn(e,t,n){return On(In(e,n),t)}function qi(e,t,n,o){let a=Pn(e,t,n,o);return an(Fi(a),a.required).output}function Mn(e,t,n,o){return Rn(Pn(e,t,n,o))}function It(e,t,n,o,a){return On(Pn(e,t,n,a),o)}function Hi(e,t){let n=zi(e);return On(n,t)}function zi(e){let t=Rt(e);return Ys(t)?k({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."]}):k({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 Gi(e){return Rn(zi(e))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4647d40c-70a2-5ffe-a91f-d43e9c522114")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3c73e79-571d-5a1b-94cd-db8c1b8ca7a4")}catch{}})();var Be=Qo.join("|"),Dl={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"},Ml={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"]}},Wi=["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 Nl(e,t){let n=Ml[e];if(!n)return[];let o=U(t);for(let[a,i]of Object.entries(n))if(U(a)===o)return i;return[]}function Nn(e,t,n){if(n.length===0)return e;if(t){let r=n.find(d=>d.declared_command_match===!0),{token_accounting:s,...l}=JSON.parse(e),c={...l,...r?{extension_command_failure:{code:"extension_command_activation_failed",extension:r.name,layer:r.layer,error:r.error,recovery_commands:r.recovery_commands??[]}}:{},failed_extensions:n};return JSON.stringify(s===void 0?c:ce(c,d=>`${JSON.stringify(d,null,2)}
8
8
  `),null,2)}let o=n.map(r=>`- ${r.layer}:${r.name}: ${r.error}`).join(`
9
9
  `),a=n.find(r=>r.declared_command_match===!0);if(!a)return`${e}
10
10
  Extension activation failures:
@@ -16,23 +16,23 @@ ${i}`:""}
16
16
 
17
17
  ${e}
18
18
  Extension activation failures:
19
- ${o}`}function Fn(e){return A(e).commandPathTokens[0]??x(e)??"<command>"}function Ki(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let a=o.shift();if(!a)continue;let i=M(E(a)),r=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!r&&n.add(i),o.push(...a.commands)}for(let a of t.keys()){let i=M(a),r=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!r&&n.add(i)}return[...n].sort((a,i)=>a.localeCompare(i))}function Wi(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let a=n.split(" ");if(n===o)return 0;if(a.includes(o))return 1;if(a.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let i=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let s of a){let l=en(s,o,i);l!==null&&(r=Math.min(r,l))}return Number.isFinite(r)?4+r:Number.POSITIVE_INFINITY}function Vi(e){return j(e).slice(2).replace(/-/g,"")}function Ln(e){return C(e)}function Ml(e){let t=H(e)?.canonical??Yt[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=$l[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function Bi(e){let t=ci(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function Nl(e,t){let n=Bi(e);if(n.length===0)return[];let o=[];for(let a of t.values()){let i=new Set,r=a.source;if(r)for(let s of[r.name,r.package]){let l=Bi(s??"");l.length>0&&i.add(l)}i.size!==0&&[...i].some(s=>s===n||s.includes(n)||n.includes(s))&&o.push(a.command)}return[...new Set(o)].sort((a,i)=>a.localeCompare(i))}function Ke(e,t){let n=new Set,o=t??ne(e);for(let a of o){a.flag.startsWith("--")&&n.add(j(a.flag));for(let i of a.aliases??[])i.startsWith("--")&&n.add(j(i))}return[...n].sort((a,i)=>a.localeCompare(i))}function Fl(e,t){if(!e.startsWith("--"))return[];let n=Vi(e);if(n.length===0)return[];let o=n.length>=8?2:1,a=[];for(let i of t){let r=Vi(i);if(r===n)continue;if(n.length>=3&&r.startsWith(n)){a.push({flag:i,rank:0,distance:r.length-n.length});continue}let s=en(n,r,o);s===null||s<=0||a.push({flag:i,rank:1,distance:s})}return a.sort((i,r)=>i.rank!==r.rank?i.rank-r.rank:i.distance!==r.distance?i.distance-r.distance:i.flag.localeCompare(r.flag)).map(i=>i.flag).slice(0,3)}var $t,Ll=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 jl(){if($t)return $t;let e=new Map;for(let t of Le)if(!Ll.has(t))for(let n of Ke(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return $t=e,$t}function Ul(e,t){if(!e.startsWith("--"))return[];let n=jl().get(j(e));if(!n)return[];let o=t?.trim().toLowerCase(),a=new Set(Ke(o));return[...new Set(n.filter(i=>i!==o).map(i=>({command:i,sharedFlagCount:Ke(i).filter(r=>a.has(r)).length})).sort((i,r)=>i.sharedFlagCount!==r.sharedFlagCount?r.sharedFlagCount-i.sharedFlagCount:i.command.localeCompare(r.command)).map(({command:i})=>H(i)?.canonical??i))]}function ql(e,t,n){for(let o=0;o<e.length;o+=1){let a=e[o];if(!a.startsWith("--"))continue;let i=a.indexOf("="),r=i>=0?a.slice(0,i):a;if(j(r)!==j(t))continue;let s=[...e];return s[o]=i>=0?`${n}${a.slice(i)}`:n,s}}function Hl(e){let t=new Set(e.commandPaths),n=i=>Math.min(Wi(i,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Wi(i,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,a=(i,r)=>{if(!Number.isFinite(r)||!t.has(i))return;let s=o.get(i);(s===void 0||r<s)&&o.set(i,r)};for(let i of e.commandPaths)a(i,n(i));for(let[i,r]of Object.entries(Yt))i!=="read"&&a(r,n(i));return[...o.entries()].sort(([i,r],[s,l])=>r!==l?r-l:i.localeCompare(s)).map(([i])=>i)}function zl(e){let t=H(e.normalizedUnknown),n=_i(e.commandPaths,e.primaryToken),o=Hl(e),a=Nl(e.primaryToken,e.extensionDescriptors).filter(i=>e.commandPaths.includes(i));return wn([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...a],e.commandPaths,e.primaryToken).filter(i=>!e.normalizedUnknown.includes(" ")||i!==e.normalizedUnknown)}function Gl(e){return[...new Set(e.map(t=>t.split(" ")[0]).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Wl(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help --all"])]:[...new Set(["pm --help --all",...n])]}function Vl(e,t,n){let o=K([...t]),a=[];for(;o!==void 0;){if(a.push(t[o]),t[o]===e)return a.join(" ");if(!n.includes(a.join(" ")))return e;let i=K(t.slice(o+1));o=i===void 0?void 0:o+1+i}return e}function Bl(e,t){if(!e)return;let n=N([...t]);return[...n.path?["--pm-path",S(process.cwd(),n.path)]:[],...n.noExtensions?["--no-extensions"]:[],...e.split(" "),"--help"]}function jn(e,t,n,o=[]){let a=e.match(/unknown command '([^']+)'/i);if(!a||typeof a[1]!="string")return;let i=Ki(t,n),r=Vl(a[1],o,i),s=M(r);if(s.length===0||i.length===0)return;let l=Ml(s);if(l&&!i.includes(l.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[l.installCommand,`pm ${l.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${l.packageAlias}" package. Install it with: ${l.installCommand}. Command after installation: pm ${l.canonicalPath}.`],suggestedRetryCommand:l.installCommand};let c=s.split(" ")[0],d=zl({commandPaths:i,normalizedUnknown:s,primaryToken:c,extensionDescriptors:n}),m=Gl(i),p=yi(s,i),u=Bl(p,o),f=[...new Set([...p?[p]:[],...d.length>0?d:wn(m,i)])].slice(0,3),h=Wl(f,d.length>0),v=d.length>0?`Did you mean: ${f.join(", ")}?`:null;return{...u?{suggestedRetryCommand:C(u),suggestedRetryArgs:u}:{},unknownCommandExamples:u?[C(u),...h.slice(1)]:h,unknownCommandNextSteps:[...v?[v]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...v?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function Kl(e){return Array.from(new Set(e))}function Jl(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
20
- `||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Yl(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 Xl(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(a=>a.trim().toLowerCase()===n))}function Ae(e,t){if(t.length===0)return!0;let n=e;for(let[o,a]of t.entries()){let i=Xl(n,a);if(!i){let r=n.registeredArguments;return r.length>0&&(n.commands.length===0||r[0]?.required===!0)&&(r.at(-1)?.variadic===!0||t.length-o<=r.length)}n=i}return!0}async function Zl(e,t,n,o){try{let a=S(process.cwd(),e.path);if(!await V(B(a)))return{allowedTypes:Be};let i=await $(a),r=e.noExtensions?void 0:se(),s=re(i,r),l;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let c=n.findIndex(m=>m===o),d=n[c+2];if(n[c+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{l=(await _t(a,d,i.id_prefix,i.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Be,pmRoot:a,settings:i,typeToFolder:s.type_to_folder,verifiedCollectionItemId:l}}catch{return{allowedTypes:Be}}}function Ql(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?Kl([...Dl(t,n[1]),...Fl(n[1],Ke(t))]).filter(r=>gi(n[1],r)):void 0,a=n?Ul(n[1],t):[],i=n!==null&&Ke(t).includes(j(n[1]));return{match:n,suggestions:o,otherCommands:a,scope:i?"declared_on_path":a.length>0?"declared_elsewhere":"declared_nowhere"}}function ec(e,t,n){if(!t||!n||n.length===0)return;let o=ql(e,t[1],n[0]);return o?Ln(o):void 0}function tc(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Yl(Jl(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let a=x(t);if(a)return hi(t,a,[o])}function nc(e,t){if(!/too many arguments/i.test(e))return;let n=K(t),o=q(t.slice(n));if(o?.alias!=="schema")return;let a=n+o.canonical_argv.length-1,i=t[a+1]?.trim().toLowerCase(),r=t[a+2]?.trim().toLowerCase();if(!i||!r)return;let s=`${i}-${r}`;if(!Gi.includes(s))return;let l=[...t.slice(0,a+1),s,...t.slice(a+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${i} ${r}`,unknownSubcommandAllowedValues:[...Gi],suggestedRetryCommand:Ln(l)}}function oc(e,t,n,o){let a=K(t),i=q(t.slice(a))?.alias??x(t);if(!/unknown option /i.test(e)||i===void 0)return i;let r=H(i)?.canonical??i;return Le.some(s=>s===i)||Ki(n,o).includes(r)?i:void 0}async function Je(e,t,n,o={},a=process.argv.slice(2)){let i=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",r=Ge([...a]).argv,s=N(r),l=oc(i,r,t,n),c=Ln(r),d=Y(r),m=await Zl(s,i,r,l),p=m.allowedTypes,u=jn(i,t,n,r),f=Ql(i,l),h=nc(i,r),v=h?.suggestedRetryCommand??ec(r,f.match,f.suggestions)??tc(i,r);return{message:i,commandName:l,allowedTypes:p,attemptedCommand:c,normalizedInvocationArgs:[...r],providedOptionFlags:d,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,unknownOptionScope:f.scope,suggestedRetryCommand:v,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function Un(e,t,n,o={},a=process.argv.slice(2)){let i=await Je(e,t,n,o,a),{message:r,commandName:s,allowedTypes:l,...c}=i,d=Ui(r,s,l,c),m=await ya("help_format",{message:d,command:s,allowed_types:l});return m.handled&&typeof m.result=="string"?m.result:d}async function qn(e,t,n,o=!1,a={},i=process.argv.slice(2)){let r=await Je(e,t,n,a,i),s=It(r.message,r.commandName,r.allowedTypes,g.USAGE,r),l=o?Ot(s):s,c=N(r.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(c?ce(l,d=>`${JSON.stringify(d,null,2)}
21
- `):l,null,2)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e57ce782-5c73-5c74-a929-0971a990a355")}catch{}})();async function Ji(e,t,n,o){if(n)return null;let a=e.some(r=>r==="--for"||r.startsWith("--for=")),i=x(e)==="contracts"&&e.includes("--full");return a||i?await o(t):null}import{Option as ac}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]="c077f66e-bac4-58af-92cd-a19c30ada04d")}catch{}})();function w(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Xi(e,t){let n=new Map;for(let o of e){let a=w(o.command);for(let i of t){if(i.layer!==o.layer||i.name!==o.name)continue;let r=w(i.command),s=r.split(" "),l=s.at(-1),c=s.slice(1).join(" "),d=c?`${s[0]}-${l} ${c}`:`${s[0]}-${l}`;if(l&&a===d){n.set(a,r);break}}}return n}function Hn(e,t,n,o){if(!t||!n)return;let a,i=0;for(let[s,l]of e.entries()){if(l!==t)continue;let c=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>i&&p.every((u,f)=>c[f]===u)&&(a=m,i=p.length)}}let r=a?.flags.find(s=>s.long===n||s.short===n);if(r)return ic(r).takesValue}function Ye(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Te(e){return typeof e=="boolean"?e:void 0}function ic(e){let t=we(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function rc(e){let t=ee(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=zn(e);if(!n)return null;let o=Ye(e.description)??"Extension-provided option.",a=[];Te(e.required)===!0&&a.push("required"),Te(e.enabled)===!1&&a.push("disabled");let i=a.length>0?` [${a.join(", ")}]`:"";return`${n} ${o}${i}`}function Zi(e){let t=[...new Set(e.map(rc).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
19
+ ${o}`}function Fn(e){return A(e).commandPathTokens[0]??x(e)??"<command>"}function Ji(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let a=o.shift();if(!a)continue;let i=M(E(a)),r=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!r&&n.add(i),o.push(...a.commands)}for(let a of t.keys()){let i=M(a),r=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!r&&n.add(i)}return[...n].sort((a,i)=>a.localeCompare(i))}function Vi(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let a=n.split(" ");if(n===o)return 0;if(a.includes(o))return 1;if(a.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let i=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let s of a){let l=en(s,o,i);l!==null&&(r=Math.min(r,l))}return Number.isFinite(r)?4+r:Number.POSITIVE_INFINITY}function Bi(e){return U(e).slice(2).replace(/-/g,"")}function Ln(e){return b(e)}function Fl(e){let t=H(e)?.canonical??Yt[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=Dl[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function Ki(e){let t=di(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function Ll(e,t){let n=Ki(e);if(n.length===0)return[];let o=[];for(let a of t.values()){let i=new Set,r=a.source;if(r)for(let s of[r.name,r.package]){let l=Ki(s??"");l.length>0&&i.add(l)}i.size!==0&&[...i].some(s=>s===n||s.includes(n)||n.includes(s))&&o.push(a.command)}return[...new Set(o)].sort((a,i)=>a.localeCompare(i))}function Ke(e,t){let n=new Set,o=t??ne(e);for(let a of o){a.flag.startsWith("--")&&n.add(U(a.flag));for(let i of a.aliases??[])i.startsWith("--")&&n.add(U(i))}return[...n].sort((a,i)=>a.localeCompare(i))}function jl(e,t){if(!e.startsWith("--"))return[];let n=Bi(e);if(n.length===0)return[];let o=n.length>=8?2:1,a=[];for(let i of t){let r=Bi(i);if(r===n)continue;if(n.length>=3&&r.startsWith(n)){a.push({flag:i,rank:0,distance:r.length-n.length});continue}let s=en(n,r,o);s===null||s<=0||a.push({flag:i,rank:1,distance:s})}return a.sort((i,r)=>i.rank!==r.rank?i.rank-r.rank:i.distance!==r.distance?i.distance-r.distance:i.flag.localeCompare(r.flag)).map(i=>i.flag).slice(0,3)}var $t,Ul=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 ql(){if($t)return $t;let e=new Map;for(let t of Le)if(!Ul.has(t))for(let n of Ke(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return $t=e,$t}function Hl(e,t){if(!e.startsWith("--"))return[];let n=ql().get(U(e));if(!n)return[];let o=t?.trim().toLowerCase(),a=new Set(Ke(o));return[...new Set(n.filter(i=>i!==o).map(i=>({command:i,sharedFlagCount:Ke(i).filter(r=>a.has(r)).length})).sort((i,r)=>i.sharedFlagCount!==r.sharedFlagCount?r.sharedFlagCount-i.sharedFlagCount:i.command.localeCompare(r.command)).map(({command:i})=>H(i)?.canonical??i))]}function zl(e,t,n){for(let o=0;o<e.length;o+=1){let a=e[o];if(!a.startsWith("--"))continue;let i=a.indexOf("="),r=i>=0?a.slice(0,i):a;if(U(r)!==U(t))continue;let s=[...e];return s[o]=i>=0?`${n}${a.slice(i)}`:n,s}}function Gl(e){let t=new Set(e.commandPaths),n=i=>Math.min(Vi(i,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Vi(i,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,a=(i,r)=>{if(!Number.isFinite(r)||!t.has(i))return;let s=o.get(i);(s===void 0||r<s)&&o.set(i,r)};for(let i of e.commandPaths)a(i,n(i));for(let[i,r]of Object.entries(Yt))i!=="read"&&a(r,n(i));return[...o.entries()].sort(([i,r],[s,l])=>r!==l?r-l:i.localeCompare(s)).map(([i])=>i)}function Wl(e){let t=H(e.normalizedUnknown),n=wi(e.commandPaths,e.primaryToken),o=Gl(e),a=Ll(e.primaryToken,e.extensionDescriptors).filter(i=>e.commandPaths.includes(i));return wn([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...a],e.commandPaths,e.primaryToken).filter(i=>!e.normalizedUnknown.includes(" ")||i!==e.normalizedUnknown)}function Vl(e){return[...new Set(e.map(t=>t.split(" ")[0]).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Bl(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help --all"])]:[...new Set(["pm --help --all",...n])]}function Kl(e,t,n){let o=K([...t]),a=[];for(;o!==void 0;){if(a.push(t[o]),t[o]===e)return a.join(" ");if(!n.includes(a.join(" ")))return e;let i=K(t.slice(o+1));o=i===void 0?void 0:o+1+i}return e}function Jl(e,t){if(!e)return;let n=N([...t]);return[...n.path?["--pm-path",S(process.cwd(),n.path)]:[],...n.noExtensions?["--no-extensions"]:[],...e.split(" "),"--help"]}function jn(e,t,n,o=[]){let a=e.match(/unknown command '([^']+)'/i);if(!a||typeof a[1]!="string")return;let i=Ji(t,n),r=Kl(a[1],o,i),s=M(r);if(s.length===0||i.length===0)return;let l=Fl(s);if(l&&!i.includes(l.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[l.installCommand,`pm ${l.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${l.packageAlias}" package. Install it with: ${l.installCommand}. Command after installation: pm ${l.canonicalPath}.`],suggestedRetryCommand:l.installCommand};let c=s.split(" ")[0],d=Wl({commandPaths:i,normalizedUnknown:s,primaryToken:c,extensionDescriptors:n}),m=Vl(i),p=_i(s,i),u=Jl(p,o),f=[...new Set([...p?[p]:[],...d.length>0?d:wn(m,i)])].slice(0,3),h=Bl(f,d.length>0),v=d.length>0?`Did you mean: ${f.join(", ")}?`:null;return{...u?{suggestedRetryCommand:b(u),suggestedRetryArgs:u}:{},unknownCommandExamples:u?[b(u),...h.slice(1)]:h,unknownCommandNextSteps:[...v?[v]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...v?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function Yl(e){return Array.from(new Set(e))}function Xl(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
20
+ `||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Zl(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 Ql(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(a=>a.trim().toLowerCase()===n))}function Ae(e,t){if(t.length===0)return!0;let n=e;for(let[o,a]of t.entries()){let i=Ql(n,a);if(!i){let r=n.registeredArguments;return r.length>0&&(n.commands.length===0||r[0]?.required===!0)&&(r.at(-1)?.variadic===!0||t.length-o<=r.length)}n=i}return!0}async function ec(e,t,n,o){try{let a=S(process.cwd(),e.path);if(!await V(B(a)))return{allowedTypes:Be};let i=await $(a),r=e.noExtensions?void 0:se(),s=re(i,r),l;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let c=n.findIndex(m=>m===o),d=n[c+2];if(n[c+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{l=(await _t(a,d,i.id_prefix,i.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Be,pmRoot:a,settings:i,typeToFolder:s.type_to_folder,verifiedCollectionItemId:l}}catch{return{allowedTypes:Be}}}function tc(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?Yl([...Nl(t,n[1]),...jl(n[1],Ke(t))]).filter(r=>hi(n[1],r)):void 0,a=n?Hl(n[1],t):[],i=n!==null&&Ke(t).includes(U(n[1]));return{match:n,suggestions:o,otherCommands:a,scope:i?"declared_on_path":a.length>0?"declared_elsewhere":"declared_nowhere"}}function nc(e,t,n){if(!t||!n||n.length===0)return;let o=zl(e,t[1],n[0]);return o?Ln(o):void 0}function oc(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Zl(Xl(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let a=x(t);if(a)return yi(t,a,[o])}function ac(e,t){if(!/too many arguments/i.test(e))return;let n=K(t),o=q(t.slice(n));if(o?.alias!=="schema")return;let a=n+o.canonical_argv.length-1,i=t[a+1]?.trim().toLowerCase(),r=t[a+2]?.trim().toLowerCase();if(!i||!r)return;let s=`${i}-${r}`;if(!Wi.includes(s))return;let l=[...t.slice(0,a+1),s,...t.slice(a+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${i} ${r}`,unknownSubcommandAllowedValues:[...Wi],suggestedRetryCommand:Ln(l)}}function ic(e,t,n,o){let a=K(t),i=q(t.slice(a))?.alias??x(t);if(!/unknown option /i.test(e)||i===void 0)return i;let r=H(i)?.canonical??i;return Le.some(s=>s===i)||Ji(n,o).includes(r)?i:void 0}async function Je(e,t,n,o={},a=process.argv.slice(2)){let i=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",r=Ge([...a]).argv,s=N(r),l=ic(i,r,t,n),c=Ln(r),d=Y(r),m=await ec(s,i,r,l),p=m.allowedTypes,u=jn(i,t,n,r),f=tc(i,l),h=ac(i,r),v=h?.suggestedRetryCommand??nc(r,f.match,f.suggestions)??oc(i,r);return{message:i,commandName:l,allowedTypes:p,attemptedCommand:c,normalizedInvocationArgs:[...r],providedOptionFlags:d,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,unknownOptionScope:f.scope,suggestedRetryCommand:v,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function Un(e,t,n,o={},a=process.argv.slice(2)){let i=await Je(e,t,n,o,a),{message:r,commandName:s,allowedTypes:l,...c}=i,d=qi(r,s,l,c),m=await ya("help_format",{message:d,command:s,allowed_types:l});return m.handled&&typeof m.result=="string"?m.result:d}async function qn(e,t,n,o=!1,a={},i=process.argv.slice(2)){let r=await Je(e,t,n,a,i),s=It(r.message,r.commandName,r.allowedTypes,g.USAGE,r),l=o?Ot(s):s,c=N(r.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(c?ce(l,d=>`${JSON.stringify(d,null,2)}
21
+ `):l,null,2)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e57ce782-5c73-5c74-a929-0971a990a355")}catch{}})();async function Yi(e,t,n,o){if(n)return null;let a=e.some(r=>r==="--for"||r.startsWith("--for=")),i=x(e)==="contracts"&&e.includes("--full");return a||i?await o(t):null}import{Option as rc}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]="c077f66e-bac4-58af-92cd-a19c30ada04d")}catch{}})();function w(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Zi(e,t){let n=new Map;for(let o of e){let a=w(o.command);for(let i of t){if(i.layer!==o.layer||i.name!==o.name)continue;let r=w(i.command),s=r.split(" "),l=s.at(-1),c=s.slice(1).join(" "),d=c?`${s[0]}-${l} ${c}`:`${s[0]}-${l}`;if(l&&a===d){n.set(a,r);break}}}return n}function Hn(e,t,n,o){if(!t||!n)return;let a,i=0;for(let[s,l]of e.entries()){if(l!==t)continue;let c=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>i&&p.every((u,f)=>c[f]===u)&&(a=m,i=p.length)}}let r=a?.flags.find(s=>s.long===n||s.short===n);if(r)return sc(r).takesValue}function Ye(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Te(e){return typeof e=="boolean"?e:void 0}function sc(e){let t=we(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function lc(e){let t=ee(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=zn(e);if(!n)return null;let o=Ye(e.description)??"Extension-provided option.",a=[];Te(e.required)===!0&&a.push("required"),Te(e.enabled)===!1&&a.push("disabled");let i=a.length>0?` [${a.join(", ")}]`:"";return`${n} ${o}${i}`}function Qi(e){let t=[...new Set(e.map(lc).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
22
22
  Extension-provided flags:
23
23
  ${t.join(`
24
- `)}`}function Qi(e){let t=new Map;for(let a of e){let i=w(a.target_command);if(i.length===0)continue;let r=t.get(i)??[];r.push(...a.flags),t.set(i,r)}let n=[...t.entries()].sort(([a],[i])=>a.localeCompare(i)),o=new Map;for(let[a,i]of n){let r=Zi(i);r&&o.set(a,r)}return o}function er(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Yi(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let a=o.trim();a.length===0||n.has(a)||(n.add(a),t.push(a))}return t}function sc(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 lc(e){let t=new Map;for(let n of e){let o=w(n.command);if(o.length===0)continue;let a=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:er(o,n.action),description:a,intent:i,examples:Yi(n.examples),failure_hints:Yi(n.failure_hints),arguments:sc(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 cc(e){let t=new Map;for(let n of e){let o=w(n.target_command);if(o.length===0)continue;let a=t.get(o)??[];a.push(...n.flags),t.set(o,a)}return t}function dc(e,t,n){let o=new Set;for(let a of e){let i=w(a);i.length>0&&o.add(i)}for(let a of t.keys())o.add(a);for(let a of n.keys())o.add(a);return o}function mc(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function tr(e,t,n,o=new Map){let a=lc(t),i=cc(n),r=dc(e,a,i),s=new Map,l=[...r].sort((c,d)=>c.localeCompare(d));for(let c of l){let d=mc(c,a,o)??a.get(c),m=i.get(c)??(d?i.get(d.command):void 0)??[];if(d){s.set(c,{...d,command:c,flags:m});continue}s.set(c,{command:c,action:er(c,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function pc(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function nr(e,t){for(let n of t.arguments)e.argument(pc(n),n.description??"Extension argument.")}function uc(e){if(Te(e.visible)===!1)return null;let t=ee(e.long),n=Ye(e.short),o=n&&n.startsWith("-")&&!n.startsWith("--")?n:null,a=t&&t.startsWith("--")&&t.length>2?t:null,i=[o,a].filter(r=>r!==null);return i.length>0?i:null}function zn(e){let t=uc(e);if(!t)return null;let{value_name:n,value_arity:o}=we(e),a=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${a}`}function fc(e){return zn(e)}function or(e){let t=Ye(e.description)??"Extension-provided option.",n=[];Te(e.required)===!0&&n.push("required"),Te(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function ar(e,t){let n=ee(t.long),o=Ye(t.short);return e.options.some(a=>{let i=a;return n!==null&&i.long===n||o!==null&&i.short===o})}function Gn(e,t){for(let n of t){if(ar(e,n))continue;let o=fc(n);if(!o)continue;let a=or(n),i=new ac(o,a);if(i.negate=!1,n.list!==!0){e.addOption(i);continue}e.addOption(i.argParser((r,s=[])=>[...Array.isArray(s)?s:[s],r]))}}function Wn(e,t){return Zi(t.filter(n=>!ar(e,n)))}function gc(e){let t=zn(e);if(!t)return null;let n=ee(e.long),o=Ye(e.short),a=n&&n.startsWith("--")&&n.length>2?n:null,i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=we(e),s=Te(e.required)===!0;return{flags:t,long:a,short:i,description:or(e),takes_value:r.value_arity!=="none",value_required:r.value_arity==="required",value_name:r.value_name,variadic:!1,required:s,aliases:[],alias_for:null}}function ir(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let a=gc(o);!a||n.has(a.flags)||(n.add(a.flags),t.push(a))}return t}function rr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(a=>a.flags));for(let a of t)o.has(a.flags)||(o.add(a.flags),n.push(a));return n}function sr(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:`
24
+ `)}`}function er(e){let t=new Map;for(let a of e){let i=w(a.target_command);if(i.length===0)continue;let r=t.get(i)??[];r.push(...a.flags),t.set(i,r)}let n=[...t.entries()].sort(([a],[i])=>a.localeCompare(i)),o=new Map;for(let[a,i]of n){let r=Qi(i);r&&o.set(a,r)}return o}function tr(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Xi(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let a=o.trim();a.length===0||n.has(a)||(n.add(a),t.push(a))}return t}function cc(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 dc(e){let t=new Map;for(let n of e){let o=w(n.command);if(o.length===0)continue;let a=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:tr(o,n.action),description:a,intent:i,examples:Xi(n.examples),failure_hints:Xi(n.failure_hints),arguments:cc(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 mc(e){let t=new Map;for(let n of e){let o=w(n.target_command);if(o.length===0)continue;let a=t.get(o)??[];a.push(...n.flags),t.set(o,a)}return t}function pc(e,t,n){let o=new Set;for(let a of e){let i=w(a);i.length>0&&o.add(i)}for(let a of t.keys())o.add(a);for(let a of n.keys())o.add(a);return o}function uc(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function nr(e,t,n,o=new Map){let a=dc(t),i=mc(n),r=pc(e,a,i),s=new Map,l=[...r].sort((c,d)=>c.localeCompare(d));for(let c of l){let d=uc(c,a,o)??a.get(c),m=i.get(c)??(d?i.get(d.command):void 0)??[];if(d){s.set(c,{...d,command:c,flags:m});continue}s.set(c,{command:c,action:tr(c,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function fc(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function or(e,t){for(let n of t.arguments)e.argument(fc(n),n.description??"Extension argument.")}function gc(e){if(Te(e.visible)===!1)return null;let t=ee(e.long),n=Ye(e.short),o=n&&n.startsWith("-")&&!n.startsWith("--")?n:null,a=t&&t.startsWith("--")&&t.length>2?t:null,i=[o,a].filter(r=>r!==null);return i.length>0?i:null}function zn(e){let t=gc(e);if(!t)return null;let{value_name:n,value_arity:o}=we(e),a=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${a}`}function hc(e){return zn(e)}function ar(e){let t=Ye(e.description)??"Extension-provided option.",n=[];Te(e.required)===!0&&n.push("required"),Te(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function ir(e,t){let n=ee(t.long),o=Ye(t.short);return e.options.some(a=>{let i=a;return n!==null&&i.long===n||o!==null&&i.short===o})}function Gn(e,t){for(let n of t){if(ir(e,n))continue;let o=hc(n);if(!o)continue;let a=ar(n),i=new rc(o,a);if(i.negate=!1,n.list!==!0){e.addOption(i);continue}e.addOption(i.argParser((r,s=[])=>[...Array.isArray(s)?s:[s],r]))}}function Wn(e,t){return Qi(t.filter(n=>!ir(e,n)))}function yc(e){let t=zn(e);if(!t)return null;let n=ee(e.long),o=Ye(e.short),a=n&&n.startsWith("--")&&n.length>2?n:null,i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=we(e),s=Te(e.required)===!0;return{flags:t,long:a,short:i,description:ar(e),takes_value:r.value_arity!=="none",value_required:r.value_arity==="required",value_name:r.value_name,variadic:!1,required:s,aliases:[],alias_for:null}}function rr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let a=yc(o);!a||n.has(a.flags)||(n.add(a.flags),t.push(a))}return t}function sr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(a=>a.flags));for(let a of t)o.has(a.flags)||(o.add(a.flags),n.push(a));return n}function lr(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:`
25
25
  Extension command metadata:
26
26
  ${t.join(`
27
- `)}`}function Vn(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 Xe(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Vn(o).includes(n))??null}function Z(e,t){let n=e;for(let o of t){let a=Xe(n,o);if(!a)return null;n=a}return n}var Bn=new WeakSet;function lr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let a=t[o];o>0&&R.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let i=Xe(n,a);if(i){n=i;continue}let r=n.command(a);Bn.add(r),o<t.length-1?(r.description("Extension-provided command group."),r.action(()=>{r.help()})):r.description("Extension-provided command path."),n=r}return n}function hc(e,t){let n=t.join(" "),o=R.find(r=>n===r.canonical||n.startsWith(`${r.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let a=e,i=[];for(let r of t){let s=Xe(a,r);if(!s)return null;i.push(r);let l=s.commands.length>0||R.some(c=>c.canonical.startsWith(`${i.join(" ")} `));if(!Bn.has(s)&&(i.length===t.length||!l))return{core_path:i.join(" "),extension_path:t.join(" ")};a=s}return null}function yc(e,t,n,o,a=!1){let i=t.split(" ").filter(d=>d.length>0),r=hc(e,i),s=Z(e,i),l=R.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Bn.has(s)));if(!r||r.core_path===t&&s!==null&&!n.has(t)&&!a||l&&!n.has(t))return null;let c=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${r.extension_path}:core_owner=pm-cli:${r.core_path}:extension_owner=${c}`}function cr(e,t,n,o,a){return[...new Set([...t,...n.keys()])].filter(i=>i.trim().length>0).sort((i,r)=>i.localeCompare(r)).filter(i=>{let r=yc(e,i,o,n.get(i),t.includes(i));return r?(a(r),!o.has(i)&&Z(e,i.split(" "))!==null):!0})}function dr(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]="c6ed71d0-b878-575e-b990-356afdc45688")}catch{}})();var _c=new Set(["__proto__","prototype","constructor"]),Kn=Symbol("looseOptionOccurrences");function Ze(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,n)=>n.toUpperCase())}function wc(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 Jn(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let r=n.indexOf("=");if(r>=0)return{consumed:1,key:n.slice(1,r).trim(),value:n.slice(r+1),attached:!0};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),attached:!0};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let a=n.slice(2).trim(),i=e[t+1];return typeof i=="string"&&!i.startsWith("-")?{consumed:2,key:a,value:i}:{consumed:1,key:a,value:!0}}function Pt(e){return _c.has(e)}function mr(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return aa(t)}function Qe(e){let t=[],n=ee(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let a=Ze(n.slice(2));a.length>0&&!Pt(a)&&t.push(a)}if(o.startsWith("-")&&!o.startsWith("--")){let a=Ze(o.slice(1));a.length>0&&!Pt(a)&&t.push(a)}return[...new Set(t)]}function pr(e){let t=new Set;for(let n of e)for(let o of Qe(n))t.add(o);return t}function vc(e){let t=ee(e.long)??"";if(t.startsWith("--")){let n=Ze(t.slice(2));if(n.length>0&&!Pt(n))return n}return Qe(e)[0]??null}function ur(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 Yn(e,t,n){if(t.length===0)return;let o=new Set,a=new Map,i=[],r=[];for(let s of t){let l=Qe(s),c=ur(s);c!==null&&r.push(c);for(let d of l)o.add(d),s.enabled===!1&&a.set(d,c);s.required===!0&&s.enabled!==!1&&l.length>0&&i.push({keys:l,label:c})}for(let s of Object.keys(e)){if(!o.has(s)){let c=r.length>0?` Expected one of: ${[...new Set(r)].join(", ")}.`:"";throw new b(`Unknown option '--${s}' for extension command '${n}'.${c}`,g.USAGE)}let l=a.get(s);if(l)throw new b(`Option '${l}' is disabled for extension command '${n}'.`,g.USAGE)}for(let s of i)if(!s.keys.some(l=>Object.hasOwn(e,l)))throw new b(`Missing required option '${s.label}' for extension command '${n}'.`,g.USAGE)}function bc(e){return typeof e=="string"||e==null?e:String(e)}function Cc(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 kc(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 xc={string:bc,number:Cc,boolean:kc};function Oe(e,t){return Array.isArray(e)?e.map(n=>Oe(n,t)):xc[t](e)}function fr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(a=>a!=null&&a!==""):tn(e);return t?o.map(a=>Oe(a,t)):o}function Ec(e,t,n,o){return n?fr(e,t,o):t?Oe(e,t):e}function Sc(e,t,n){let o=e[Kn];if(!o||o.length===0)return n;let a=new Set(t);return o.filter(i=>a.has(i.key)).map(i=>i.value)}function gr(e){return we(e).value_arity==="none"}function Xn(e,t,n,o,a){let i=ur(e),r=a?` for extension command '${a}'`:"",s=n===!0?"no value":JSON.stringify(n);throw new b(`Option '${i}'${r} expects ${o}; received ${s}.`,g.USAGE,{code:"extension_flag_value_invalid",required:`Pass ${i} ${t==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${t} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${t} value for ${i}.`,`Run pm ${a??"<command>"} --help to review the declared flag contract.`]})}function Zn(e,t){return e.value_validation==="strict"&&t!=="string"}function Ac(e,t){let n=e[Kn];if(!n)return[];let o=new Set(t);return n.filter(a=>o.has(a.key))}function Tc(e,t,n,o){if(gr(e))for(let a of Ac(n,t)){if(a.attached!==!0)continue;let i=e.list===!0&&e.repeatable!==!0?tn(a.value):[a.value];for(let r of i){let s=pt(Oe(r,"boolean"),"boolean");s!==null&&Xn(e,"boolean",r,s.expected,o)}}}function Oc(e,t,n,o,a){let i=Array.isArray(n)?n.flat(1/0):[n],r=o?i:i.flatMap(s=>typeof s=="string"?s.split(","):[s]);for(let s of r)if(typeof s=="string"&&s.trim().length===0){let l=pt(s,t);Xn(e,t,s,l.expected,a)}}function Qn(e,t,n,o){if(!Zn(e,n))return t;let a=n==="boolean"&&gr(e),i=r=>{let s=pt(r,n);return s===null?r:a&&typeof r=="string"?!0:Xn(e,n,r,s.expected,o)};return Array.isArray(t)?t.map(i):i(t)}function Rc(e,t,n,o){for(let a of n)if(!(a===t||!Object.hasOwn(e,a))){if(Object.hasOwn(e,t)){if(o){let i=e[t],r=e[a];e[t]=[...Array.isArray(i)?i:[i],...Array.isArray(r)?r:[r]].filter(s=>s!=null)}delete e[a];continue}e[t]=e[a],delete e[a]}}function hr(e,t,n=e,o){if(t.length===0)return e;let a=Object.create(null);for(let[i,r]of Object.entries(e))a[i]=r;for(let i of t){let r=vc(i);r&&Ic(a,i,r,n,o)}return a}function Ic(e,t,n,o,a){let i=t.list===!0,r=Qe(t),s=mr(t);s&&!i&&$c(e,t,n,r,s,a),Rc(e,n,r,i);let l=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=Ec(t.default,s,i,l));return}if(s==="boolean"&&Zn(t,s)&&Tc(t,r,o,a),i){e[n]=Pc(t,r,o,e[n],s,l,a);return}s&&(e[n]=Qn(t,Oe(e[n],s),s,a))}function $c(e,t,n,o,a,i){for(let r of o)r!==n&&Object.hasOwn(e,r)&&Qn(t,Oe(e[r],a),a,i)}function Pc(e,t,n,o,a,i,r){let s=Sc(n,t,o);a&&Zn(e,a)&&Oc(e,a,s,i,r);let l=fr(s,a,i);return a?Qn(e,l,a,r):l}function yr(e){let t=Object.create(null),n=[];Object.defineProperty(t,Kn,{value:n});let o=0;for(;o<e.length;){let a=Jn(e,o);if(!a){o+=1;continue}let i=Ze(a.key);if(i.length===0||Pt(i)){o+=a.consumed;continue}wc(t,i,a.value),n.push({...a,key:i}),o+=a.consumed}return t}function _r(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=Jn(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function eo(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let r of t){let s=mr(r);for(let l of Qe(r))n.add(l),s==="boolean"&&o.add(l)}if(n.size===0)return[...e];let a=[],i=0;for(;i<e.length;){if(e[i]==="--"){a.push(...e.slice(i+1));break}let r=Jn(e,i);if(r){let s=Ze(r.key);if(n.has(s)){let l=e[i],c=o.has(s)&&!l.includes("=")?1:r.consumed;i+=c;continue}}a.push(e[i]),i+=1}return a}import Re from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a2291ff-7618-518c-8bff-e9aa0e2f8af2")}catch{}})();async function to(e,t={},n=[]){let o={readSettings:$,loadExtensions:je,activateExtensions:Ue,resolveImplicitPmRoot:Qt,...t};try{let a=await o.readSettings(e),i=await o.loadExtensions({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1}),r=await o.activateExtensions(i);return[...i.failed,...r.failed].map(s=>{let l=(i.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),c=[...l?.contributions?.commands??[],...l?.contributions?.command_handlers??[],...l?.activation?.commands??[]].map(M).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(M),m=c.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...c.length>0?{declared_commands:c}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(a){return[{layer:"runtime",name:"extension-loader",error:a instanceof Error?a.message:String(a)}]}}async function wr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let a=await to(t,n,o),i={readSettings:$,loadExtensions:je,activateExtensions:Ue,resolveImplicitPmRoot:Qt,...n};try{let r=i.resolveImplicitPmRoot(process.cwd());if(Re.resolve(r)===Re.resolve(t))return a;let[s,l]=await Promise.all([i.readSettings(t),i.readSettings(r)]),[c,d]=await Promise.all([i.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),i.loadExtensions({pmRoot:r,settings:l,cwd:process.cwd(),noExtensions:!1})]),m=new Set(c.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return a;a.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Re.resolve(t)} extension_discovery_root=${c.roots.project}; cwd_storage_root=${Re.resolve(r)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${Re.resolve(r)}, or install the extension into the selected tracker with "pm --pm-path ${Re.resolve(t)} install <package> --project".`})}catch{}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3f896a8d-2c03-5f9c-9909-4684a187870d")}catch{}})();var vr={core:0,standard:1,full:2,internal:3};function br(e,t,n=!0){let o=t.get(I(e));if(o)return o;if(!n)return;let a=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(a.length===0)return;let i=a.reduce((s,l)=>vr[l.tier]<vr[s]?l.tier:s,"internal"),r=new Set(a.map(({family:s})=>s));return{tier:i,family:r.size===1?a[0].family:"extensions"}}function Cr(e,t){if(t.length===0)return e;let n=Z(e,t);if(n)return n;let o=t.join(" ");if(I(o)!==o||!Le.some(a=>a===o)&&!Na(o)&&!He(o)&&!Ae(e,t))return null;for(let a=t.length-1;a>0;a-=1){let i=Z(e,t.slice(0,a));if(i)return i}return t.length===1?e:null}function Dc(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function kr(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 Mc(e){let t=new Map;for(let n of e){let o=n,a=kr(n);if(!a||typeof o.long!="string"||o.long.trim().length===0)continue;let i=t.get(a)??[];i.push(o.long.trim()),t.set(a,i)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(a=>a.trim()).filter(a=>a.length>0))].sort((a,i)=>a.localeCompare(i)));return t}function Nc(e){return C(e)}function Fc(e){let t=e.options??[],n=Mc(t);return t.map(o=>{let a=o,i=typeof a.flags=="string"?a.flags.trim():"",r=typeof a.description=="string"?a.description.trim():"",s=kr(o),l=(s?n.get(s)??[]:[]).filter(h=>h!==a.long).map(h=>h.trim()).filter(h=>h.length>0),c=r.match(/^Alias for ([^ ]+)/i),d=c&&c[1]?c[1].trim():null,m=a.mandatory===!0||r.includes("[required]")||r.toLowerCase().includes("required;"),p=i.includes("<"),u=p||i.includes("["),f={flags:i,long:typeof a.long=="string"?a.long:null,short:typeof a.short=="string"?a.short:null,description:r,takes_value:u,value_required:p,value_name:Dc(i),variadic:a.variadic===!0,required:m,aliases:l,alias_for:d};return a.defaultValue!==void 0&&(f.default_value=a.defaultValue),f})}function Lc(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 a=o.alias_for,i=t.get(a);if(!i)continue;let r=o.long,s=new Set([...i.aliases??[],r]);i.aliases=[...s].sort((l,c)=>l.localeCompare(c))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function jc(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(n=>{let o=typeof n.name=="function"?n.name():typeof n.name=="string"?n.name:"argument",a=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():null;return{name:o.trim(),required:n.required===!0||a?.toLowerCase().startsWith("required;")===!0,variadic:n.variadic===!0,description:a}})}function Uc(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(a=>a.name()!=="help"||e.parent===null).filter(a=>!n||(pe(a)??J(a.name()))!=="internal").map(a=>{let i=M(E(a)),r=i,s=pe(a),l=br(i,t,s!==void 0),c=W.find(({alias:d})=>d===i);return{name:a.name().trim(),aliases:Vn(a),description:a.description().trim(),tier:l?.tier??s??J(r),family:l?.family??xt(r),...c?{alias_for:c.canonical,alias_lifecycle:c.lifecycle,...c.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((a,i)=>a.name.localeCompare(i.name))}function qc(e,t,n){if(!n)return t;let o=n.examples??[],a=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"?a.length>0?[...a]:[...t.tips]:[],detail_mode:e}}function Hc(e,t,n,o,a){let i=e!==void 0&&kn(e)===xe,r=i?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Ai(e,n),s=a?"positional_action":o?.intent||o?.description?"extension":i?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:qc(n,r,o),intentSource:s}}function zc(e,t){return e===void 0?null:t?.tier??J(e)}function Gc(e,t){return e===void 0?null:t?.family??xt(e)}function Wc(e,t,n){if(!(t!==e||!n))return W.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Cr(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function Vc(e,t,n,o,a=new Map,i=!1){if(!e){let s=jc(t),l=Uc(t,a,i),c=new Set(l.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...l,...wt.filter(({parent:d,action:m})=>d===n&&!c.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:J(n.split(" ")[0]),family:xt(n.split(" ")[0])}))].sort((d,m)=>d.name.localeCompare(m.name)),usage:[n,s.reduce((d,m)=>m.required?d.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let r=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:l,variadic:c,value_kind:d,polymorphic:m})=>({name:s,required:l,variadic:c,description:m?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:l})=>s!==null&&r.has(s)||l.some(c=>r.has(c))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:l,variadic:c})=>{let d=c?`${s}...`:s;return l?`<${d}>`:`[${d}]`})].join(" ")}}function Bc(e,t,n,o,a){let i=Cn(n),r=oe(n),s=M(E(t)),l=M(o.join(" ")),c=l.length>s.length?l:s,d=He(c),m=d?.command??s,p=m.length>0?m:void 0,u=p,f=p?a.get(I(p)):void 0,h=p?br(p,a,pe(t)!==void 0):void 0,{narrative:v,intentSource:P}=Hc(p,t.description().trim(),i,f,d!==void 0),z=Lc(rr(Fc(t),ir(f))),Q=Vc(d,t,m,z,a,r),G=Wc(e,t,r);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:zc(u,h),capability_family:Gc(u,h),description:d?.description??t.description(),usage:Q.usage,intent:d?.description??v.intent,intent_source:P,examples:d?[d.example]:v.examples,tips:d?[vt(d.accepted_flags)]:v.tips,arguments:Q.arguments,options:Q.options,subcommands:Q.subcommands,has_subcommands:Q.subcommands.length>0,...G===void 0?{}:{command_aliases:G}}}async function xr(e,t,n,o=t){let a=N(t);if(!a.json)return!1;let i=A(t);if(!i.requested)return!1;let r=Cr(e,i.commandPathTokens);if(!r){if(!a.quiet){let s=`unknown command '${i.commandPathTokens.join(" ")}'`,l=jn(s,e,n,t),c=It(s,"help",Be,g.USAGE,{...l,attemptedCommand:Nc(t),normalizedInvocationArgs:[...t],providedOptionFlags:Y(t)}),d=a.tokenAccounting?ce(c,m=>`${JSON.stringify(m,null,2)}
27
+ `)}`}function Vn(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 Xe(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Vn(o).includes(n))??null}function Z(e,t){let n=e;for(let o of t){let a=Xe(n,o);if(!a)return null;n=a}return n}var Bn=new WeakSet;function cr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let a=t[o];o>0&&R.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let i=Xe(n,a);if(i){n=i;continue}let r=n.command(a);Bn.add(r),o<t.length-1?(r.description("Extension-provided command group."),r.action(()=>{r.help()})):r.description("Extension-provided command path."),n=r}return n}function _c(e,t){let n=t.join(" "),o=R.find(r=>n===r.canonical||n.startsWith(`${r.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let a=e,i=[];for(let r of t){let s=Xe(a,r);if(!s)return null;i.push(r);let l=s.commands.length>0||R.some(c=>c.canonical.startsWith(`${i.join(" ")} `));if(!Bn.has(s)&&(i.length===t.length||!l))return{core_path:i.join(" "),extension_path:t.join(" ")};a=s}return null}function wc(e,t,n,o,a=!1){let i=t.split(" ").filter(d=>d.length>0),r=_c(e,i),s=Z(e,i),l=R.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Bn.has(s)));if(!r||r.core_path===t&&s!==null&&!n.has(t)&&!a||l&&!n.has(t))return null;let c=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${r.extension_path}:core_owner=pm-cli:${r.core_path}:extension_owner=${c}`}function dr(e,t,n,o,a){return[...new Set([...t,...n.keys()])].filter(i=>i.trim().length>0).sort((i,r)=>i.localeCompare(r)).filter(i=>{let r=wc(e,i,o,n.get(i),t.includes(i));return r?(a(r),!o.has(i)&&Z(e,i.split(" "))!==null):!0})}function mr(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]="c6ed71d0-b878-575e-b990-356afdc45688")}catch{}})();var vc=new Set(["__proto__","prototype","constructor"]),Kn=Symbol("looseOptionOccurrences");function Ze(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,n)=>n.toUpperCase())}function bc(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 Jn(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let r=n.indexOf("=");if(r>=0)return{consumed:1,key:n.slice(1,r).trim(),value:n.slice(r+1),attached:!0};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),attached:!0};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let a=n.slice(2).trim(),i=e[t+1];return typeof i=="string"&&!i.startsWith("-")?{consumed:2,key:a,value:i}:{consumed:1,key:a,value:!0}}function Pt(e){return vc.has(e)}function pr(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return aa(t)}function Qe(e){let t=[],n=ee(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let a=Ze(n.slice(2));a.length>0&&!Pt(a)&&t.push(a)}if(o.startsWith("-")&&!o.startsWith("--")){let a=Ze(o.slice(1));a.length>0&&!Pt(a)&&t.push(a)}return[...new Set(t)]}function ur(e){let t=new Set;for(let n of e)for(let o of Qe(n))t.add(o);return t}function Cc(e){let t=ee(e.long)??"";if(t.startsWith("--")){let n=Ze(t.slice(2));if(n.length>0&&!Pt(n))return n}return Qe(e)[0]??null}function fr(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 Yn(e,t,n){if(t.length===0)return;let o=new Set,a=new Map,i=[],r=[];for(let s of t){let l=Qe(s),c=fr(s);c!==null&&r.push(c);for(let d of l)o.add(d),s.enabled===!1&&a.set(d,c);s.required===!0&&s.enabled!==!1&&l.length>0&&i.push({keys:l,label:c})}for(let s of Object.keys(e)){if(!o.has(s)){let c=r.length>0?` Expected one of: ${[...new Set(r)].join(", ")}.`:"";throw new C(`Unknown option '--${s}' for extension command '${n}'.${c}`,g.USAGE)}let l=a.get(s);if(l)throw new C(`Option '${l}' is disabled for extension command '${n}'.`,g.USAGE)}for(let s of i)if(!s.keys.some(l=>Object.hasOwn(e,l)))throw new C(`Missing required option '${s.label}' for extension command '${n}'.`,g.USAGE)}function kc(e){return typeof e=="string"||e==null?e:String(e)}function xc(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 Ec(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 Sc={string:kc,number:xc,boolean:Ec};function Oe(e,t){return Array.isArray(e)?e.map(n=>Oe(n,t)):Sc[t](e)}function gr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(a=>a!=null&&a!==""):tn(e);return t?o.map(a=>Oe(a,t)):o}function Ac(e,t,n,o){return n?gr(e,t,o):t?Oe(e,t):e}function Tc(e,t,n){let o=e[Kn];if(!o||o.length===0)return n;let a=new Set(t);return o.filter(i=>a.has(i.key)).map(i=>i.value)}function hr(e){return we(e).value_arity==="none"}function Xn(e,t,n,o,a){let i=fr(e),r=a?` for extension command '${a}'`:"",s=n===!0?"no value":JSON.stringify(n);throw new C(`Option '${i}'${r} expects ${o}; received ${s}.`,g.USAGE,{code:"extension_flag_value_invalid",required:`Pass ${i} ${t==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${t} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${t} value for ${i}.`,`Run pm ${a??"<command>"} --help to review the declared flag contract.`]})}function Zn(e,t){return e.value_validation==="strict"&&t!=="string"}function Oc(e,t){let n=e[Kn];if(!n)return[];let o=new Set(t);return n.filter(a=>o.has(a.key))}function Rc(e,t,n,o){if(hr(e))for(let a of Oc(n,t)){if(a.attached!==!0)continue;let i=e.list===!0&&e.repeatable!==!0?tn(a.value):[a.value];for(let r of i){let s=pt(Oe(r,"boolean"),"boolean");s!==null&&Xn(e,"boolean",r,s.expected,o)}}}function Ic(e,t,n,o,a){let i=Array.isArray(n)?n.flat(1/0):[n],r=o?i:i.flatMap(s=>typeof s=="string"?s.split(","):[s]);for(let s of r)if(typeof s=="string"&&s.trim().length===0){let l=pt(s,t);Xn(e,t,s,l.expected,a)}}function Qn(e,t,n,o){if(!Zn(e,n))return t;let a=n==="boolean"&&hr(e),i=r=>{let s=pt(r,n);return s===null?r:a&&typeof r=="string"?!0:Xn(e,n,r,s.expected,o)};return Array.isArray(t)?t.map(i):i(t)}function $c(e,t,n,o){for(let a of n)if(!(a===t||!Object.hasOwn(e,a))){if(Object.hasOwn(e,t)){if(o){let i=e[t],r=e[a];e[t]=[...Array.isArray(i)?i:[i],...Array.isArray(r)?r:[r]].filter(s=>s!=null)}delete e[a];continue}e[t]=e[a],delete e[a]}}function yr(e,t,n=e,o){if(t.length===0)return e;let a=Object.create(null);for(let[i,r]of Object.entries(e))a[i]=r;for(let i of t){let r=Cc(i);r&&Pc(a,i,r,n,o)}return a}function Pc(e,t,n,o,a){let i=t.list===!0,r=Qe(t),s=pr(t);s&&!i&&Dc(e,t,n,r,s,a),$c(e,n,r,i);let l=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=Ac(t.default,s,i,l));return}if(s==="boolean"&&Zn(t,s)&&Rc(t,r,o,a),i){e[n]=Mc(t,r,o,e[n],s,l,a);return}s&&(e[n]=Qn(t,Oe(e[n],s),s,a))}function Dc(e,t,n,o,a,i){for(let r of o)r!==n&&Object.hasOwn(e,r)&&Qn(t,Oe(e[r],a),a,i)}function Mc(e,t,n,o,a,i,r){let s=Tc(n,t,o);a&&Zn(e,a)&&Ic(e,a,s,i,r);let l=gr(s,a,i);return a?Qn(e,l,a,r):l}function _r(e){let t=Object.create(null),n=[];Object.defineProperty(t,Kn,{value:n});let o=0;for(;o<e.length;){let a=Jn(e,o);if(!a){o+=1;continue}let i=Ze(a.key);if(i.length===0||Pt(i)){o+=a.consumed;continue}bc(t,i,a.value),n.push({...a,key:i}),o+=a.consumed}return t}function wr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=Jn(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function eo(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let r of t){let s=pr(r);for(let l of Qe(r))n.add(l),s==="boolean"&&o.add(l)}if(n.size===0)return[...e];let a=[],i=0;for(;i<e.length;){if(e[i]==="--"){a.push(...e.slice(i+1));break}let r=Jn(e,i);if(r){let s=Ze(r.key);if(n.has(s)){let l=e[i],c=o.has(s)&&!l.includes("=")?1:r.consumed;i+=c;continue}}a.push(e[i]),i+=1}return a}import Re from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a2291ff-7618-518c-8bff-e9aa0e2f8af2")}catch{}})();async function to(e,t={},n=[]){let o={readSettings:$,loadExtensions:je,activateExtensions:Ue,resolveImplicitPmRoot:Qt,...t};try{let a=await o.readSettings(e),i=await o.loadExtensions({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1}),r=await o.activateExtensions(i);return[...i.failed,...r.failed].map(s=>{let l=(i.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),c=[...l?.contributions?.commands??[],...l?.contributions?.command_handlers??[],...l?.activation?.commands??[]].map(M).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(M),m=c.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...c.length>0?{declared_commands:c}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(a){return[{layer:"runtime",name:"extension-loader",error:a instanceof Error?a.message:String(a)}]}}async function vr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let a=await to(t,n,o),i={readSettings:$,loadExtensions:je,activateExtensions:Ue,resolveImplicitPmRoot:Qt,...n};try{let r=i.resolveImplicitPmRoot(process.cwd());if(Re.resolve(r)===Re.resolve(t))return a;let[s,l]=await Promise.all([i.readSettings(t),i.readSettings(r)]),[c,d]=await Promise.all([i.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),i.loadExtensions({pmRoot:r,settings:l,cwd:process.cwd(),noExtensions:!1})]),m=new Set(c.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return a;a.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Re.resolve(t)} extension_discovery_root=${c.roots.project}; cwd_storage_root=${Re.resolve(r)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${Re.resolve(r)}, or install the extension into the selected tracker with "pm --pm-path ${Re.resolve(t)} install <package> --project".`})}catch{}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3f896a8d-2c03-5f9c-9909-4684a187870d")}catch{}})();var br={core:0,standard:1,full:2,internal:3};function Cr(e,t,n=!0){let o=t.get(I(e));if(o)return o;if(!n)return;let a=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(a.length===0)return;let i=a.reduce((s,l)=>br[l.tier]<br[s]?l.tier:s,"internal"),r=new Set(a.map(({family:s})=>s));return{tier:i,family:r.size===1?a[0].family:"extensions"}}function kr(e,t){if(t.length===0)return e;let n=Z(e,t);if(n)return n;let o=t.join(" ");if(I(o)!==o||!Le.some(a=>a===o)&&!Na(o)&&!He(o)&&!Ae(e,t))return null;for(let a=t.length-1;a>0;a-=1){let i=Z(e,t.slice(0,a));if(i)return i}return t.length===1?e:null}function Nc(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function xr(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 Fc(e){let t=new Map;for(let n of e){let o=n,a=xr(n);if(!a||typeof o.long!="string"||o.long.trim().length===0)continue;let i=t.get(a)??[];i.push(o.long.trim()),t.set(a,i)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(a=>a.trim()).filter(a=>a.length>0))].sort((a,i)=>a.localeCompare(i)));return t}function Lc(e){return b(e)}function jc(e){let t=e.options??[],n=Fc(t);return t.map(o=>{let a=o,i=typeof a.flags=="string"?a.flags.trim():"",r=typeof a.description=="string"?a.description.trim():"",s=xr(o),l=(s?n.get(s)??[]:[]).filter(h=>h!==a.long).map(h=>h.trim()).filter(h=>h.length>0),c=r.match(/^Alias for ([^ ]+)/i),d=c&&c[1]?c[1].trim():null,m=a.mandatory===!0||r.includes("[required]")||r.toLowerCase().includes("required;"),p=i.includes("<"),u=p||i.includes("["),f={flags:i,long:typeof a.long=="string"?a.long:null,short:typeof a.short=="string"?a.short:null,description:r,takes_value:u,value_required:p,value_name:Nc(i),variadic:a.variadic===!0,required:m,aliases:l,alias_for:d};return a.defaultValue!==void 0&&(f.default_value=a.defaultValue),f})}function Uc(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 a=o.alias_for,i=t.get(a);if(!i)continue;let r=o.long,s=new Set([...i.aliases??[],r]);i.aliases=[...s].sort((l,c)=>l.localeCompare(c))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function qc(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(n=>{let o=typeof n.name=="function"?n.name():typeof n.name=="string"?n.name:"argument",a=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():null;return{name:o.trim(),required:n.required===!0||a?.toLowerCase().startsWith("required;")===!0,variadic:n.variadic===!0,description:a}})}function Hc(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(a=>a.name()!=="help"||e.parent===null).filter(a=>!n||(pe(a)??J(a.name()))!=="internal").map(a=>{let i=M(E(a)),r=i,s=pe(a),l=Cr(i,t,s!==void 0),c=W.find(({alias:d})=>d===i);return{name:a.name().trim(),aliases:Vn(a),description:a.description().trim(),tier:l?.tier??s??J(r),family:l?.family??xt(r),...c?{alias_for:c.canonical,alias_lifecycle:c.lifecycle,...c.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((a,i)=>a.name.localeCompare(i.name))}function zc(e,t,n){if(!n)return t;let o=n.examples??[],a=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"?a.length>0?[...a]:[...t.tips]:[],detail_mode:e}}function Gc(e,t,n,o,a){let i=e!==void 0&&kn(e)===xe,r=i?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Ti(e,n),s=a?"positional_action":o?.intent||o?.description?"extension":i?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:zc(n,r,o),intentSource:s}}function Wc(e,t){return e===void 0?null:t?.tier??J(e)}function Vc(e,t){return e===void 0?null:t?.family??xt(e)}function Bc(e,t,n){if(!(t!==e||!n))return W.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:kr(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function Kc(e,t,n,o,a=new Map,i=!1){if(!e){let s=qc(t),l=Hc(t,a,i),c=new Set(l.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...l,...wt.filter(({parent:d,action:m})=>d===n&&!c.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:J(n.split(" ")[0]),family:xt(n.split(" ")[0])}))].sort((d,m)=>d.name.localeCompare(m.name)),usage:[n,s.reduce((d,m)=>m.required?d.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let r=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:l,variadic:c,value_kind:d,polymorphic:m})=>({name:s,required:l,variadic:c,description:m?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:l})=>s!==null&&r.has(s)||l.some(c=>r.has(c))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:l,variadic:c})=>{let d=c?`${s}...`:s;return l?`<${d}>`:`[${d}]`})].join(" ")}}function Jc(e,t,n,o,a){let i=Cn(n),r=oe(n),s=M(E(t)),l=M(o.join(" ")),c=l.length>s.length?l:s,d=He(c),m=d?.command??s,p=m.length>0?m:void 0,u=p,f=p?a.get(I(p)):void 0,h=p?Cr(p,a,pe(t)!==void 0):void 0,{narrative:v,intentSource:P}=Gc(p,t.description().trim(),i,f,d!==void 0),z=Uc(sr(jc(t),rr(f))),Q=Kc(d,t,m,z,a,r),G=Bc(e,t,r);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:Wc(u,h),capability_family:Vc(u,h),description:d?.description??t.description(),usage:Q.usage,intent:d?.description??v.intent,intent_source:P,examples:d?[d.example]:v.examples,tips:d?[vt(d.accepted_flags)]:v.tips,arguments:Q.arguments,options:Q.options,subcommands:Q.subcommands,has_subcommands:Q.subcommands.length>0,...G===void 0?{}:{command_aliases:G}}}async function Er(e,t,n,o=t){let a=N(t);if(!a.json)return!1;let i=A(t);if(!i.requested)return!1;let r=kr(e,i.commandPathTokens);if(!r){if(!a.quiet){let s=`unknown command '${i.commandPathTokens.join(" ")}'`,l=jn(s,e,n,t),c=It(s,"help",Be,g.USAGE,{...l,attemptedCommand:Lc(t),normalizedInvocationArgs:[...t],providedOptionFlags:Y(t)}),d=a.tokenAccounting?ce(c,m=>`${JSON.stringify(m,null,2)}
28
28
  `):c;be(`${JSON.stringify(d,null,2)}
29
- `)}return process.exitCode=g.USAGE,!0}if(!a.quiet){let s=Bc(e,r,t,i.commandPathTokens,n),l=A(o).commandPathTokens;s.requested_path=l;let c=H(l.join(" "));c&&(s.resolved_path=c.canonical),r===e&&!oe(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),Sa(`${JSON.stringify(s,null,2)}
30
- `)}return process.exitCode=g.SUCCESS,!0}function Kc(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(`
31
- `)}function Jc(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)":"",a=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${a.length>0?a.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Yc(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let a of[...t.required_create_fields,...t.required_create_repeatables])o.add(a);return{progressive:n,strict:o}}function Xc(e,t,n,o){let a=new Set(n),i=o.filter(l=>!a.has(l)),r=l=>l.length>0?l.map(c=>Zt("create",c)).join(", "):"none";e.push(` required in strict mode: ${r(i)}`);let s=i.map(di).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 Zc(e,t,n){let o=La(n);if(!o)return Kc(e,t);let a=ea(o,t);if(!a){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
32
- `)}let i=n.indexOf("--"),r=i<0?n:n.slice(0,i),s=r.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),l=s<0?void 0:r[s]?.startsWith("--create-mode=")?r[s]?.slice(14):r[s+1],c=e==="create"&&l?.toLowerCase()==="strict",d=Yc(e,a),m=mt(a,e,d.progressive),p=mt(a,e,c?d.strict:d.progressive),u=h=>h.length>0?h.map(v=>Zt(e,v)).join(", "):"none",f=["",`Type-aware option policies for ${a.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=mt(a,e,d.strict);Xc(f,a,m.required,h.required)}return Jc(f,a),p.errors.length>0&&f.push(` config errors: ${p.errors.join("; ")}`),f.join(`
33
- `)}function Er(e,t,n){let o=x(n);if(o!=="create"&&o!=="update")return;let a=Xe(e,o);a&&a.addHelpText("after",Zc(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]="714821f9-dd8f-5958-a751-29e8dfc06471")}catch{}})();function Qc(e,t){return Fe(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function ed(e){return Fe(e.status)?.toLowerCase()??"pending"}function td(e){return e.mandatory===!0}function nd(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 Tr(e){let t=[];return e.forEach((n,o)=>{if(!td(n.definition))return;let a=ed(n.definition);a!=="applied"&&t.push({layer:n.layer,name:n.name,id:Qc(n.definition,o),status:a})}),t.sort(nd),t}function Sr(e){return Array.isArray(e)&&e.length>0}var od=new Set(["create","beads import","todos import"]),ad=new Set(["restore","update","close","delete","append","claim","release"]),id=new Set(["comments","notes","learnings"]),rd=new Set(["files","docs","test"]),sd=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 no(e,t){let n=t.force===!0;return od.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:ad.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:id.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:rd.has(e)?{isMutation:Sr(t.add)||Sr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function ld(e,t,n){if(no(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Xa(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(a=>sd.has(a.trim().toLowerCase())):!1}function Ar(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function cd(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let a=[];if(Fe(t[1])||a.push("source"),Fe(n.to)||a.push("--to"),a.length!==0)throw new b(`Schema migration requires ${a.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:a.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:a,suggested_flags:a.filter(i=>i.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function dd(e,t,n,o,a){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Ar(n.status)!==Ar(a.schema.workflow.in_progress_status))return;let i=t[0];if(!i)return;let r=re(a,se()),s=await _t(o,i,a.id_prefix,a.item_format,r.type_to_folder);if(!s)return;let l=await Pa(s,{schema:a.schema}),c=typeof n.assignee=="string"?n.assignee.trim():void 0;(c===void 0?l.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(c.toLowerCase())&&c)||_(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function oo(e,t,n,o,a){if(!ld(e,t,n)||(cd(e,t,n),!await V(B(a))))return;let i=await Ce(a);o.json!==!0&&await dd(e,t,n,a,i.settings);let r=Ya({author:ht(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 r.warnings)_(`warning:${s}`)}function Or(e,t,n){if(n.length===0)return;let o=no(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let a=n.map(r=>`extension_migration_blocking:${r.layer}:${r.name}:${r.id}:${r.status}`),i=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new b(`Write command "${e}" blocked by unresolved mandatory extension migrations (${a.join(",")}). ${i}`,g.CONFLICT)}async function ao(e,t,n,o){if(!no(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await V(B(n)))return;let{settings:a,metadata:i,warnings:r}=await Ce(n);for(let s of r)_(`warning:${s}`);if(o.enforce_item_format_gate&&!i.has_explicit_item_format&&(Ra(a),await Ia(n,a,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let s=re(a,se());await Za(n,a.item_format,"item_format:pre_mutation_sync",s.type_to_folder,a.schema)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0826cb1-5181-51b3-9ad9-0cd7a3d2c4b3")}catch{}})();function io(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=w(n);o.length!==0&&t.push(o)}return t}function $e(e){let t=w(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(a=>a.length>0);for(let a of io(e.commandArgs))o.push(...a.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(a=>[a,I(a)]))]}function ro(e,t){let n=w(e);if(n.length===0)return!1;let o=$e(t);for(let a of o)if(a===n||a.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(a=>n.startsWith(`${a} `)):!1}function Mt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...O(n.commands),...O(n.command_handlers),...O(n.command_overrides),...O(n.flag_commands),...O(n.parser_overrides),...Rr(n.preflight_ownership),...Rr(n.renderer_ownership)]:[]}function O(e){return e??[]}function Rr(e){return O(e).flatMap(t=>t.commands)}function et(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Ir=new Set(["hooks","parser","preflight","renderers"]),$r=new Set(["commands","schema","services","importers"]),md=new Set(["reindex","search","search-advanced"]),pd=new Set(["--template"]);function Ie(e,t){for(let n of t)if(e.has(n))return!0;return!1}function so(e){let t=w(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return md.has(n??t)}function lo(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 Nt(e){return w(e.commandPath??"")==="create"&&lo(e,pd)}function co(e){return e.some(t=>{let n=w(t);return n==="templates"||n.startsWith("templates ")})}function Dt(e,t){return e.some(n=>ro(n,t))||Nt(t)&&co(e)}function mo(e){return[O(e.hooks).length,(e.preflight_overrides??0)-O(e.preflight_ownership).length,O(e.item_types).length,O(e.item_fields).length,O(e.relationship_kinds).length,O(e.service_overrides).length,O(e.assurance_providers).length,O(e.renderer_overrides).length-O(e.renderer_ownership).length].some(t=>t>0)}function po(e,t){let n=e.activation?.commands??[];if(n.length>0)return Dt(n,t);let o=Mt(e);if(Dt(o,t)||et(e).has("search")&&so(t.commandPath))return!0;if(e.contributions)return mo(e.contributions)}function Ft(e,t){let n=po(e,t);if(n!==void 0)return n;let o=et(e);return!!(Ie(o,Ir)||Ie(o,$r))}function tt(e,t){return e.effective.length===0?!1:nt(t)!=="all"?e.effective.some(n=>Ft(n,t)):e.effective.some(n=>{let o=et(n);return Mt(n).length>0||Ie(o,Ir)||Ie(o,$r)||o.has("search")})}function nt(e){if(w(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=$e(e).filter(o=>o.split(" ").every(a=>!a.startsWith("-"))).sort((o,a)=>a.length-o.length)[0]??w(e.commandPath??"");if(t.length===0)return"all";let n=Nt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function uo(e){return nt(e)==="all"?void 0:t=>Ft(t,e)}function Pe(e){let t=A(e);if(t.requested&&t.commandPathTokens.length>0){let[a,...i]=t.commandPathTokens;return{commandPath:a,commandArgs:i,allowCommandPrefixMatch:!0}}let n=D(e),o=n.findIndex(a=>a.trim().length>0&&!a.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function fo(e){let t=e.args.map(String);if(w(E(e))==="create"){let n=e.optsWithGlobals();typeof n.template=="string"&&n.template.trim().length>0&&t.push("--template")}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="298624a5-da1b-53ca-aefb-19fbc3fa0401")}catch{}})();var Lt=Symbol.for("pm.readOutputInvocationProvenance");function ie(e,t){let n=Reflect.get(e,Lt);n!==void 0&&Reflect.set(t,Lt,n)}function go(e,t,n){let o=va(t,n);if(!o)return;let a=e;for(;a.parent;)a=a.parent;let i=a.rawArgs,r=new Set(Y(i.slice(2))),s=wa.find(d=>d.command===o),l=Object.values(s?.dimensions??{}).flatMap(d=>d.legacy_aliases.flatMap(m=>r.has(m.flag)?[m.flag]:[])),c=Reflect.get(n,Lt);Reflect.set(n,Lt,{canonical_include_modes:c?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),ie(n,e)}function ud(e){let t=e.optsWithGlobals(),n=E(e);if(I(n)===n)return t;let o=e.opts();for(let a=e.parent;a?.parent;a=a.parent)for(let i of a.options){let r=i.attributeName(),s=a.getOptionValueSource(r)==="cli";if(s&&!e.options.some(l=>l.long===i.long))throw new b(`Unknown option '${i.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:i.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(r)!=="cli"){let l=a.getOptionValue(r);e.setOptionValueWithSource(r,l,"cli")}r in o?t[r]=o[r]:delete t[r]}return t}function ho(e,t,n,o){go(e,t,o);let a=n.outputInclude;if(a===void 0)return;let{selectors:i,modes:r}=ka(t,a,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),r.length===0)return;ie(o,e);let s=Ca(t);for(let c of r){let d=s.get(c),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let l=i.length>0?i.join(","):void 0;l===void 0?delete n.outputInclude:n.outputInclude=l;for(let c=e;c;c=c.parent)c.setOptionValueWithSource("outputInclude",l,"cli");kt(e,n)}function De(e,t,n=[]){let o={...ud(e)};ie(e,o),delete o.json,delete o.quiet,delete o.path,delete o.pmPath,delete o.noExtensions,delete o.extensions,delete o.profile,delete o.pager,delete o.changedFields,delete o.fullChangedFields,delete o.idOnly,delete o.lean,delete o.tokenAccounting,delete o.outputInclude,delete o.outputLimit,delete o.outputBudget,delete o.outputFormat,delete o.outputSession;let a=yr(t);for(let[i,r]of Object.entries(a))o[i]===void 0&&(o[i]=r);if(n.length>0){let i=pr(n),r=ne(E(e)).map(c=>({long:c.flag,short:c.short,aliases:c.aliases})),s={...a};for(let c of i)o[c]!==void 0&&(s[c]=o[c]);Yn(s,[...r,...n],E(e));let l=hr(o,n,a,E(e));return ie(o,l),l}return o}function jt(e,t){let n=w(t);return n.length===0?[]:e.flags.filter(o=>I(w(o.target_command))===I(n)).flatMap(o=>o.flags)}function ot(e,t,n){let o=jt(e,t),a=[t],i=[];for(let r of n){if(r.startsWith("-"))break;a.push(r);let s=jt(e,a.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function Ut(e){return e.arguments??[]}function Pr(e){let t=Ut(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function yo(e,t){if(!e)return!1;let n=w(t);return e.importers.some(o=>w(`${o.importer} import`)===n)||e.exporters.some(o=>w(`${o.exporter} export`)===n)}function _o(e,t){let n=Ut(e),o=n.filter(s=>s.required).length,a=n.some(s=>s.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],r=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new b(`Missing required argument for extension command '${e.command}'. Usage: ${Pr(e)}${r}`,g.USAGE);if(t.length>a){let s=t.slice(a).join(" ");throw new b(`Too many arguments for extension command '${e.command}': ${s}. Usage: ${Pr(e)}${r}`,g.USAGE)}}function fd(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function gd(e,t,n){if(n.length>0){Yn(t,n,e.command);return}let o=Object.keys(t).filter(a=>t[a]!==void 0).sort();if(o.length!==0)throw new b(`Unknown option '${o.map(fd).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function wo(e,t,n,o){e&&(_o(e,t),gd(e,n,o))}import{Command as Dr}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0503f6e5-36d9-5afb-a17f-feef2241f984")}catch{}})();var hd=new Set(["--version","-V"]);function at(e){let t=D(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function Mr(e){if(D(e)[0]!=="item"||!e.includes("--dry-run"))return;let t=new Dr().configureOutput({writeErr:()=>{}}).exitOverride(),n=new Set;for(let a of ze)for(let i of[a.flag,a.short,...a.aliases??[]]){if(i===void 0||n.has(i))continue;n.add(i);let r=a.value_name!==void 0||a.flag==="--pm-path";t.option(`${i}${r?" <value>":""}`)}try{t.parseOptions(e)}catch{}let o=t.opts();return{path:o.pmPath??o.path}}var yd=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),vo=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"]),Nr=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),_d=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),wd=new Set(["claim","close-task","pause-task","release","start-task","test"]),he={setup:!0,listQuery:!0,mutation:!0,operation:!0},vd=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 it(e){return e.some(t=>hd.has(t))}function bd(e,t){if(!R.some(o=>o.canonical_argv[0]===t))return;let n=new Dr().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of ai(t,ne(t))){let a=o.takes_value?o.value_required?" <value>":" [value]":"";for(let i of[o.flag,o.short,...o.aliases??[]])i!==void 0&&n.option(`${i}${a}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return he;let a=q([t,...o.operands])?.alias;if(R.some(i=>i.alias===a))return{...he,targetCommandName:a}}catch{return he}}function bo(e){if(it(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||A(e).requested)return he;let t=x(e);if(!t)return he;let n=t.trim().toLowerCase(),o=D(e),a=q(o)?.alias;return R.some(i=>i.alias===a)?{...he,targetCommandName:a}:bd(o,n==="ctx"?"context":n)||(yd.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:vo.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:Nr.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:_d.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:he)}function Co(e){return e.length===0||A(e).requested||e.includes("--explain")&&x(e)===void 0}function ko(e,t){return at(t)||it(t)?!1:oe(t)||A(t).requested?!0:!!x(t)}function xo(e){if(it(e))return!1;let t=x(e);return t?vd.has(t):!1}function Cd(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,a=e.normalizedTokens.map(c=>{let d=c.indexOf("=");return d>=0?c.slice(0,d):c}).find(c=>c==="--literal"||c==="--regex"||c==="--replacement"),i=a?e.argv.map(c=>{let d=c.indexOf("=");return(d>=0?c.slice(0,d):c)===o?d>=0?`${a}${c.slice(d)}`:a:c}):e.argv,r=qe(i),s=a&&n>=0?`${o}=[redacted]`:t,l=a&&e.normalizedDisplay.includes("=")?`${a}=[redacted]`:e.normalizedDisplay;return{argv:r,normalizedDisplay:l,sourceDisplay:s}}function Eo(e){let t=e.commandName;if(!t)return;let n=e.trace.find(c=>c.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(c=>c.length>0),a=o.length>0?o.join(" "):"the canonical flag",i=Nr.has(t)||wd.has(t),r=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",l=Cd({argv:e.argv,normalizedDisplay:a,normalizedTokens:o,rawFrom:n.from});throw new b(`Refusing to auto-correct ${s} ${l.sourceDisplay} to ${l.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:r,examples:[C(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:C(l.argv)}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d83c356-db56-5116-9fe7-e0c27973b36f")}catch{}})();var kd=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"]),xd=new Set(["parse","preflight","execute","unknown"]),Ed=new Set(["usage","validation","conflict","runtime","unknown"]);function ye(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let a=o.trim();if(a.length>0)return a}}}function So(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function qt(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 Ao(e){if(!e)return;let t=e.trim().toLowerCase();if(kd.has(t))return t}function To(e){if(!e)return;let t=e.trim().toLowerCase();if(xd.has(t))return t}function Oo(e){if(!e)return;let t=e.trim().toLowerCase();if(Ed.has(t))return t}function Ro(e){let t=ye(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(r=>typeof r=="string"&&r.trim().length>0);if(typeof i=="string")return i.trim()}if(So(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let o=qt(e,"failed");if(typeof o=="number"&&o>0)return`failed_runs:${o}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(r=>Xt(r)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function Io(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function $o(){let e=Xt(le()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=qt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,a=li(o),i=ye(e,"error_code","errorCode")??Io(a,o),r=Oo(ye(e,"error_category","errorCategory"))??(a?void 0:dt(i)),s=a?void 0:Ro(e)??`command_exit_${o}`,l=Ao(ye(e,"command_resolution","commandResolution"))??bt({ok:a,errorCode:i,errorCategory:r}),c=To(ye(e,"resolution_stage","resolutionStage"))??"execute";return{ok:a,error:s,exit_code:o,error_code:i,error_category:r,command_resolution:l,resolution_stage:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3e4a18e9-6c97-5b44-95bc-678c3e7bdbcc")}catch{}})();var Po="PM_CLI_PACKAGE_ROOT",Gr=Symbol("pm.deprecatedAliasInvocation"),Gt=new Map;for(let e of W){let t=e.alias.split(" ")[0],n=Gt.get(t)??[];n.push(e),Gt.set(t,n)}for(let e of Gt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function Sd(){return Xo(import.meta.url,["../.."])}(typeof process.env[Po]!="string"||process.env[Po]?.trim().length===0)&&(process.env[Po]=Sd());var Me=null,F=null,Wt=null;function Ad(e){Me=e}function Td(e){T=e}var rt=null,_e=null,T=new Map,Uo=250,Od=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Rd=new Set(["1","true","yes","on"]),Id=We(()=>import("./chunks/register-setup-GNKWL3VL.js")),$d=We(()=>import("./chunks/register-list-query-JOB65KDN.js")),Pd=We(()=>import("./chunks/register-mutation-QMNIN3RJ.js")),Dd=We(()=>import("./chunks/register-operations-Z4VET3I7.js"));function zt(e){return C(e)}function Wr(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=>me(o)??o))];return n.length>0?n:void 0}function Md(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=Y(t),a=new Set(o.map(d=>me(d)??d)),i=Wr(e),r=t.find(d=>y.commands.some(m=>m.name()===d)),s=r?y.commands.find(d=>d.name()===r):void 0,l=new Set([...y.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>me(m)).filter(m=>m!==void 0))),c=i?.filter(d=>{let m=me(d)??d;return a.has(m)?!1:l.has(m)||Hn(t,r,m,T)!==void 0});return c&&c.length>0?c:void 0}function Nd(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let a=n?.[0],i=a?me(a):void 0,r=e.find(p=>y.commands.some(u=>u.name()===p)),s=r?y.commands.find(p=>p.name()===r):void 0,l=i?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(i)):void 0,c=Hn(e,r,i,T),d=i?l?.isBoolean()===!0||c===!1?[i]:[i,"<value>"]:[],m=i?zt([...e,...d]):t;return m===t?void 0:m}function Fd(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 a=e[o];a!=null&&(n[o]=a)}return n}function Ld(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,...Fd(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Vr(e,t,n){let o=qe(t),a=D(o),i=K(a),[r,s]=i===void 0?[]:a.slice(i,i+2),l=o.includes("--explain"),c=vi(o,e?.code,e?.recovery),d=c&&(r==="history-redact"||r==="history"&&s==="redact")?{...c,...c.attempted_command?{attempted_command:zt(o)}:{},...c.normalized_args?{normalized_args:[...o]}:{},...c.suggested_retry?{suggested_retry:zt(o)}:{},...c.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:c;if(d?.recovery_mode==="compact"&&!l)return{...e,recovery:d};let m=zt(o),p=Y(o),u=Md(n,o,d),f=Nd(o,m,u,d),h=Ld({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:f,existingRecovery:d});return{...e,recovery:h}}async function lt(e){let t=F;F=null,await bi(t,e);let n=Me;if(Me=null,!n){ft();return}let o=[],a=ga();try{await Ci({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?a?.map(i=>i.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await ra(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:le(),affected:a}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{ft()}!n.globalOptions.json&&o.length>0&&_(`[pm] warning: afterCommand hook_warnings=${L(o)}`),n.profileEnabled&&o.length>0&&_(`profile:extensions hook_warnings=${L(o)}`)}async function Br(){await Ga()}function Kr(e){return Rd.has((process.env[e]??"").trim().toLowerCase())}function Jr(e){return Kr("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Od.has(Math.trunc(e))}async function Vt(e){return Jr(e.exit_code)?(await Br(),Ja(e),!0):!1}async function Yr(e){let t=de(e.error),n=zi(t);e.bootstrapGlobal.json?_(JSON.stringify(qi(t,g.GENERIC_FAILURE),null,2)):_(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",a="runtime_failed";try{await Br(),fn(e.error);let i=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=i.errorCategory,a=i.commandResolution,await Jt(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:a,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||_(`Failed to report error: ${de(i)}`)}try{await lt({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:a,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||_(`Failed to run error hooks: ${de(i)}`)}try{await ke()}catch(i){e.bootstrapGlobal.json||_(`Failed to flush error reporting: ${de(i)}`)}}var jd={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"},Do=new Map;function Mo(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Xr(e,t){return e.options.some(n=>n.long===t)}function Zr(e,t){return e.options.some(n=>n.short===t)}function No(e,t,n,o){let a=t.trim();if(!a)return;let i=n.length>0?n:`Runtime schema field (${t})`;if(a.startsWith("-")&&!a.startsWith("--")){if(Zr(e,a))return;if(o){e.option(`${a} <value>`,`${i} (repeatable)`,yn);return}e.option(`${a} <value>`,i);return}let r=a.startsWith("--")?a:`--${a}`;if(!Xr(e,r)){if(o){e.option(`${r} <value>`,`${i} (repeatable)`,yn);return}e.option(`${r} <value>`,i)}}async function Qr(e,t){let n=jd[e];if(!n)return[];let o=`${t}:${n}`,a=Do.get(o);if(a)return a;if(!await V(B(t)))return Do.set(o,[]),[];let i=await $(t),r=(pn(i.schema).command_to_fields.get(n)??[]).flatMap(s=>[s.cli_flag,...s.cli_aliases].map(l=>({long:`--${l}`,type:Mo(s.type),value_type:Mo(s.type)})));return Do.set(o,r),r}async function es(e,t){let n=N(t),o=S(process.cwd(),n.path);if(!await V(B(o)))return;let a=_e?.key===zo(o)?_e.snapshot:null,i=a===null?await $(o):a.settings,r=pn(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 c=Z(e,l.path.split(" "));if(c)for(let d of r.command_to_fields.get(l.command)??[]){let m=d.description??"";No(c,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)No(c,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function qo(e,t,n,o,a){let i=x(n);if(!(i!=="create"&&i!=="update"))try{let r=a??await $(t),s=re(r,o);Er(e,s,n)}catch{}}function Fo(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function ts(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Ho(e){return e.some(t=>t==="--profile")}function zo(e){return`pm-root:${e}`}function Lo(e){for(let t of e)t.startsWith("settings_read_")&&_(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function ns(e,t){e.profile&&(_(`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&&_(`profile:extensions activation_warnings=${L(t.activationWarnings)}`))}function Bt(e,t,n){if(!e)return;let o=w(n.commandPath??"")||"<none>";_(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function Kt(e,t=Ce){let n=zo(e);if(_e?.key===n)return _e.snapshot;try{let o=Date.now(),{settings:a,warnings:i}=await t(e),r=await sa({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:a,discovery:r,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return _e={key:n,snapshot:s},s}catch{return _e={key:n,snapshot:null},null}}async function Ne(e,t,n=$){let o=t?nt(t):"all",a=ts(e,o);if(rt?.key===a)return rt.snapshot;try{let i=await n(e),r=await je({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?uo(t):void 0}),s=await Ue({...r,loaded:r.loaded}),l=[...new Set(s.commands.handlers.map(u=>w(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),c=Qi(s.registrations.flags),d=Xi(s.commands.handlers,s.registrations.commands),m=tr(l,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:i,commandHandlers:l,commandFlagHelp:c,commandDescriptors:m,commandAliases:d,loadWarnings:[...r.warnings],activationWarnings:[...s.warnings],loadedCount:r.loaded.length,loadFailedCount:r.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:r.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return rt={key:a,snapshot:p},p}catch{return rt={key:a,snapshot:null},null}}async function os(e){let t=Ve(e);if(t.noExtensions){let r=S(process.cwd(),t.path);return await V(B(r))&&Lo((await Ce(r)).warnings),null}let n=S(process.cwd(),t.path),o=await Kt(n);if(!o)return null;Lo(o.settingsReadWarnings);let a={commandPath:E(e),commandArgs:fo(e)};if(!tt(o.discovery,a))return Bt(t.profile,o,a),null;let i=await Ne(n,a);return i?(ns(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 Go(e){let t=await Ne(e);return t?new Map(t.commandDescriptors):T}async function Ud(e,t){return!e.requested||t.noExtensions||Ae(y,e.commandPathTokens)?T:Go(S(process.cwd(),t.path))}async function as(e,t){return(await Ma({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function is(e,t,n){let o=t.author;return Da(e,pi.forActiveExtensionHost({pmRoot:e,author:o}),o,w(n))}async function rs(e,t,n,o=[]){let a=E(e),i=eo(e.args.map(String),o),r={...t};delete r.author;let s={...n},l=S(process.cwd(),n.path),c=await gt({command:a,args:i,options:r,global:s,pm_root:l});n.profile&&c.warnings.length>0&&_(`profile:extensions parser_warnings=${L(c.warnings)}`),i=c.context.args,r=c.context.options,s=c.context.global,wo(T.get(w(a)),i,r,o),ve(void 0),ut({command:a,args:i,options:{...r},global:{...s},pm_root:l});let d=await on({command:a,args:i,options:r,global:s,pm_root:l,sdk:is(l,s,a)});if(s.profile&&d.warnings.length>0&&_(`profile:extensions command_handler_warnings=${L(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new b(`Command "${a}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new b(`Command "${a}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ve(d.result),d.result}var Fr=Symbol("pm.wrappedActionHandler");function qd(e,t){let n=e[e.length-1];return n instanceof jo?n:t}function Lr(e,t,n){e&&n.length>0&&_(`profile:extensions ${t}=${L(n)}`)}function Hd(e){let t=T.get(w(e.commandPath));if(!t||!yo(e.activeRegistrations,e.commandPath))return;let n=Ut(t).length===0?_r(e.commandArgs):eo(e.commandArgs,e.extensionFlagDefinitions);_o(t,n)}function zd(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 ss(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[Fr]!==!0){let a=o._actionHandler;o._actionHandler=async function(...i){let r=qd(i,n),s=Date.now();hn(r);let l=Ve(r),c=I(E(r));if(["package inventory","packages inventory","extension inventory"].includes(c))return await a.apply(this,i);let d=S(process.cwd(),l.path),m=r.args.map(String),p=se(),u=p?ot(p,c,m):[],f=await Qr(c,d),h=De(r,m,[...u,...f]);T.has(w(c))&&delete h.author;let v=await gt({command:c,args:m,options:h,global:l,pm_root:d});Lr(l.profile,"parser_warnings",v.warnings),m=v.context.args,h=v.context.options,ie(r,h),l=v.context.global,Hd({activeRegistrations:p,commandPath:c,commandArgs:m,extensionFlagDefinitions:u}),l=await ni(l),kt(r,l),zd(r,i,m),Ct(r,h),ve(void 0),ut({command:c,args:m,options:{...h},global:{...l},pm_root:d});let P=await on({command:c,args:m,options:h,global:l,pm_root:d,sdk:is(d,l,c)});if(Lr(l.profile,"command_handler_warnings",P.warnings),P.handled){ve(P.result),rn(P.result,{...l,command:c,commandArgs:m,commandOptions:h,pmRoot:d}),l.profile&&_(`profile:command=${c} took_ms=${Date.now()-s}`);return}return await a.apply(this,i)},o[Fr]=!0}for(let a of n.commands)t(a)};t(e)}async function Ht(e){T=new Map,te({overrides:[]}),e&&await qo(e.rootProgram,e.pmRoot,e.invocationArgv,oa(),e.settings)}function Gd(e,t,n,o){if(t?.flags&&t.flags.length>0){Gn(e,t.flags);let a=Wn(e,t.flags);a&&e.addHelpText("after",a)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function ls(e,t,n){let o={core:0,standard:1,full:2,internal:3},a=(i,r)=>{let s=r.join(" "),l=[...n.entries()].filter(([d])=>d===s||d.startsWith(`${s} `)).map(([,d])=>d),c=l.length===0?"standard":l.reduce((d,m)=>o[m.tier]<o[d]?m.tier:d,"internal");St(i,c);for(let d of i.commands)a(d,[...r,d.name()])};for(let i of e.commands)t.has(i.name())||a(i,[i.name()])}async function cs(e,t){let n=N(t),o=S(process.cwd(),n.path);if(n.noExtensions){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t});return}let a=await Kt(o),i=Pe(t);if(!a){await Ht();return}if(!tt(a.discovery,i)){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings}),Bt(Ho(t),a,i);return}let r=await Ne(o,i);if(!r){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings});return}te(r.services),T=new Map(r.commandDescriptors),await qo(e,o,t,r.registrations,r.settings);let s=cr(e,r.commandHandlers,r.commandDescriptors,r.commandAliases,d=>dr(r.activationWarnings,_,d)),l=new Set(e.commands.map(d=>d.name())),c=d=>{let m=d.split(" ").filter(z=>z.length>0),p=r.commandDescriptors.get(d),u=Z(e,m),f=r.commandFlagHelp.get(d),h=p?sr(p):null;if(u){Gd(u,p,f,h);return}let v=lr(e,m);p?.description&&v.description(p.description);let P=f;p&&(nr(v,p),p.flags.length>0&&(Gn(v,p.flags),P=Wn(v,p.flags)??void 0)),P&&v.addHelpText("after",P),h&&v.addHelpText("after",h),v.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...z)=>{let Q=z[z.length-1],G=Q instanceof jo?Q:v,ct=Ve(G),bs=Date.now(),Bo=ot(r.registrations,d,G.args.map(String)),Ko=De(G,G.args.map(String),Bo),Jo=await rs(G,Ko,ct,Bo);await oi(ct,Jo),rn(Jo,{...ct,command:d,commandArgs:G.args.map(String),commandOptions:Ko,pmRoot:o}),ct.profile&&_(`profile:command=${d} took_ms=${Date.now()-bs}`)})};for(let d of s)c(d);ls(e,l,r.commandDescriptors)}var st=Zo(import.meta.url,["../.."])??"0.0.0",y=sn(st);async function jr(e){if(!F)return;let t=Reflect.get(e,Gr);typeof t=="string"&&await mi(t)}async function Ur(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function qr(e,t,n){!F||!await un(!0)||(Wa(e,t,n,{source_context:F.source_context,source_context_source:F.source_context_source}),Va(e),Wt=F)}async function Jt(e,t,n){let o=Wt;if(!o)return;Wt=null;let a=!1;try{let i=await $(o.global_pm_root);a=i.telemetry.enabled&&i.telemetry.installation_id===o.installation_id}catch{}await un(a)?Ka(e,t,n):Ba()}async function Wd(e){let t=await os(e);return nn(t?.registrations??null),t}function ds(e,t){t&&at(t)||(e.hook("preAction",async(n,o)=>{Me=null,F=null,Wt=null,ft(),hn(o);let a=o.optsWithGlobals(),i=Ve(o),r=I(E(o)),s=o.args.map(String),l=De(o,s),c={...i},d=S(process.cwd(),i.path),m=await Wd(o);if(ba(r,{...l,outputInclude:a.outputInclude,outputLimit:a.outputLimit,outputBudget:a.outputBudget,outputFormat:a.outputFormat,outputSession:a.outputSession,outputCursor:a.outputCursor}),ho(o,r,c,l),await Ur(o,void 0,()=>Qa(r,c)),!m){Me=la({commandName:r,commandArgs:s,commandOptions:l,globalOptions:c,pmRoot:d}),F=await gn({command:r,pm_version:st,args:s,options:l,global:c,pm_root:d}),await jr(e),await qr(r,s,l),await ao(r,l,d,Fo()),await oo(r,s,l,c,d);return}ca(m.hooks),da(m.commands),ma(m.parsers),pa(m.preflight),te(m.services),ua(m.renderers),nn(m.registrations);let p=ot(m.registrations,r,s);l=De(o,s,p),ho(o,r,c,l);let u=await gt({command:r,args:s,options:l,global:c,pm_root:m.pmRoot});c.profile&&u.warnings.length>0&&_(`profile:extensions parser_warnings=${L(u.warnings)}`),s=u.context.args,l=u.context.options,ie(o,l),c=u.context.global,Ct(o,l);let f=await ha({command:r,args:s,options:l,global:c,pm_root:m.pmRoot,decision:Fo()});c.profile&&f.warnings.length>0&&_(`profile:extensions preflight_warnings=${L(f.warnings)}`),s=f.context.args,l=f.context.options,ie(o,l),c=f.context.global,Ct(o,l);let h=f.decision;await ao(r,l,m.pmRoot,h),await oo(r,s,l,c,m.pmRoot);let v=h.run_extension_migrations?await Ur(o,[],()=>as(m.registrations.migrations,m.pmRoot)):[];c.profile&&v.length>0&&_(`profile:extensions migration_warnings=${L(v)}`);let P=Tr(m.registrations.migrations);Me={hooks:m.hooks,commandName:r,commandArgs:s,commandOptions:{...l},globalOptions:{...c},pmRoot:m.pmRoot,profileEnabled:!!c.profile,migrationBlockers:P},ve(void 0),ut({command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot}),F=await gn({command:r,pm_version:st,args:s,options:l,global:c,pm_root:m.pmRoot}),await jr(e),await qr(r,s,l);let z=await ia(m.hooks,{command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot});c.profile&&z.length>0&&_(`profile:extensions hook_warnings=${L(z)}`),h.enforce_mandatory_migration_gate&&Or(r,l,P)}),e.hook("postAction",async()=>{let n=$o();await Jt(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await lt(n),await ke()}))}ds(y);var Hr=Symbol("pmCliIdempotentTopLevelRegistration");function ms(e){let t=e;if(t[Hr])return;t[Hr]=!0;let n=e.command.bind(e);e.command=((o,...a)=>{let i=o.split(/\s+/u)[0];return e.commands.some(r=>r.name()===i||r.aliases().includes(i))?new jo(i):n(o,...a)})}async function Vd(e,t){if(ms(e),t.setup){let{registerSetupCommands:n}=await Id();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await $d(),o=typeof t.targetCommandName=="string"&&vo.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Pd();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Dd();n(e)}}function Bd(e){return async t=>{let n=dt(t.errorCode),o=bt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await ti({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:st,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 ps(e){if(e.bootstrapGlobal.noExtensions||at(e.invocationArgv))return;let t=Pe(e.invocationArgv),n=await Kt(e.bootstrapPmRoot);if(n&&tt(n.discovery,t)){let o=await Ne(e.bootstrapPmRoot,t);us(o);return}n&&Bt(Ho(e.invocationArgv),n,t),te({overrides:[]})}function us(e){if(!e){te({overrides:[]});return}te(e.services)}async function Wo(e){await Jt(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await lt({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 fs(){await Jt(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await lt({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function gs(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof b)&&(dn(e.error)||!n))return!1;let o=de(e.error),a=e.error instanceof b?e.error.exitCode:cn(t),i=e.error instanceof b?e.error.context:void 0,r=Vr(i,e.invocationArgv,o),s=ji(o,r),l=e.bootstrapGlobal.lean?Ot(Dn(o,a,r)):Dn(o,a,r),c=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?ce(l,u=>`${JSON.stringify(u,null,2)}
34
- `):l,null,2):Li(o,r);e.jsonErrors?be(`${c}
35
- `):_(c);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:a,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Vt({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:a,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:F?.source_context});return await Wo({errorMessage:o,exitCode:a,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(fn(mn(e.error,o)),await ke(Uo)),process.exitCode=a,!0}async function hs(e,t){let n=A(e.invocationArgv).commandPathTokens.join(" ")||Fn(e.invocationArgv),o=I(n),a=`unknown command '${n}'`,i=S(process.cwd(),e.bootstrapGlobal.path),r=e.bootstrapGlobal.noExtensions?T:await Go(i),s=Pe(e.invocationArgv),l=e.bootstrapGlobal.noExtensions?[]:await to(i,{},$e(s)),c=await Je({message:a},y,r,{failedExtensions:l},e.invocationArgv),d=Mn(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:l}),{errorCategory:m,commandResolution:p}=await e.emitTelemetryCommandError({command:o,errorCode:d.code,errorMessage:d.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),u=await Vt({command:o,error_code:d.code,error_category:m,exit_code:g.USAGE,error_message:d.detail,command_resolution:p,resolution_stage:"parse"}),f=e.jsonErrors?await qn({message:a},y,r,e.bootstrapGlobal.lean===!0,{failedExtensions:l},e.invocationArgv):await Un({message:a},y,r,{failedExtensions:l},e.invocationArgv),h=Nn(f,e.jsonErrors,l);await Wo({errorMessage:a,exitCode:g.USAGE,classificationCode:d.code,errorCategory:m,commandResolution:p,resolutionStage:"parse"}),e.jsonErrors?be(`${h}
36
- `):_(h),u&&await ke(Uo),process.exitCode=g.USAGE}async function ys(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let o=A(e.invocationArgv);return o.requested&&!Ae(y,o.commandPathTokens)?(await hs(e,t),!0):(await fs(),!0)}async function _s(e,t){let n=await Je(e.error,y,T,{},e.invocationArgv),o=Mn(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:a,commandResolution:i}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),r=await Vt({command:e.attemptedCommand,error_code:o.code,error_category:a,exit_code:g.USAGE,error_message:o.detail,command_resolution:i,resolution_stage:"parse",source_context:F?.source_context}),s=e.jsonErrors?await qn(e.error,y,T,e.bootstrapGlobal.lean===!0,{},e.invocationArgv):await Un(e.error,y,T,{},e.invocationArgv),l=await wr(o.code,e.bootstrapPmRoot,{},$e(Pe(e.invocationArgv))),c=Nn(s,e.jsonErrors,l);await Wo({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:a,commandResolution:i,resolutionStage:"parse"}),e.jsonErrors?be(`${c}
37
- `):_(c),r&&await ke(Uo),process.exitCode=g.USAGE}function ws(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 vs(e){let t=e.error.code,n=String(e.error.message??"");if(!await ys(e,t,n)){if(t==="commander.version"){await fs();return}await _s(e,t)}}async function Vo(e){let t=N(e.invocationArgv),n=S(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:x(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:Bd({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await ps({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await gs(o,ln(e.error))){if(ws(e.error)){await vs(o);return}await Yr({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}function Kd(e,t,n){let o=n.requested?n.commandPathTokens:D(t),a=q(o);if(a&&!Z(e,[...a.canonical_argv]))throw new zr(g.USAGE,"commander.unknownCommand",`unknown command '${a.alias}'`)}function Jd(e,t){let n=K(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let r=K(t.slice(n+1));if(r===void 0)return;n+=r+1}let o=Gt.get(t[n]),a=t.slice(n).filter(r=>!["--global","--project","--local"].includes(r)),i=o?.find(r=>r.alias.split(" ").every((s,l)=>a[l]===s));i?.lifecycle==="deprecated"&&Reflect.set(e,Gr,i.alias)}function Yd(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function Xd(e,t){y=sn(st),y.hook("preAction",(i,r)=>{t.configurationOnly=["item mutate","item complete"].includes(E(r))&&r.optsWithGlobals().dryRun===!0}),ds(y,e),rt=null,_e=null,T=new Map,fa();let n=[...e],o,a;try{let i=Ge(e);n=i.argv,Jd(y,e);let r=Yd(n),s=n.length===0,l=N(n);if(l.authorMissingValue)throw new b("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=Ha(l.author),Eo(i),a=Fa(n);let c=bo(n);await Vd(y,c),xn(y,!0),ko(y,n)?await cs(y,n):(T=new Map,te({overrides:[]})),xo(n)&&await es(y,n),xn(y);let d=A(n);Kd(y,n,d),Co(n)&&Ti(y,n),ss(y);let m=await Ud(d,l);if(await xr(y,n,m,e))return;if(d.requested&&!Ae(y,d.commandPathTokens))throw new zr(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||oe(n)&&x(n)===void 0){y.outputHelp();return}if(at(n)){await y.parseAsync(r);return}let p=S(process.cwd(),l.path),u=await $(p),f=await Ji(n,p,l.noExtensions,Ne);await Aa({pmRoot:p,packages:f?.contextIntentPackages},()=>Ta({env:{...process.env,PM_PATH:p},argv:r,cwd:process.cwd()},()=>Oa(u.agent_identity.harness_signals,()=>y.parseAsync(r),{probesEnabled:u.agent_identity?.probes_enabled})))}catch(i){await Vo({error:i,invocationArgv:n})}finally{a?.(),o?.()}}async function xu(e=process.argv.slice(2)){let t=e;try{t=Ge(e).argv}catch{}let n=Mr(t),o={configurationOnly:n!==void 0},a=()=>o.configurationOnly,i=async()=>{try{await za(process.env,()=>Xd(e,o))}catch(r){await Vo({error:r,invocationArgv:[...e]})}};if(n!==void 0){let r=S(process.cwd(),N(t).path),s=S(process.cwd(),n.path),l=na(process.cwd());await yt(r,()=>yt(s,()=>yt(l,i,a),a),a)}else await i()}var Eu={activationCommandMatchesProbe:ro,applyDynamicExtensionRootHelpVisibility:ls,bootstrapProfileEnabled:Ho,buildBootstrapActivationProbe:Pe,buildPostActionTelemetryOutcome:$o,buildPmCliRecoveryContext:Vr,buildRuntimeExtensionDiscoverySnapshotCacheKey:zo,buildRuntimeExtensionActivationScope:nt,buildRuntimeExtensionSnapshotCacheKey:ts,buildRuntimeExtensionFilterForProbe:uo,addRuntimeFieldOption:No,collectActivationCommandCandidates:$e,collectExtensionFlagDefinitionsForCommand:jt,collectExtensionFlagDefinitionsForInvocation:ot,collectLeadingCommandArgs:io,collectParsedActivationCommandArgs:fo,collectRuntimeFieldLooseFlagDefinitionsForCommand:Qr,commandHasLongOption:Xr,commandHasShortOption:Zr,commandPathNeedsSearchExtensions:so,commandPathNeedsTemplateExtensions:Nt,describeUnknownError:de,defaultPreflightDecision:Fo,discoveryNeedsActivationForProbe:tt,emitExtensionProfile:ns,emitExtensionSkippedProfile:Bt,emitSettingsReadWarnings:Lo,ensureIdempotentTopLevelCommandRegistration:ms,enforceExplicitRetryForFlagTypos:Eo,envFlagEnabled:Kr,executeRegisteredRuntimeMigrations:as,extractCommandScopedOptions:De,extensionActivationCommands:Mt,extensionCapabilities:et,extensionNeedsActivationForProbe:Ft,extensionProvidesTemplatesRuntime:co,hasAnyCapability:Ie,hasGlobalExtensionContributions:mo,handleGenericRunPmCliError:Yr,handleRunPmCliCommanderError:vs,handleRunPmCliError:Vo,handleRunPmCliHelpDisplayError:ys,handleRunPmCliKnownError:gs,handleRunPmCliCommanderUsageError:_s,handleUnknownHelpCommandError:hs,inferMissingFieldsFromErrorMessage:Wr,inferPostActionErrorCode:Io,inferPostActionFailureMessage:Ro,invocationRequestsVersion:it,isCommanderError:dn,loadRuntimeExtensionCommandDescriptorsForRecovery:Go,loadRuntimeExtensionDiscoverySnapshot:Kt,loadRuntimeExtensionSnapshot:Ne,maybeLoadRuntimeExtensions:os,maybeAttachCreateUpdatePolicyHelpText:qo,maybeLogHandledCliErrorToSentry:Vt,matchesStaticExtensionCommand:Dt,normalizeTelemetryCommandResolution:Ao,normalizeTelemetryErrorCategory:Oo,normalizeTelemetryResolutionStage:To,normalizeThrownExitCode:cn,probeUsesAnyFlag:lo,prepareExtensionServicesForRunPmCliError:ps,readRecordBoolean:So,readRecordNumber:qt,readRecordString:ye,recordCliReadOutputInvocationProvenance:go,registerDynamicExtensionCommandPaths:cs,registerRuntimeSchemaFieldFlags:es,resolveCoreCommandRegistrationSelection:bo,resolveStaticExtensionActivationDecision:po,resolveUnknownHelpToken:Fn,readThrownExitCode:ln,runAndClearAfterCommandHooks:lt,runRequiredExtensionCommand:rs,shouldAttachRichHelpTextForInvocation:Co,shouldLogHandledErrorToSentry:Jr,shouldRegisterDynamicExtensionPaths:ko,shouldRegisterRuntimeSchemaFlags:xo,shouldHandleRunPmCliCommanderError:ws,setActiveExtensionHookContextForTest:Ad,setActiveRuntimeExtensionCommandDescriptorsForTest:Td,setRecoveredExtensionServices:us,toLooseFieldDefinitionType:Mo,isImporterOrExporterCommandPath:yo,validateDynamicExtensionCommandInvocation:wo,wrapProgramActionsForExtensionHandlers:ss,wrapThrownErrorForSentry:mn};export{Eu as _testOnly,xu as runPmCli};
29
+ `)}return process.exitCode=g.USAGE,!0}if(!a.quiet){let s=Jc(e,r,t,i.commandPathTokens,n),l=A(o).commandPathTokens;s.requested_path=l;let c=H(l.join(" "));c&&(s.resolved_path=c.canonical),r===e&&!oe(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),Sa(`${JSON.stringify(s,null,2)}
30
+ `)}return process.exitCode=g.SUCCESS,!0}function Yc(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(`
31
+ `)}function Xc(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)":"",a=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${a.length>0?a.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Zc(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let a of[...t.required_create_fields,...t.required_create_repeatables])o.add(a);return{progressive:n,strict:o}}function Qc(e,t,n,o){let a=new Set(n),i=o.filter(l=>!a.has(l)),r=l=>l.length>0?l.map(c=>Zt("create",c)).join(", "):"none";e.push(` required in strict mode: ${r(i)}`);let s=i.map(mi).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 ed(e,t,n){let o=La(n);if(!o)return Yc(e,t);let a=ea(o,t);if(!a){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
32
+ `)}let i=n.indexOf("--"),r=i<0?n:n.slice(0,i),s=r.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),l=s<0?void 0:r[s]?.startsWith("--create-mode=")?r[s]?.slice(14):r[s+1],c=e==="create"&&l?.toLowerCase()==="strict",d=Zc(e,a),m=mt(a,e,d.progressive),p=mt(a,e,c?d.strict:d.progressive),u=h=>h.length>0?h.map(v=>Zt(e,v)).join(", "):"none",f=["",`Type-aware option policies for ${a.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=mt(a,e,d.strict);Qc(f,a,m.required,h.required)}return Xc(f,a),p.errors.length>0&&f.push(` config errors: ${p.errors.join("; ")}`),f.join(`
33
+ `)}function Sr(e,t,n){let o=x(n);if(o!=="create"&&o!=="update")return;let a=Xe(e,o);a&&a.addHelpText("after",ed(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]="714821f9-dd8f-5958-a751-29e8dfc06471")}catch{}})();function td(e,t){return Fe(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function nd(e){return Fe(e.status)?.toLowerCase()??"pending"}function od(e){return e.mandatory===!0}function ad(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 Or(e){let t=[];return e.forEach((n,o)=>{if(!od(n.definition))return;let a=nd(n.definition);a!=="applied"&&t.push({layer:n.layer,name:n.name,id:td(n.definition,o),status:a})}),t.sort(ad),t}function Ar(e){return Array.isArray(e)&&e.length>0}var id=new Set(["create","beads import","todos import"]),rd=new Set(["restore","update","close","delete","append","claim","release"]),sd=new Set(["comments","notes","learnings"]),ld=new Set(["files","docs","test"]),cd=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 no(e,t){let n=t.force===!0;return id.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:rd.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:sd.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:ld.has(e)?{isMutation:Ar(t.add)||Ar(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function dd(e,t,n){if(no(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Za(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(a=>cd.has(a.trim().toLowerCase())):!1}function Tr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function md(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let a=[];if(Fe(t[1])||a.push("source"),Fe(n.to)||a.push("--to"),a.length!==0)throw new C(`Schema migration requires ${a.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:a.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:a,suggested_flags:a.filter(i=>i.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function pd(e,t,n,o,a){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Tr(n.status)!==Tr(a.schema.workflow.in_progress_status))return;let i=t[0];if(!i)return;let r=re(a,se()),s=await _t(o,i,a.id_prefix,a.item_format,r.type_to_folder);if(!s)return;let l=await Pa(s,{schema:a.schema}),c=typeof n.assignee=="string"?n.assignee.trim():void 0;(c===void 0?l.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(c.toLowerCase())&&c)||_(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function oo(e,t,n,o,a){if(!dd(e,t,n)||(md(e,t,n),!await V(B(a))))return;let i=await Ce(a);o.json!==!0&&await pd(e,t,n,a,i.settings);let r=Xa({author:ht(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 r.warnings)_(`warning:${s}`)}function Rr(e,t,n){if(n.length===0)return;let o=no(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let a=n.map(r=>`extension_migration_blocking:${r.layer}:${r.name}:${r.id}:${r.status}`),i=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new C(`Write command "${e}" blocked by unresolved mandatory extension migrations (${a.join(",")}). ${i}`,g.CONFLICT)}async function ao(e,t,n,o){if(!no(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await V(B(n)))return;let{settings:a,metadata:i,warnings:r}=await Ce(n);for(let s of r)_(`warning:${s}`);if(o.enforce_item_format_gate&&!i.has_explicit_item_format&&(Ra(a),await Ia(n,a,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let s=re(a,se());await Qa(n,a.item_format,"item_format:pre_mutation_sync",s.type_to_folder,a.schema)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0826cb1-5181-51b3-9ad9-0cd7a3d2c4b3")}catch{}})();function io(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=w(n);o.length!==0&&t.push(o)}return t}function $e(e){let t=w(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(a=>a.length>0);for(let a of io(e.commandArgs))o.push(...a.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(a=>[a,I(a)]))]}function ro(e,t){let n=w(e);if(n.length===0)return!1;let o=$e(t);for(let a of o)if(a===n||a.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(a=>n.startsWith(`${a} `)):!1}function Mt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...O(n.commands),...O(n.command_handlers),...O(n.command_overrides),...O(n.flag_commands),...O(n.parser_overrides),...Ir(n.preflight_ownership),...Ir(n.renderer_ownership)]:[]}function O(e){return e??[]}function Ir(e){return O(e).flatMap(t=>t.commands)}function et(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var $r=new Set(["hooks","parser","preflight","renderers"]),Pr=new Set(["commands","schema","services","importers"]),ud=new Set(["reindex","search","search-advanced"]),fd=new Set(["--template"]);function Ie(e,t){for(let n of t)if(e.has(n))return!0;return!1}function so(e){let t=w(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return ud.has(n??t)}function lo(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 Nt(e){return w(e.commandPath??"")==="create"&&lo(e,fd)}function co(e){return e.some(t=>{let n=w(t);return n==="templates"||n.startsWith("templates ")})}function Dt(e,t){return e.some(n=>ro(n,t))||Nt(t)&&co(e)}function mo(e){return[O(e.hooks).length,(e.preflight_overrides??0)-O(e.preflight_ownership).length,O(e.item_types).length,O(e.item_fields).length,O(e.relationship_kinds).length,O(e.service_overrides).length,O(e.assurance_providers).length,O(e.renderer_overrides).length-O(e.renderer_ownership).length].some(t=>t>0)}function po(e,t){let n=e.activation?.commands??[];if(n.length>0)return Dt(n,t);let o=Mt(e);if(Dt(o,t)||et(e).has("search")&&so(t.commandPath))return!0;if(e.contributions)return mo(e.contributions)}function Ft(e,t){let n=po(e,t);if(n!==void 0)return n;let o=et(e);return!!(Ie(o,$r)||Ie(o,Pr))}function tt(e,t){return e.effective.length===0?!1:nt(t)!=="all"?e.effective.some(n=>Ft(n,t)):e.effective.some(n=>{let o=et(n);return Mt(n).length>0||Ie(o,$r)||Ie(o,Pr)||o.has("search")})}function nt(e){if(w(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=$e(e).filter(o=>o.split(" ").every(a=>!a.startsWith("-"))).sort((o,a)=>a.length-o.length)[0]??w(e.commandPath??"");if(t.length===0)return"all";let n=Nt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function uo(e){return nt(e)==="all"?void 0:t=>Ft(t,e)}function Pe(e){let t=A(e);if(t.requested&&t.commandPathTokens.length>0){let[a,...i]=t.commandPathTokens;return{commandPath:a,commandArgs:i,allowCommandPrefixMatch:!0}}let n=D(e),o=n.findIndex(a=>a.trim().length>0&&!a.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function fo(e){let t=e.args.map(String);if(w(E(e))==="create"){let n=e.optsWithGlobals();typeof n.template=="string"&&n.template.trim().length>0&&t.push("--template")}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="298624a5-da1b-53ca-aefb-19fbc3fa0401")}catch{}})();var Lt=Symbol.for("pm.readOutputInvocationProvenance");function ie(e,t){let n=Reflect.get(e,Lt);n!==void 0&&Reflect.set(t,Lt,n)}function go(e,t,n){let o=va(t,n);if(!o)return;let a=e;for(;a.parent;)a=a.parent;let i=a.rawArgs,r=new Set(Y(i.slice(2))),s=wa.find(d=>d.command===o),l=Object.values(s?.dimensions??{}).flatMap(d=>d.legacy_aliases.flatMap(m=>r.has(m.flag)?[m.flag]:[])),c=Reflect.get(n,Lt);Reflect.set(n,Lt,{canonical_include_modes:c?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),ie(n,e)}function gd(e){let t=e.optsWithGlobals(),n=E(e);if(I(n)===n)return t;let o=e.opts();for(let a=e.parent;a?.parent;a=a.parent)for(let i of a.options){let r=i.attributeName(),s=a.getOptionValueSource(r)==="cli";if(s&&!e.options.some(l=>l.long===i.long))throw new C(`Unknown option '${i.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:i.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(r)!=="cli"){let l=a.getOptionValue(r);e.setOptionValueWithSource(r,l,"cli")}r in o?t[r]=o[r]:delete t[r]}return t}function ho(e,t,n,o){go(e,t,o);let a=n.outputInclude;if(a===void 0)return;let{selectors:i,modes:r}=ka(t,a,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),r.length===0)return;ie(o,e);let s=Ca(t);for(let c of r){let d=s.get(c),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let l=i.length>0?i.join(","):void 0;l===void 0?delete n.outputInclude:n.outputInclude=l;for(let c=e;c;c=c.parent)c.setOptionValueWithSource("outputInclude",l,"cli");kt(e,n)}function De(e,t,n=[]){let o={...gd(e)};ie(e,o),delete o.json,delete o.quiet,delete o.path,delete o.pmPath,delete o.noExtensions,delete o.extensions,delete o.profile,delete o.pager,delete o.changedFields,delete o.fullChangedFields,delete o.idOnly,delete o.lean,delete o.tokenAccounting,delete o.outputInclude,delete o.outputLimit,delete o.outputBudget,delete o.outputFormat,delete o.outputSession;let a=_r(t);for(let[i,r]of Object.entries(a))o[i]===void 0&&(o[i]=r);if(n.length>0){let i=ur(n),r=ne(E(e)).map(c=>({long:c.flag,short:c.short,aliases:c.aliases})),s={...a};for(let c of i)o[c]!==void 0&&(s[c]=o[c]);Yn(s,[...r,...n],E(e));let l=yr(o,n,a,E(e));return ie(o,l),l}return o}function jt(e,t){let n=w(t);return n.length===0?[]:e.flags.filter(o=>I(w(o.target_command))===I(n)).flatMap(o=>o.flags)}function ot(e,t,n){let o=jt(e,t),a=[t],i=[];for(let r of n){if(r.startsWith("-"))break;a.push(r);let s=jt(e,a.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function Ut(e){return e.arguments??[]}function Dr(e){let t=Ut(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function yo(e,t){if(!e)return!1;let n=w(t);return e.importers.some(o=>w(`${o.importer} import`)===n)||e.exporters.some(o=>w(`${o.exporter} export`)===n)}function _o(e,t){let n=Ut(e),o=n.filter(s=>s.required).length,a=n.some(s=>s.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],r=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new C(`Missing required argument for extension command '${e.command}'. Usage: ${Dr(e)}${r}`,g.USAGE);if(t.length>a){let s=t.slice(a).join(" ");throw new C(`Too many arguments for extension command '${e.command}': ${s}. Usage: ${Dr(e)}${r}`,g.USAGE)}}function hd(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function yd(e,t,n){if(n.length>0){Yn(t,n,e.command);return}let o=Object.keys(t).filter(a=>t[a]!==void 0).sort();if(o.length!==0)throw new C(`Unknown option '${o.map(hd).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function wo(e,t,n,o){e&&(_o(e,t),yd(e,n,o))}import{Command as Mr}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0503f6e5-36d9-5afb-a17f-feef2241f984")}catch{}})();var _d=new Set(["--version","-V"]);function at(e){let t=D(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function Nr(e){if(D(e)[0]!=="item"||!e.includes("--dry-run"))return;let t=new Mr().configureOutput({writeErr:()=>{}}).exitOverride(),n=new Set;for(let a of ze)for(let i of[a.flag,a.short,...a.aliases??[]]){if(i===void 0||n.has(i))continue;n.add(i);let r=a.value_name!==void 0||a.flag==="--pm-path";t.option(`${i}${r?" <value>":""}`)}try{t.parseOptions(e)}catch{}let o=t.opts();return{path:o.pmPath??o.path}}var wd=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),vo=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"]),Fr=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),vd=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),bd=new Set(["claim","close-task","pause-task","release","start-task","test"]),he={setup:!0,listQuery:!0,mutation:!0,operation:!0},Cd=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 it(e){return e.some(t=>_d.has(t))}function kd(e,t){if(!R.some(o=>o.canonical_argv[0]===t))return;let n=new Mr().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of ii(t,ne(t))){let a=o.takes_value?o.value_required?" <value>":" [value]":"";for(let i of[o.flag,o.short,...o.aliases??[]])i!==void 0&&n.option(`${i}${a}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return he;let a=q([t,...o.operands])?.alias;if(R.some(i=>i.alias===a))return{...he,targetCommandName:a}}catch{return he}}function bo(e){if(it(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||A(e).requested)return he;let t=x(e);if(!t)return he;let n=t.trim().toLowerCase(),o=D(e),a=q(o)?.alias;return R.some(i=>i.alias===a)?{...he,targetCommandName:a}:kd(o,n==="ctx"?"context":n)||(wd.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:vo.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:Fr.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:vd.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:he)}function Co(e){return e.length===0||A(e).requested||e.includes("--explain")&&x(e)===void 0}function ko(e,t){return at(t)||it(t)?!1:oe(t)||A(t).requested?!0:!!x(t)}function xo(e){if(it(e))return!1;let t=x(e);return t?Cd.has(t):!1}function xd(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,a=e.normalizedTokens.map(c=>{let d=c.indexOf("=");return d>=0?c.slice(0,d):c}).find(c=>c==="--literal"||c==="--regex"||c==="--replacement"),i=a?e.argv.map(c=>{let d=c.indexOf("=");return(d>=0?c.slice(0,d):c)===o?d>=0?`${a}${c.slice(d)}`:a:c}):e.argv,r=qe(i),s=a&&n>=0?`${o}=[redacted]`:t,l=a&&e.normalizedDisplay.includes("=")?`${a}=[redacted]`:e.normalizedDisplay;return{argv:r,normalizedDisplay:l,sourceDisplay:s}}function Eo(e){let t=e.commandName;if(!t)return;let n=e.trace.find(c=>c.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(c=>c.length>0),a=o.length>0?o.join(" "):"the canonical flag",i=Fr.has(t)||bd.has(t),r=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",l=xd({argv:e.argv,normalizedDisplay:a,normalizedTokens:o,rawFrom:n.from});throw new C(`Refusing to auto-correct ${s} ${l.sourceDisplay} to ${l.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:r,examples:[b(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:b(l.argv)}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d83c356-db56-5116-9fe7-e0c27973b36f")}catch{}})();var Ed=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"]),Sd=new Set(["parse","preflight","execute","unknown"]),Ad=new Set(["usage","validation","conflict","runtime","unknown"]);function ye(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let a=o.trim();if(a.length>0)return a}}}function So(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function qt(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 Ao(e){if(!e)return;let t=e.trim().toLowerCase();if(Ed.has(t))return t}function To(e){if(!e)return;let t=e.trim().toLowerCase();if(Sd.has(t))return t}function Oo(e){if(!e)return;let t=e.trim().toLowerCase();if(Ad.has(t))return t}function Ro(e){let t=ye(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(r=>typeof r=="string"&&r.trim().length>0);if(typeof i=="string")return i.trim()}if(So(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let o=qt(e,"failed");if(typeof o=="number"&&o>0)return`failed_runs:${o}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(r=>Xt(r)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function Io(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function $o(){let e=Xt(le()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=qt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,a=ci(o),i=ye(e,"error_code","errorCode")??Io(a,o),r=Oo(ye(e,"error_category","errorCategory"))??(a?void 0:dt(i)),s=a?void 0:Ro(e)??`command_exit_${o}`,l=Ao(ye(e,"command_resolution","commandResolution"))??bt({ok:a,errorCode:i,errorCategory:r}),c=To(ye(e,"resolution_stage","resolutionStage"))??"execute";return{ok:a,error:s,exit_code:o,error_code:i,error_category:r,command_resolution:l,resolution_stage:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3e4a18e9-6c97-5b44-95bc-678c3e7bdbcc")}catch{}})();var Po="PM_CLI_PACKAGE_ROOT",Wr=Symbol("pm.deprecatedAliasInvocation"),Gt=new Map;for(let e of W){let t=e.alias.split(" ")[0],n=Gt.get(t)??[];n.push(e),Gt.set(t,n)}for(let e of Gt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function Td(){return Xo(import.meta.url,["../.."])}(typeof process.env[Po]!="string"||process.env[Po]?.trim().length===0)&&(process.env[Po]=Td());var Me=null,L=null,Wt=null;function Od(e){Me=e}function Rd(e){T=e}var rt=null,_e=null,T=new Map,Uo=250,Id=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),$d=new Set(["1","true","yes","on"]),Pd=We(()=>import("./chunks/register-setup-P3VLCTDY.js")),Dd=We(()=>import("./chunks/register-list-query-2FE6K7FQ.js")),Md=We(()=>import("./chunks/register-mutation-KZXQUZUH.js")),Nd=We(()=>import("./chunks/register-operations-BOCBWNKJ.js"));function zt(e){return b(e)}function Vr(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=>me(o)??o))];return n.length>0?n:void 0}function Fd(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=Y(t),a=new Set(o.map(d=>me(d)??d)),i=Vr(e),r=t.find(d=>y.commands.some(m=>m.name()===d)),s=r?y.commands.find(d=>d.name()===r):void 0,l=new Set([...y.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>me(m)).filter(m=>m!==void 0))),c=i?.filter(d=>{let m=me(d)??d;return a.has(m)?!1:l.has(m)||Hn(t,r,m,T)!==void 0});return c&&c.length>0?c:void 0}function Ld(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let a=n?.[0],i=a?me(a):void 0,r=e.find(p=>y.commands.some(u=>u.name()===p)),s=r?y.commands.find(p=>p.name()===r):void 0,l=i?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(i)):void 0,c=Hn(e,r,i,T),d=i?l?.isBoolean()===!0||c===!1?[i]:[i,"<value>"]:[],m=i?zt([...e,...d]):t;return m===t?void 0:m}function jd(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 a=e[o];a!=null&&(n[o]=a)}return n}function Ud(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,...jd(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Br(e,t,n){let o=qe(t),a=D(o),i=K(a),[r,s]=i===void 0?[]:a.slice(i,i+2),l=o.includes("--explain"),c=bi(o,e?.code,e?.recovery),d=c&&(r==="history-redact"||r==="history"&&s==="redact")?{...c,...c.attempted_command?{attempted_command:zt(o)}:{},...c.normalized_args?{normalized_args:[...o]}:{},...c.suggested_retry?{suggested_retry:zt(o)}:{},...c.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:c;if(d?.recovery_mode==="compact"&&!l)return{...e,recovery:d};let m=zt(o),p=Y(o),u=Fd(n,o,d),f=Ld(o,m,u,d),h=Ud({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:f,existingRecovery:d});return{...e,recovery:h}}async function lt(e){let t=L;L=null,await Ci(t,e);let n=Me;if(Me=null,!n){ft();return}let o=[],a=ga();try{await ki({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?a?.map(i=>i.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await ra(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:le(),affected:a}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{ft()}!n.globalOptions.json&&o.length>0&&_(`[pm] warning: afterCommand hook_warnings=${j(o)}`),n.profileEnabled&&o.length>0&&_(`profile:extensions hook_warnings=${j(o)}`)}async function Kr(){await Wa()}function Jr(e){return $d.has((process.env[e]??"").trim().toLowerCase())}function Yr(e){return Jr("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Id.has(Math.trunc(e))}async function Vt(e){return Yr(e.exit_code)?(await Kr(),Ya(e),!0):!1}async function Xr(e){let t=de(e.error),n=Gi(t);e.bootstrapGlobal.json?_(JSON.stringify(Hi(t,g.GENERIC_FAILURE),null,2)):_(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",a="runtime_failed";try{await Kr(),fn(e.error);let i=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=i.errorCategory,a=i.commandResolution,await Jt(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:a,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||_(`Failed to report error: ${de(i)}`)}try{await lt({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:a,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||_(`Failed to run error hooks: ${de(i)}`)}try{await ke()}catch(i){e.bootstrapGlobal.json||_(`Failed to flush error reporting: ${de(i)}`)}}var qd={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"},Do=new Map;function Mo(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Zr(e,t){return e.options.some(n=>n.long===t)}function Qr(e,t){return e.options.some(n=>n.short===t)}function No(e,t,n,o){let a=t.trim();if(!a)return;let i=n.length>0?n:`Runtime schema field (${t})`;if(a.startsWith("-")&&!a.startsWith("--")){if(Qr(e,a))return;if(o){e.option(`${a} <value>`,`${i} (repeatable)`,yn);return}e.option(`${a} <value>`,i);return}let r=a.startsWith("--")?a:`--${a}`;if(!Zr(e,r)){if(o){e.option(`${r} <value>`,`${i} (repeatable)`,yn);return}e.option(`${r} <value>`,i)}}async function es(e,t){let n=qd[e];if(!n)return[];let o=`${t}:${n}`,a=Do.get(o);if(a)return a;if(!await V(B(t)))return Do.set(o,[]),[];let i=await $(t),r=(pn(i.schema).command_to_fields.get(n)??[]).flatMap(s=>[s.cli_flag,...s.cli_aliases].map(l=>({long:`--${l}`,type:Mo(s.type),value_type:Mo(s.type)})));return Do.set(o,r),r}async function ts(e,t){let n=N(t),o=S(process.cwd(),n.path);if(!await V(B(o)))return;let a=_e?.key===zo(o)?_e.snapshot:null,i=a===null?await $(o):a.settings,r=pn(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 c=Z(e,l.path.split(" "));if(c)for(let d of r.command_to_fields.get(l.command)??[]){let m=d.description??"";No(c,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)No(c,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function qo(e,t,n,o,a){let i=x(n);if(!(i!=="create"&&i!=="update"))try{let r=a??await $(t),s=re(r,o);Sr(e,s,n)}catch{}}function Fo(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function ns(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Ho(e){return e.some(t=>t==="--profile")}function zo(e){return`pm-root:${e}`}function Lo(e){for(let t of e)t.startsWith("settings_read_")&&_(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function os(e,t){e.profile&&(_(`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&&_(`profile:extensions activation_warnings=${j(t.activationWarnings)}`))}function Bt(e,t,n){if(!e)return;let o=w(n.commandPath??"")||"<none>";_(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function Kt(e,t=Ce){let n=zo(e);if(_e?.key===n)return _e.snapshot;try{let o=Date.now(),{settings:a,warnings:i}=await t(e),r=await sa({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:a,discovery:r,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return _e={key:n,snapshot:s},s}catch{return _e={key:n,snapshot:null},null}}async function Ne(e,t,n=$){let o=t?nt(t):"all",a=ns(e,o);if(rt?.key===a)return rt.snapshot;try{let i=await n(e),r=await je({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?uo(t):void 0}),s=await Ue({...r,loaded:r.loaded}),l=[...new Set(s.commands.handlers.map(u=>w(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),c=er(s.registrations.flags),d=Zi(s.commands.handlers,s.registrations.commands),m=nr(l,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:i,commandHandlers:l,commandFlagHelp:c,commandDescriptors:m,commandAliases:d,loadWarnings:[...r.warnings],activationWarnings:[...s.warnings],loadedCount:r.loaded.length,loadFailedCount:r.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:r.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return rt={key:a,snapshot:p},p}catch{return rt={key:a,snapshot:null},null}}async function as(e){let t=Ve(e);if(t.noExtensions){let r=S(process.cwd(),t.path);return await V(B(r))&&Lo((await Ce(r)).warnings),null}let n=S(process.cwd(),t.path),o=await Kt(n);if(!o)return null;Lo(o.settingsReadWarnings);let a={commandPath:E(e),commandArgs:fo(e)};if(!tt(o.discovery,a))return Bt(t.profile,o,a),null;let i=await Ne(n,a);return i?(os(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 Go(e){let t=await Ne(e);return t?new Map(t.commandDescriptors):T}async function Hd(e,t){return!e.requested||t.noExtensions||Ae(y,e.commandPathTokens)?T:Go(S(process.cwd(),t.path))}async function is(e,t){return(await Ma({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function rs(e,t,n){let o=t.author;return Da(e,ui.forActiveExtensionHost({pmRoot:e,author:o}),o,w(n))}async function ss(e,t,n,o=[]){let a=E(e),i=eo(e.args.map(String),o),r={...t};delete r.author;let s={...n},l=S(process.cwd(),n.path),c=await gt({command:a,args:i,options:r,global:s,pm_root:l});n.profile&&c.warnings.length>0&&_(`profile:extensions parser_warnings=${j(c.warnings)}`),i=c.context.args,r=c.context.options,s=c.context.global,wo(T.get(w(a)),i,r,o),ve(void 0),ut({command:a,args:i,options:{...r},global:{...s},pm_root:l});let d=await on({command:a,args:i,options:r,global:s,pm_root:l,sdk:rs(l,s,a)});if(s.profile&&d.warnings.length>0&&_(`profile:extensions command_handler_warnings=${j(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new C(`Command "${a}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new C(`Command "${a}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ve(d.result),d.result}var Lr=Symbol("pm.wrappedActionHandler");function zd(e,t){let n=e[e.length-1];return n instanceof jo?n:t}function jr(e,t,n){e&&n.length>0&&_(`profile:extensions ${t}=${j(n)}`)}function Gd(e){let t=T.get(w(e.commandPath));if(!t||!yo(e.activeRegistrations,e.commandPath))return;let n=Ut(t).length===0?wr(e.commandArgs):eo(e.commandArgs,e.extensionFlagDefinitions);_o(t,n)}function Wd(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 ls(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[Lr]!==!0){let a=o._actionHandler;o._actionHandler=async function(...i){let r=zd(i,n),s=Date.now();hn(r);let l=Ve(r),c=I(E(r));if(["package inventory","packages inventory","extension inventory"].includes(c))return await a.apply(this,i);let d=S(process.cwd(),l.path),m=r.args.map(String),p=se(),u=p?ot(p,c,m):[],f=await es(c,d),h=De(r,m,[...u,...f]);T.has(w(c))&&delete h.author;let v=await gt({command:c,args:m,options:h,global:l,pm_root:d});jr(l.profile,"parser_warnings",v.warnings),m=v.context.args,h=v.context.options,ie(r,h),l=v.context.global,Gd({activeRegistrations:p,commandPath:c,commandArgs:m,extensionFlagDefinitions:u}),l=await oi(l),kt(r,l),Wd(r,i,m),Ct(r,h),ve(void 0),ut({command:c,args:m,options:{...h},global:{...l},pm_root:d});let P=await on({command:c,args:m,options:h,global:l,pm_root:d,sdk:rs(d,l,c)});if(jr(l.profile,"command_handler_warnings",P.warnings),P.handled){ve(P.result),rn(P.result,{...l,command:c,commandArgs:m,commandOptions:h,pmRoot:d}),l.profile&&_(`profile:command=${c} took_ms=${Date.now()-s}`);return}return await a.apply(this,i)},o[Lr]=!0}for(let a of n.commands)t(a)};t(e)}async function Ht(e){T=new Map,te({overrides:[]}),e&&await qo(e.rootProgram,e.pmRoot,e.invocationArgv,oa(),e.settings)}function Vd(e,t,n,o){if(t?.flags&&t.flags.length>0){Gn(e,t.flags);let a=Wn(e,t.flags);a&&e.addHelpText("after",a)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function cs(e,t,n){let o={core:0,standard:1,full:2,internal:3},a=(i,r)=>{let s=r.join(" "),l=[...n.entries()].filter(([d])=>d===s||d.startsWith(`${s} `)).map(([,d])=>d),c=l.length===0?"standard":l.reduce((d,m)=>o[m.tier]<o[d]?m.tier:d,"internal");St(i,c);for(let d of i.commands)a(d,[...r,d.name()])};for(let i of e.commands)t.has(i.name())||a(i,[i.name()])}async function ds(e,t){let n=N(t),o=S(process.cwd(),n.path);if(n.noExtensions){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t});return}let a=await Kt(o),i=Pe(t);if(!a){await Ht();return}if(!tt(a.discovery,i)){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings}),Bt(Ho(t),a,i);return}let r=await Ne(o,i);if(!r){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings});return}te(r.services),T=new Map(r.commandDescriptors),await qo(e,o,t,r.registrations,r.settings);let s=dr(e,r.commandHandlers,r.commandDescriptors,r.commandAliases,d=>mr(r.activationWarnings,_,d)),l=new Set(e.commands.map(d=>d.name())),c=d=>{let m=d.split(" ").filter(z=>z.length>0),p=r.commandDescriptors.get(d),u=Z(e,m),f=r.commandFlagHelp.get(d),h=p?lr(p):null;if(u){Vd(u,p,f,h);return}let v=cr(e,m);p?.description&&v.description(p.description);let P=f;p&&(or(v,p),p.flags.length>0&&(Gn(v,p.flags),P=Wn(v,p.flags)??void 0)),P&&v.addHelpText("after",P),h&&v.addHelpText("after",h),v.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...z)=>{let Q=z[z.length-1],G=Q instanceof jo?Q:v,ct=Ve(G),Cs=Date.now(),Bo=ot(r.registrations,d,G.args.map(String)),Ko=De(G,G.args.map(String),Bo),Jo=await ss(G,Ko,ct,Bo);await ai(ct,Jo),rn(Jo,{...ct,command:d,commandArgs:G.args.map(String),commandOptions:Ko,pmRoot:o}),ct.profile&&_(`profile:command=${d} took_ms=${Date.now()-Cs}`)})};for(let d of s)c(d);cs(e,l,r.commandDescriptors)}var st=Zo(import.meta.url,["../.."])??"0.0.0",y=sn(st);async function Ur(e){if(!L)return;let t=Reflect.get(e,Wr);typeof t=="string"&&await pi(t)}async function qr(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function Hr(e,t,n){!L||!await un(!0)||(Va(e,t,n,{source_context:L.source_context,source_context_source:L.source_context_source}),Ba(e),Wt=L)}async function Jt(e,t,n){let o=Wt;if(!o)return;Wt=null;let a=!1;try{let i=await $(o.global_pm_root);a=i.telemetry.enabled&&i.telemetry.installation_id===o.installation_id}catch{}await un(a)?Ja(e,t,n):Ka()}async function Bd(e){let t=await as(e);return nn(t?.registrations??null),t}function ms(e,t){t&&at(t)||(e.hook("preAction",async(n,o)=>{Me=null,L=null,Wt=null,ft(),hn(o);let a=o.optsWithGlobals(),i=Ve(o),r=I(E(o)),s=o.args.map(String),l=De(o,s),c={...i},d=S(process.cwd(),i.path),m=await Bd(o);if(ba(r,{...l,outputInclude:a.outputInclude,outputLimit:a.outputLimit,outputBudget:a.outputBudget,outputFormat:a.outputFormat,outputSession:a.outputSession,outputCursor:a.outputCursor}),ho(o,r,c,l),await qr(o,void 0,()=>ei(r,c)),!m){Me=la({commandName:r,commandArgs:s,commandOptions:l,globalOptions:c,pmRoot:d}),L=await gn({command:r,pm_version:st,args:s,options:l,global:c,pm_root:d}),await Ur(e),await Hr(r,s,l),await ao(r,l,d,Fo()),await oo(r,s,l,c,d);return}ca(m.hooks),da(m.commands),ma(m.parsers),pa(m.preflight),te(m.services),ua(m.renderers),nn(m.registrations);let p=ot(m.registrations,r,s);l=De(o,s,p),ho(o,r,c,l);let u=await gt({command:r,args:s,options:l,global:c,pm_root:m.pmRoot});c.profile&&u.warnings.length>0&&_(`profile:extensions parser_warnings=${j(u.warnings)}`),s=u.context.args,l=u.context.options,ie(o,l),c=u.context.global,Ct(o,l);let f=await ha({command:r,args:s,options:l,global:c,pm_root:m.pmRoot,decision:Fo()});c.profile&&f.warnings.length>0&&_(`profile:extensions preflight_warnings=${j(f.warnings)}`),s=f.context.args,l=f.context.options,ie(o,l),c=f.context.global,Ct(o,l);let h=f.decision;await ao(r,l,m.pmRoot,h),await oo(r,s,l,c,m.pmRoot);let v=h.run_extension_migrations?await qr(o,[],()=>is(m.registrations.migrations,m.pmRoot)):[];c.profile&&v.length>0&&_(`profile:extensions migration_warnings=${j(v)}`);let P=Or(m.registrations.migrations);Me={hooks:m.hooks,commandName:r,commandArgs:s,commandOptions:{...l},globalOptions:{...c},pmRoot:m.pmRoot,profileEnabled:!!c.profile,migrationBlockers:P},ve(void 0),ut({command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot}),L=await gn({command:r,pm_version:st,args:s,options:l,global:c,pm_root:m.pmRoot}),await Ur(e),await Hr(r,s,l);let z=await ia(m.hooks,{command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot});c.profile&&z.length>0&&_(`profile:extensions hook_warnings=${j(z)}`),h.enforce_mandatory_migration_gate&&Rr(r,l,P)}),e.hook("postAction",async()=>{let n=$o();await Jt(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await lt(n),await ke()}))}ms(y);var zr=Symbol("pmCliIdempotentTopLevelRegistration");function ps(e){let t=e;if(t[zr])return;t[zr]=!0;let n=e.command.bind(e);e.command=((o,...a)=>{let i=o.split(/\s+/u)[0];return e.commands.some(r=>r.name()===i||r.aliases().includes(i))?new jo(i):n(o,...a)})}async function Kd(e,t){if(ps(e),t.setup){let{registerSetupCommands:n}=await Pd();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Dd(),o=typeof t.targetCommandName=="string"&&vo.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Md();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Nd();n(e)}}function Jd(e){return async t=>{let n=dt(t.errorCode),o=bt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await ni({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:st,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 us(e){if(e.bootstrapGlobal.noExtensions||at(e.invocationArgv))return;let t=Pe(e.invocationArgv),n=await Kt(e.bootstrapPmRoot);if(n&&tt(n.discovery,t)){let o=await Ne(e.bootstrapPmRoot,t);fs(o);return}n&&Bt(Ho(e.invocationArgv),n,t),te({overrides:[]})}function fs(e){if(!e){te({overrides:[]});return}te(e.services)}async function Wo(e){await Jt(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await lt({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 gs(){await Jt(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await lt({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function hs(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof C)&&(dn(e.error)||!n))return!1;let o=de(e.error),a=e.error instanceof C?e.error.exitCode:cn(t),i=e.error instanceof C?e.error.context:void 0,r=Br(i,e.invocationArgv,o),s=Ui(o,r),l=e.bootstrapGlobal.lean?Ot(Dn(o,a,r)):Dn(o,a,r),c=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?ce(l,u=>`${JSON.stringify(u,null,2)}
34
+ `):l,null,2):ji(o,r);e.jsonErrors?be(`${c}
35
+ `):_(c);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:a,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Vt({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:a,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:L?.source_context});return await Wo({errorMessage:o,exitCode:a,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(fn(mn(e.error,o)),await ke(Uo)),process.exitCode=a,!0}async function ys(e,t){let n=A(e.invocationArgv).commandPathTokens.join(" ")||Fn(e.invocationArgv),o=I(n),a=`unknown command '${n}'`,i=S(process.cwd(),e.bootstrapGlobal.path),r=e.bootstrapGlobal.noExtensions?T:await Go(i),s=Pe(e.invocationArgv),l=e.bootstrapGlobal.noExtensions?[]:await to(i,{},$e(s)),c=await Je({message:a},y,r,{failedExtensions:l},e.invocationArgv),d=Mn(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:l}),{errorCategory:m,commandResolution:p}=await e.emitTelemetryCommandError({command:o,errorCode:d.code,errorMessage:d.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),u=await Vt({command:o,error_code:d.code,error_category:m,exit_code:g.USAGE,error_message:d.detail,command_resolution:p,resolution_stage:"parse"}),f=e.jsonErrors?await qn({message:a},y,r,e.bootstrapGlobal.lean===!0,{failedExtensions:l},e.invocationArgv):await Un({message:a},y,r,{failedExtensions:l},e.invocationArgv),h=Nn(f,e.jsonErrors,l);await Wo({errorMessage:a,exitCode:g.USAGE,classificationCode:d.code,errorCategory:m,commandResolution:p,resolutionStage:"parse"}),e.jsonErrors?be(`${h}
36
+ `):_(h),u&&await ke(Uo),process.exitCode=g.USAGE}async function _s(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let o=A(e.invocationArgv);return o.requested&&!Ae(y,o.commandPathTokens)?(await ys(e,t),!0):(await gs(),!0)}async function ws(e,t){let n=await Je(e.error,y,T,{},e.invocationArgv),o=Mn(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:a,commandResolution:i}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),r=await Vt({command:e.attemptedCommand,error_code:o.code,error_category:a,exit_code:g.USAGE,error_message:o.detail,command_resolution:i,resolution_stage:"parse",source_context:L?.source_context}),s=e.jsonErrors?await qn(e.error,y,T,e.bootstrapGlobal.lean===!0,{},e.invocationArgv):await Un(e.error,y,T,{},e.invocationArgv),l=await vr(o.code,e.bootstrapPmRoot,{},$e(Pe(e.invocationArgv))),c=Nn(s,e.jsonErrors,l);await Wo({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:a,commandResolution:i,resolutionStage:"parse"}),e.jsonErrors?be(`${c}
37
+ `):_(c),r&&await ke(Uo),process.exitCode=g.USAGE}function vs(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 bs(e){let t=e.error.code,n=String(e.error.message??"");if(!await _s(e,t,n)){if(t==="commander.version"){await gs();return}await ws(e,t)}}async function Vo(e){let t=N(e.invocationArgv),n=S(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:x(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:Jd({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await us({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await hs(o,ln(e.error))){if(vs(e.error)){await bs(o);return}await Xr({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}function Yd(e,t,n){let o=n.requested?n.commandPathTokens:D(t),a=q(o);if(a&&!Z(e,[...a.canonical_argv]))throw new Gr(g.USAGE,"commander.unknownCommand",`unknown command '${a.alias}'`)}function Xd(e,t){let n=K(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let r=K(t.slice(n+1));if(r===void 0)return;n+=r+1}let o=Gt.get(t[n]),a=t.slice(n).filter(r=>!["--global","--project","--local"].includes(r)),i=o?.find(r=>r.alias.split(" ").every((s,l)=>a[l]===s));i?.lifecycle==="deprecated"&&Reflect.set(e,Wr,i.alias)}function Zd(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function Qd(e,t){y=sn(st),y.hook("preAction",(i,r)=>{t.configurationOnly=["item mutate","item complete"].includes(E(r))&&r.optsWithGlobals().dryRun===!0}),ms(y,e),rt=null,_e=null,T=new Map,fa();let n=[...e],o,a;try{let i=Ge(e);n=i.argv,Xd(y,e);let r=Zd(n),s=n.length===0,l=N(n);if(l.authorMissingValue)throw new C("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=Ha(l.author),Eo(i),a=Fa(n);let c=bo(n);await Kd(y,c),xn(y,!0),ko(y,n)?await ds(y,n):(T=new Map,te({overrides:[]})),xo(n)&&await ts(y,n),xn(y);let d=A(n);Yd(y,n,d),Co(n)&&Oi(y,n),ls(y);let m=await Hd(d,l);if(await Er(y,n,m,e))return;if(d.requested&&!Ae(y,d.commandPathTokens))throw new Gr(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||oe(n)&&x(n)===void 0){y.outputHelp();return}if(at(n)){await y.parseAsync(r);return}let p=S(process.cwd(),l.path),u=await $(p),f=await Yi(n,p,l.noExtensions,Ne);await Aa({pmRoot:p,packages:f?.contextIntentPackages},()=>Ta({env:{...process.env,PM_PATH:p},argv:r,cwd:process.cwd()},()=>Oa(u.agent_identity.harness_signals,()=>y.parseAsync(r),{probesEnabled:u.agent_identity?.probes_enabled})))}catch(i){await Vo({error:i,invocationArgv:n})}finally{a?.(),o?.()}}async function Su(e=process.argv.slice(2)){let t=e;try{t=Ge(e).argv}catch{}let n=Nr(t),o={configurationOnly:n!==void 0},a=()=>o.configurationOnly,i=async()=>{try{await za(process.env,()=>Qd(e,o))}catch(r){await Vo({error:r,invocationArgv:[...e]})}};if(n!==void 0){let r=S(process.cwd(),N(t).path),s=S(process.cwd(),n.path),l=na(process.cwd());await yt(r,()=>yt(s,()=>yt(l,i,a),a),a)}else await i()}var Au={activationCommandMatchesProbe:ro,applyDynamicExtensionRootHelpVisibility:cs,bootstrapProfileEnabled:Ho,buildBootstrapActivationProbe:Pe,buildPostActionTelemetryOutcome:$o,buildPmCliRecoveryContext:Br,buildRuntimeExtensionDiscoverySnapshotCacheKey:zo,buildRuntimeExtensionActivationScope:nt,buildRuntimeExtensionSnapshotCacheKey:ns,buildRuntimeExtensionFilterForProbe:uo,addRuntimeFieldOption:No,collectActivationCommandCandidates:$e,collectExtensionFlagDefinitionsForCommand:jt,collectExtensionFlagDefinitionsForInvocation:ot,collectLeadingCommandArgs:io,collectParsedActivationCommandArgs:fo,collectRuntimeFieldLooseFlagDefinitionsForCommand:es,commandHasLongOption:Zr,commandHasShortOption:Qr,commandPathNeedsSearchExtensions:so,commandPathNeedsTemplateExtensions:Nt,describeUnknownError:de,defaultPreflightDecision:Fo,discoveryNeedsActivationForProbe:tt,emitExtensionProfile:os,emitExtensionSkippedProfile:Bt,emitSettingsReadWarnings:Lo,ensureIdempotentTopLevelCommandRegistration:ps,enforceExplicitRetryForFlagTypos:Eo,envFlagEnabled:Jr,executeRegisteredRuntimeMigrations:is,extractCommandScopedOptions:De,extensionActivationCommands:Mt,extensionCapabilities:et,extensionNeedsActivationForProbe:Ft,extensionProvidesTemplatesRuntime:co,hasAnyCapability:Ie,hasGlobalExtensionContributions:mo,handleGenericRunPmCliError:Xr,handleRunPmCliCommanderError:bs,handleRunPmCliError:Vo,handleRunPmCliHelpDisplayError:_s,handleRunPmCliKnownError:hs,handleRunPmCliCommanderUsageError:ws,handleUnknownHelpCommandError:ys,inferMissingFieldsFromErrorMessage:Vr,inferPostActionErrorCode:Io,inferPostActionFailureMessage:Ro,invocationRequestsVersion:it,isCommanderError:dn,loadRuntimeExtensionCommandDescriptorsForRecovery:Go,loadRuntimeExtensionDiscoverySnapshot:Kt,loadRuntimeExtensionSnapshot:Ne,maybeLoadRuntimeExtensions:as,maybeAttachCreateUpdatePolicyHelpText:qo,maybeLogHandledCliErrorToSentry:Vt,matchesStaticExtensionCommand:Dt,normalizeTelemetryCommandResolution:Ao,normalizeTelemetryErrorCategory:Oo,normalizeTelemetryResolutionStage:To,normalizeThrownExitCode:cn,probeUsesAnyFlag:lo,prepareExtensionServicesForRunPmCliError:us,readRecordBoolean:So,readRecordNumber:qt,readRecordString:ye,recordCliReadOutputInvocationProvenance:go,registerDynamicExtensionCommandPaths:ds,registerRuntimeSchemaFieldFlags:ts,resolveCoreCommandRegistrationSelection:bo,resolveStaticExtensionActivationDecision:po,resolveUnknownHelpToken:Fn,readThrownExitCode:ln,runAndClearAfterCommandHooks:lt,runRequiredExtensionCommand:ss,shouldAttachRichHelpTextForInvocation:Co,shouldLogHandledErrorToSentry:Yr,shouldRegisterDynamicExtensionPaths:ko,shouldRegisterRuntimeSchemaFlags:xo,shouldHandleRunPmCliCommanderError:vs,setActiveExtensionHookContextForTest:Od,setActiveRuntimeExtensionCommandDescriptorsForTest:Rd,setRecoveredExtensionServices:fs,toLooseFieldDefinitionType:Mo,isImporterOrExporterCommandPath:yo,validateDynamicExtensionCommandInvocation:wo,wrapProgramActionsForExtensionHandlers:ls,wrapThrownErrorForSentry:mn};export{Au as _testOnly,Su as runPmCli};
38
38
  //# sourceMappingURL=main.js.map