@unbrained/pm-cli 2026.10.3 → 2026.10.4

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 (98) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +17 -2
  3. package/dist/cli/error-guidance.js +1 -1
  4. package/dist/cli/runtime/invocation-options.js +1 -1
  5. package/dist/cli/runtime/selection.js +1 -1
  6. package/dist/cli/runtime-compatibility-boundary.d.ts +1 -1
  7. package/dist/cli/runtime-compatibility-boundary.js +3 -3
  8. package/dist/cli-bundle/bundle-manifest.json +154 -154
  9. package/dist/cli-bundle/chunks/{chunk-YCBGZF3T.js → chunk-7CE2DJMA.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-6ST3SCQ6.js → chunk-7UVXKI7K.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-H2DZW6I6.js → chunk-D7Z2ZMJL.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-44UGMMQ6.js → chunk-GZMWISWW.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-KP7NBQK3.js → chunk-J52QIRRZ.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-3AF2R3Y6.js → chunk-JDKD3WGG.js} +6 -6
  15. package/dist/cli-bundle/chunks/chunk-JQ7DW663.js +2 -0
  16. package/dist/cli-bundle/chunks/{chunk-MKXBCBAN.js → chunk-QXIDOOWT.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-5XKF5SQV.js → chunk-SMKHR6BM.js} +49 -49
  18. package/dist/cli-bundle/chunks/{chunk-FW5LJXQY.js → chunk-V3U77H3V.js} +28 -28
  19. package/dist/cli-bundle/chunks/{chunk-YDWKGUQU.js → chunk-XZDWAYJC.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-QPKQKSQU.js → chunk-Y6VRBTP3.js} +71 -71
  21. package/dist/cli-bundle/chunks/{chunk-6Z4IV2MC.js → chunk-YAAFYFS4.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-list-query-DYCGUQEW.js → register-list-query-QBGXO5JJ.js} +2 -2
  23. package/dist/cli-bundle/chunks/{register-mutation-5PT3NW3A.js → register-mutation-53ZLT4RX.js} +2 -2
  24. package/dist/cli-bundle/chunks/{register-operations-QDDQOAAV.js → register-operations-OBK2FXUU.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-setup-BBX67YMA.js → register-setup-HM3OCBH2.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-FKK2HI3S.js → chunk-2JFYR56O.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-UTRSM3ZK.js → chunk-32EVUSS4.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-DBD4W4QP.js → chunk-467EW5RL.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-WAJNX4RN.js → chunk-5GUSO2P4.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-GMYUNHST.js → chunk-6XBRADQQ.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-EJN7DY3B.js → chunk-7O4NUJVO.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-E754JDLY.js → chunk-CURTIIQT.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-4FFPGNCJ.js → chunk-IJUWEEEB.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-XRSCIYHR.js → chunk-JCVMOSWQ.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-ZIXFMIUL.js → chunk-JMJK2L4Z.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-WCY6HRZO.js → chunk-KG3H4UZZ.js} +14 -14
  37. package/dist/cli-bundle/focused-chunks/{chunk-VVWYI2X7.js → chunk-MHQ2XICU.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-3BIYG72P.js → chunk-Q6DJ5DFQ.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-73DA7ISY.js → chunk-RJV6QVJE.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-HIA2ZF64.js → chunk-ZE2JZ7R6.js} +11 -11
  41. package/dist/cli-bundle/focused-chunks/chunk-ZLEN4HZD.js +165 -0
  42. package/dist/cli-bundle/main.js +22 -22
  43. package/dist/cli-bundle/sdk-authoring.js +1 -1
  44. package/dist/cli-bundle/sdk-contracts.js +1 -1
  45. package/dist/cli-bundle/sdk-core.js +22 -22
  46. package/dist/cli-bundle/sdk-governance.js +1 -1
  47. package/dist/cli-bundle/sdk-graph.js +1 -1
  48. package/dist/cli-bundle/sdk-merge.js +11 -11
  49. package/dist/cli-bundle/sdk-query.js +1 -1
  50. package/dist/cli-bundle/sdk-runtime.js +1 -1
  51. package/dist/cli-bundle/sdk-testing.js +1 -1
  52. package/dist/cli-bundle/sdk.js +1 -1
  53. package/dist/core/extensions/extension-types.d.ts +8 -1
  54. package/dist/core/extensions/extension-types.js +1 -1
  55. package/dist/core/shared/time.js +1 -1
  56. package/dist/core/store/settings.d.ts +11 -2
  57. package/dist/core/store/settings.js +2 -2
  58. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  59. package/dist/sdk/cli-bootstrap.js +1 -1
  60. package/dist/sdk/context-intent-contracts.js +1 -1
  61. package/dist/sdk/extension-command-context.js +1 -1
  62. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  63. package/dist/sdk/item-transaction.js +1 -1
  64. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  65. package/dist/sdk/lifecycle/task-composition.js +1 -1
  66. package/dist/sdk/output-projection.js +1 -1
  67. package/dist/sdk/public-surface.json +1 -1
  68. package/dist/sdk/query/get.js +1 -1
  69. package/dist/sdk/query/search-pagination.d.ts +1 -1
  70. package/dist/sdk/query/search-pagination.js +1 -1
  71. package/dist/sdk/test/workspace-snapshot.js +1 -1
  72. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +25 -0
  73. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
  74. package/docs/SDK_AUDITED_MUTATIONS.md +35 -0
  75. package/docs/TESTING.md +8 -0
  76. package/docs/ecosystem-review-2026-09-28.json +2864 -3157
  77. package/marketplace.json +2 -2
  78. package/package.json +1 -1
  79. package/packages/pm-beads/package.json +1 -1
  80. package/packages/pm-calendar/package.json +1 -1
  81. package/packages/pm-command-kit/package.json +1 -1
  82. package/packages/pm-digital-twin/package.json +1 -1
  83. package/packages/pm-governance-audit/package.json +1 -1
  84. package/packages/pm-guide-shell/package.json +1 -1
  85. package/packages/pm-kanban/package.json +1 -1
  86. package/packages/pm-lifecycle-hooks/package.json +1 -1
  87. package/packages/pm-linked-test-adapters/package.json +1 -1
  88. package/packages/pm-search-advanced/package.json +1 -1
  89. package/packages/pm-templates/package.json +1 -1
  90. package/packages/pm-todos/package.json +1 -1
  91. package/packages/pm-vcs/package.json +1 -1
  92. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  93. package/plugins/pm-claude/package.json +2 -2
  94. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  95. package/plugins/pm-codex/package.json +2 -2
  96. package/plugins/pm-codex/plugin.json +1 -1
  97. package/dist/cli-bundle/chunks/chunk-H7CXQBGQ.js +0 -2
  98. package/dist/cli-bundle/focused-chunks/chunk-YC32ZSLS.js +0 -165
@@ -1,10 +1,10 @@
1
- import{B as er,D as tr,E as _n,a as an,b as ce,c as sn,d as ln,e as cn,f as dn,i as U,j as D,k as A,l as de,m as x,n as Oi,s as qe,t as Ri,u as Ni,y as Di,z as wn}from"./chunks/chunk-H7CXQBGQ.js";import{Wa as Qi,f as vi,l as Si}from"./chunks/chunk-5XKF5SQV.js";import"./chunks/chunk-YDWKGUQU.js";import"./chunks/chunk-3AF2R3Y6.js";import{F as Vi,Id as Zi,Nc as Xi,d as bt,g as Gi,h as Wi,i as Y,j as Bi}from"./chunks/chunk-FW5LJXQY.js";import{Ga as Ki,g as Ai}from"./chunks/chunk-KP7NBQK3.js";import"./chunks/chunk-MKXBCBAN.js";import"./chunks/chunk-DEZPZOQ7.js";import{$a as Bo,$g as bi,Ac as ne,Bc as ri,Cc as ai,Ce as mi,Dc as ae,De as on,Ec as si,En as Ge,Fc as mt,Gb as Ko,Gc as ve,Hc as se,Hn as Ui,I as Ho,If as le,J as zo,Jf as _i,Kc as li,Kf as be,Kn as qi,Lc as pt,M as De,Mf as rn,Nf as _,No as Ct,Oo as xt,Pb as Jo,Pn as gn,Po as hn,Q as Zt,Qb as Yo,Qn as Hi,Qo as We,Ra as Qt,Rc as nn,Rn as zi,Ro as E,Sc as ut,So as Ji,Tc as ci,Te as pi,To as yn,Ua as re,Uc as di,Ue as ui,Ve as fi,Wa as Wo,Wb as Xo,We as gi,Xa as dt,Xe as hi,Xi as yt,Yb as Zo,Yi as Ei,Zo as q,_a as en,ab as R,ae as ft,ah as Ci,cb as Vo,cd as k,db as J,dd as Le,e as F,fl as Ti,g as W,gl as xe,gn as Mi,h as O,hn as vt,ih as gt,il as Ii,in as pn,j as B,jc as Qo,jl as Pi,jn as un,k as Xt,kc as Me,ki as ht,kj as wt,kn as He,l as V,ll as $i,ln as fn,lp as Yi,m as qo,mc as Fe,mg as mn,mi as xi,mj as je,mn as Fi,na as f,nc as ei,nj as _t,nn as ze,oa as ct,oi as Ce,pa as C,pi as N,qa as Go,qi as ki,qn as Li,rn as ji,sf as yi,vb as tn,wc as ti,wf as wi,x as K,xc as ni,yc as oi,zc as ii,zj as Ue}from"./chunks/chunk-QPKQKSQU.js";import{Command as No,CommanderError as Ca}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]="0429ff6a-ec0d-5c20-9fa7-0ed05b154523")}catch{}})();function H(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 H(t)}function X(e){let t=new Set,n=[];for(let o of e){let i=me(o);i&&(t.has(i)||n.push(i),t.add(i))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bdbd1281-8294-5bda-8053-f9fff4c34bf3")}catch{}})();var vn=new Set(["--fields","--depth","--for","--token-budget"]),kt=new Set(["--full","--brief","--compact"]);function ts(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 ns(e){let t=xe(x([...e])),n=new Set([...Ii,...Pi,...$i].flatMap(a=>a.keys.map(s=>`--${s.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),o=new Map([...Ue,...t].flatMap(a=>[a.flag,...a.aliases??[]].map(s=>[s,a.flag]))),i=new Map([...Ue,...t].flatMap(a=>[a.flag,...a.aliases??[]].map(s=>[s,ts(a,n)])));for(let a of vn)i.set(a,!0);for(let a of kt)i.set(a,!1);let r=new Map;for(let a=0;a<e.length;a+=1){let s=e[a];if(s==="--")break;if(!s.startsWith("-"))continue;let l=s.split("=")[0];if(!i.has(l)&&!s.includes("="))return;r.set(a,o.get(l)??l),i.get(l)&&!s.includes("=")&&(a+=1)}return r}function nr(e,t,n){let o=new Set;for(let[i,r]of t)n.has(r)&&(o.add(i),vn.has(r)&&!e[i].includes("=")&&o.add(i+1));return e.filter((i,r)=>!o.has(r))}function or(e,t,n){return e.splice(n,0,...t),e}function os(e,t){let n=t.find(i=>kt.has(i));if(n===void 0)return;let o=[...new Set(e.values())].filter(i=>kt.has(i));return o.length===1?o[0]:n}function ir(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,i={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return i;let r=ns(e);if(!r)return i;let a;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return i;let l=[...r].find(([c,d])=>d==="--fields")?.[0]??-1;if(l<0)return i;a=or(nr(e,r,new Set(["--fields"])),["--fields",o[s+1]],l)}else{let s=os(r,o);if(s===void 0)return i;let l=new Set([...vn,...kt]),c=[...r].find(([d,m])=>l.has(m))?.[0]??-1;if(c<0)return i;a=or(nr(e,r,l),[s],c)}return{...n,suggested_retry:k(a),suggested_retry_args: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]="1c4a4bc4-d26a-5f51-bac0-2a132dad1f56")}catch{}})();async function rr(e,t){await Hi(e,{ok:t.ok,error:t.error,result:se(),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 ar(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await yi({pmRoot:e.pmRoot,result:se()})}catch(o){t=o}let n=await N(e.pmRoot);if(await wi({pmRoot:e.pmRoot,author:gt(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]="63db65f1-fdbe-513d-b71a-87490ec9b69e")}catch{}})();var sr=new WeakMap;function Et(e,t){sr.set(e,t)}function pe(e){return sr.get(e)}function lr(e){return e.length>0?[e[0]]:[]}function is(e){let t=["","Intent:",` ${e.why}`],n=lr(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 rs(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 cr(e,t){return t==="detailed"?rs(e):is(e)}function M(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var as={cal:"calendar",ctx:"context"};function ss(e,t){return e.commands.find(n=>n.name()===t)??null}function ls(e,t){let n=e;for(let o of t){let i=ss(n,o);if(!i)return null;n=i}return n}function bn(e,t,n,o){let i=ls(e,t.split(" ").filter(r=>r.length>0));i&&i.addHelpText("after",cr(n,o))}function Cn(e){return e.includes("--explain")?"detailed":"compact"}function oe(e){return e.includes("--all")||e.includes("--explain")}var ue={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 install ./my-package --project","pm install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm extension catalog --project","pm extension catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list-all --limit 50","pm list-all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-in-progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list-blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' 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" --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 takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause"]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of F){let n=ue[e];n&&(ue[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var ke={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},dr=B.filter(e=>e.lifecycle==="deprecated");for(let e of dr){let t=ue[e.alias];ue[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[ke,...Object.values(ue)])e.examples=e.examples.map(t=>{for(let n of dr){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function cs(e){let t=M(e??"");return t?as[t]??t:""}function xn(e){let t=cs(e);return t?ue[t]??ke:ke}function mr(e,t){let n=xn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:lr(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function ds(){let e=B.filter(({lifecycle:n})=>n==="permanent"),t=B.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(" ")} (${qo(n)})`)].join(`
4
- `)}function ms(e,t,n,o){let i=new Set(Gi);e.configureHelp({visibleCommands(r){let a=t.visibleCommands(r);return n?a.filter(s=>(pe(s)??Y(s.name()))!=="internal"):r!==e?a:a.filter(s=>o.has(s))},visibleOptions(r){let a=t.visibleOptions(r);return r!==e||n?a:a.filter(s=>i.has(s.flags))}})}function ps(e,t,n,o){let i=new Set(Bi("core")),r=e.createHelp();r.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let a=()=>`${r.formatHelp(e,r)}${o}
5
- `,s=t.visibleCommands(e);for(let l of s)pe(l)===void 0&&(l.name()==="help"||i.has(l.name()))&&n.add(l);for(let l of s)pe(l)==="core"&&(n.add(l),Wi(a()).within_budget||n.delete(l))}function pr(e,t=process.argv.slice(2)){let n=e.createHelp(),o=oe(t),i=new Set;ms(e,n,o,i);let r=Cn(t),a=cr(ke,r);e.addHelpText("after",a),o&&e.addHelpText("after",ds()),ps(e,n,i,a);for(let[d,m]of Object.entries(ue))bn(e,d,m,r);let s=M(A(t).commandPathTokens.join(" ")),l=je(s);if(l){bn(e,l.parent,{why:l.description,examples:[l.example],tips:[`Action path: pm ${l.command}`,_t(l.accepted_flags)]},r);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.`]},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]="b70452a1-26dc-5f66-bb87-67a5bde7bd30")}catch{}})();function kn(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:i}of F){if(t&&!F.some(c=>c.canonical.startsWith(`${o} `)))continue;let r=e.commands.findIndex(c=>c.name()===n);if(r<0)continue;let a=e.commands[r],s=e;for(let c of i.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===c)??s.command(c).description(`Discover ${c} operations.`);let l=i[i.length-1];if(s.commands.some(c=>c.name()===l))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(r,1),a.name(l),Et(a,Y(o)),s.enablePositionalOptions(),s.addCommand(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]="f8d165fe-486f-57d6-8154-f379f5ad9780")}catch{}})();function Tt(e){let{why:t,title:n,...o}=e;return o}var us=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function fs(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!us.has(e.code)}function yr(e){return`urn:pm-cli:error:${e}`}function b(e){return{...e,type:yr(e.code)}}var Ee={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},ur={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},fr={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},St={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},gs={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:ur,cal:ur,reindex:fr,"search-advanced":fr,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":St,"dedupe-audit":St,"dedupe-merge":St,normalize:St};function hs(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return gs[t]}function En(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function ys(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 ws(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 Z(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let i=n.map(r=>({role:typeof r?.role=="string"?r.role.trim():"",value:typeof r?.value=="string"?r.value.trim():""})).filter(r=>r.role.length>0&&r.value.length>0);i.length>0&&(e.parsed_positionals=i);return}let o=ys(n);o&&(e[t]=o)}function Se(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Sn(t,"attempted_command",e.attempted_command),Z(t,"normalized_args",e.normalized_args),Z(t,"parsed_positionals",e.parsed_positionals),Z(t,"provided_fields",e.provided_fields),Z(t,"missing",e.missing),Z(t,"missing_required_fields",e.missing_required_fields),Z(t,"suggested_flags",e.suggested_flags),Z(t,"allowed_values",e.allowed_values),Z(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),Z(t,"suggested_retry_args",e.suggested_retry_args),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=ws(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 _s(e){let t=Se(e);if(!t)return[];let n=["Recovery bundle:"];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}`),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),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 wr(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=_s(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
6
- `)}function _r(e,t){return t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),fs(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=i=>{let r=i.split("=",1)[0];return D([r]).length>0&&!["--help","--no-changed-fields","--version"].includes(r)&&t.some(a=>a===r||a.startsWith(`${r}=`))},o=[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(i=>i[0]).find(i=>n(i));return o||e.recovery?.provided_fields?.map(i=>i.split("=",1)[0]).find(i=>n(i))}function bs(e,t,n){if(e.value!==void 0)return e.value;if(n){let i=t.find(a=>a===n||a.startsWith(`${n}=`));if(i?.startsWith(`${n}=`))return i.slice(n.length+1);let r=t.indexOf(n);return r>=0?t[r+1]:void 0}let o=e.recovery?.allowed_values;if(o?.length)return t.find((i,r)=>r>0&&!i.startsWith("-")&&!o.includes(i))}function Cs(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=W(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,r=vs(e,i),a=bs(e,i,r);return{surface:r??e.recovery?.missing?.[0]??wn(i)??"command",...a!==void 0?{rejected_value:a}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function xs(e,t){return _r({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Cs(e,t)},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 mi(xs(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function Rn(e){return _r({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function Ot(e){return e.replace(/\(outputHelp\)/g,"").trim()}function ks(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 gr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Es(e){return wn(e?.normalized_args)}function Ss(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 As(e,t){let n=e?.normalized_args,o=e?.provided_fields,i=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!i))for(let r of o){let a=n.findIndex(s=>s===r);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=i,k(s)}}}function Ts(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function At(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function Q(e,t,n){if(!n)return e;let o=Ot(t),i=At(n.code,e.code),r=At(n.type,yr(i)),a=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?Ts(o):void 0,d=Se(n.recovery),m=d&&e.recovery?Se({...e.recovery,...d}):d??e.recovery;return{...e,code:i,type:r,title:c??e.title,happened:o.length>0?o:e.happened,required:At(n.required,e.required),why:At(n.why,e.why),examples:a,nextSteps:s,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:n.flag,value:n.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,tombstone:n.tombstone,availableDependencies:n.available_dependencies,recovery:m}}function Os(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let i=o[1],r=Bo(process.cwd(),i);return Q(b(r?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${i}, but found a tracker at ${r}.`,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 ${r} <command>`,`PM_PATH=${r} pm <command>`],nextSteps:[`Re-run with "--pm-path ${r}" or export PM_PATH=${r}.`]}:{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 Rs(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let i=o[1],r=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(i),a=r?`The item ID "${i}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${i}" exists in the active tracker scope.`;return Q(b({code:"item_not_found",title:"Item ID not found",happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:r?["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 Is(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:Q(b({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 Ps(e,t,n){return t.includes("is locked")?Q(b({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function $s(e,t,n){let o=t.match(/^Missing required option /),i=t.match(/^Missing required options /);if(!o&&!i)return null;let r=!!i,a=r?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",l=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return Q(b({code:"missing_required_option",title:r?"Missing required options":`Missing required option ${s}`,happened:t,required:r?"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 Ns(e,t,n){return t.startsWith("No update flags provided")?Q(b({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 Ds(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=Se(n?.recovery),i=Es(o),r=i?`pm ${i} --help`:"pm <command> --help",a=Ss(t),s=Se({...o,allowed_values:o?.allowed_values??a}),l=As(o,a),c=l?[l,r]:[r,"pm contracts --command <command> --flags-only --json"],d=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${r}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return Q(b({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=Ot(e),o=Os(e,n,t)??Rs(e,n,t)??Is(e,n,t)??Ps(e,n,t)??$s(e,n,t)??Ns(e,n,t)??Ds(e,n,t);return o||Q(b({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 Ms(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 Fs(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Ls(e){if(!(!Array.isArray(e)||e.length===0))return k(e)}function Pn(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 z(e,t={}){let n=Pn(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Ls(o),r=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Se({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:r,...t})}function Tn(e,t){return!t||e.includes(t)?e:[...e,t]}var js=new Set(["--add","--add-json","--remove"]),Us=new Set(["command","cmd","path"]);function qs(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(js.has(o))return o}}function Hs(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let i=e[o];if(i!=="--add"&&i!=="--remove")continue;let r=e[o+1];if(typeof r!="string"||!Us.has(r))return;let a=[];for(let c=o+2;c<e.length;c+=1){let d=e[c];if(d.startsWith("--")&&d.length>2)break;a.push(d)}if(a.length<2)return;let s=`${r}=${a.join(" ")}`,l=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return k(l)}}function zs(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let r=Fs(i[1]),a=r.startsWith("--type"),s=o?.suggestedRetryCommand,l=Pn(o?.providedOptionFlags),c=[r],d=Ms(t,r,n),m=s?Tn(d,s):d,p=a?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Tn(p,`Replay with preserved arguments: ${s}`):p,g=l&&l.length>0?Tn(u,`Already provided options: ${l.join(", ")}`):u;return b({code:"missing_required_option",title:`Missing required option ${r}`,happened:`Commander rejected the command because ${r} was not provided.`,required:`Pass ${r} with a valid value before running the command.`,why:a?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:g,recovery:z(o,{missing:c})})}function Gs(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let i=o[1];return b({code:"missing_required_argument",title:`Missing required argument ${i}`,happened:`Command invocation omitted positional argument ${i}.`,required:`Provide ${i} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:z(n,{missing:[i]})})}function Ws(e,t,n){return b({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:z(t,{suggested_flags:n})})}var Bs={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 Vs(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 Ks(e,t,n,o,i){let r=o.otherCommands.slice(0,3),a=o.candidateTotal-r.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,r.length?`${e} is accepted by ${r.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,i?`Replay with suggested correction: ${i}`:void 0].filter(l=>typeof l=="string")}function Js(e,t){if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};let n=e.normalizedInvocationArgs;if(n===void 0)return{};if(n.filter(r=>r===t||r.startsWith(`${t}=`)).length!==1)return{};let o=n.findIndex(r=>r===t||r.startsWith(`${t}=`));if(o<0||n.includes("--")||!n[o]?.includes("=")&&o!==n.length-1&&n[o+1]?.startsWith("-")!==!0)return{};let i=D(n.filter((r,a)=>a!==o));return{retryCommand:k(i),suggestedRetryArgs:i}}function Ys(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},r=o[1],a=Pn(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=Js(i,r);if(t==="update"&&(r==="--file"||r==="--doc"))return Ws(r,n,a);let c=Vs(i),d=Ks(r,t,a,c,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(r.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,`pm ${t?V(t)?.canonical??t:"<command>"} --help`].filter(p=>typeof p=="string");return b({code:"unknown_option",title:`Unknown option ${r}`,happened:`Commander does not recognize option ${r} for this command path.`,required:Bs[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:r,value:r,examples:m,nextSteps:d,recovery:z(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:l,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:i.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function Xs(e,t,n,o,i){let r=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return b({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:gr([t.installCommand,...n]),nextSteps:gr([r,...a]),recovery:z(i)})}function Zs(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=ge(t?.unknownCommandExamples),r=ge(t?.unknownCommandNextSteps),a=hs(o),s=i??["pm --help"],l=r??["Verify spelling and active extensions, then rerun."],c=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!d||!c.has(d))?Xs(o,a,s,l,t):b({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:z(t)})}function Qs(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ge(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let i=e?.suggestedRetryCommand;return b({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...i?[i]:[],`pm ${V(t)?.canonical??t} --help`],nextSteps:i?[`Retry with the declared hyphenated action: ${i}`]:["Choose one value from recovery.allowed_values."],recovery:z(e,{allowed_values:o,suggested_retry:i})})}function el(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=qs(o);if(!i)return null;let r=Hs(o);return b({code:"linked_test_value_not_quoted",title:`Linked-test ${i} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${i} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${i} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...r?[r]:[],'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:[...r?[`Replay with the value re-joined into one argument: ${r}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:z(n,r?{suggested_retry:r}:{})})}var tl=new Set(["comments","docs","files","learnings","notes","test"]);function nl(e,t,n){if(!/too many arguments/i.test(e)||!tl.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(c=>c===t),r=o[i+1],a=o[i+2],s=n?.verifiedCollectionItemId?.trim();if(r?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let l=`pm ${t} ${s} --add <value>`;return b({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:z(n,{parsed_positionals:[{role:"transposed_subcommand",value:r},{role:"item_id",value:s}],suggested_retry:l})})}var ol=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"]),hr=new Set(["context","ctx"]);function il(e,t,n){if(!/too many arguments/i.test(e)||!hr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(c=>hr.has(c)),r=i===-1?1:i+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let c=!1;for(let d of o.slice(r)){if(c){c=!1;continue}let m=d.split("=")[0];if(ol.has(m)){c=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let l=`pm get ${s}`;return b({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:z(n,{suggested_retry:l})})}function $n(e,t,n,o){let i=Ot(e),r=zs(i,t,n,o)??Gs(i,t,o)??Ys(i,t,o)??Zs(i,o)??Qs(o)??nl(i,t,o)??el(i,t,o)??il(i,t,o);return r||b({code:"invalid_command_usage",title:"Invalid command usage",happened:i,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:z(o)})}function vr(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: ${k(n.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
7
- `):on(wr(n),n.required).output}function br(e,t){return Rn(In(e,t))}function Nn(e,t,n){return On(In(e,n),t)}function Cr(e,t,n,o){let i=$n(e,t,n,o);return on(wr(i),i.required).output}function Dn(e,t,n,o){return Rn($n(e,t,n,o))}function Rt(e,t,n,o,i){return On($n(e,t,n,i),o)}function xr(e,t){let n=kr(e);return On(n,t)}function kr(e){let t=Ot(e);return ks(t)?b({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."]}):b({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 Er(e){return Rn(kr(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]="667ad638-d21d-5a49-a00e-1335cb3f10be")}catch{}})();var Be=Go.join("|"),rl={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"},al={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"]}},Sr=["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 sl(e,t){let n=al[e];if(!n)return[];let o=H(t);for(let[i,r]of Object.entries(n))if(H(i)===o)return r;return[]}function Mn(e,t,n){if(n.length===0)return e;if(t){let a=n.find(d=>d.declared_command_match===!0),{token_accounting:s,...l}=JSON.parse(e),c={...l,...a?{extension_command_failure:{code:"extension_command_activation_failed",extension:a.name,layer:a.layer,error:a.error,recovery_commands:a.recovery_commands??[]}}:{},failed_extensions:n};return JSON.stringify(s===void 0?c:le(c,d=>`${JSON.stringify(d,null,2)}
1
+ import{B as tr,D as nr,E as _n,a as an,b as de,c as sn,d as ln,e as cn,f as dn,i as U,j as M,k as A,l as me,m as x,n as Ti,s as He,t as Ri,u as Ni,y as Di,z as wn}from"./chunks/chunk-JQ7DW663.js";import{Wa as er,f as vi,l as Si}from"./chunks/chunk-SMKHR6BM.js";import"./chunks/chunk-XZDWAYJC.js";import"./chunks/chunk-JDKD3WGG.js";import{F as Ki,Id as Qi,Nc as Zi,b as Gi,d as Ct,g as Wi,h as Vi,i as Y,j as Bi}from"./chunks/chunk-V3U77H3V.js";import{Ga as Ji,g as Ai}from"./chunks/chunk-J52QIRRZ.js";import"./chunks/chunk-QXIDOOWT.js";import"./chunks/chunk-DEZPZOQ7.js";import{$a as Vo,$g as bi,Ac as ne,Aj as qe,Bc as ri,Cc as ai,Ce as mi,Dc as se,De as on,Ec as si,Fc as pt,Fn as We,Gb as Ko,Gc as Ce,Hc as le,I as Ho,If as ce,In as Ui,J as zo,Jf as _i,Kc as li,Kf as xe,Lc as ut,Ln as qi,M as Me,Mf as rn,Nf as _,Oo as xt,Pb as Jo,Po as kt,Q as Zt,Qb as Yo,Qn as gn,Qo as hn,Ra as Qt,Rc as nn,Rn as Hi,Ro as Ve,Sc as ft,Sn as zi,So as E,Tc as ci,Te as pi,To as Yi,Ua as ae,Uc as di,Ue as ui,Uo as yn,Ve as fi,Wa as Wo,Wb as Xo,We as gi,Xa as mt,Xe as hi,Yb as Zo,Yi as wt,Zi as Ei,_a as en,_o as q,ab as R,ae as gt,ah as Ci,cb as Bo,cd as k,db as J,dd as je,e as P,g as W,gl as Oi,h as T,hl as oe,hn as Mi,ih as ht,in as bt,j as V,jc as Qo,jl as Ii,jn as pn,k as Xt,kc as Fe,ki as yt,kl as Pi,kn as un,l as B,lj as _t,ln as ze,m as qo,mc as Le,mg as mn,mi as xi,ml as $i,mn as fn,mp as Xi,na as f,nc as ei,nj as Ue,nn as Fi,oa as dt,oj as vt,on as Ge,pa as C,pi as ke,qa as Go,qi as D,ri as ki,rn as Li,sf as yi,sn as ji,vb as tn,wc as ti,wf as wi,x as K,xc as ni,yc as oi,zc as ii}from"./chunks/chunk-Y6VRBTP3.js";import{Command as No,CommanderError as ka}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]="0429ff6a-ec0d-5c20-9fa7-0ed05b154523")}catch{}})();function H(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function pe(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return H(t)}function X(e){let t=new Set,n=[];for(let o of e){let i=pe(o);i&&(t.has(i)||n.push(i),t.add(i))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bdbd1281-8294-5bda-8053-f9fff4c34bf3")}catch{}})();var vn=new Set(["--fields","--depth","--for","--token-budget"]),Et=new Set(["--full","--brief","--compact"]);function os(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 is(e){let t=oe(x([...e])),n=new Set([...Ii,...Pi,...$i].flatMap(a=>a.keys.map(s=>`--${s.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),o=new Map([...qe,...t].flatMap(a=>[a.flag,...a.aliases??[]].map(s=>[s,a.flag]))),i=new Map([...qe,...t].flatMap(a=>[a.flag,...a.aliases??[]].map(s=>[s,os(a,n)])));for(let a of vn)i.set(a,!0);for(let a of Et)i.set(a,!1);let r=new Map;for(let a=0;a<e.length;a+=1){let s=e[a];if(s==="--")break;if(!s.startsWith("-"))continue;let l=s.split("=")[0];if(!i.has(l)&&!s.includes("="))return;r.set(a,o.get(l)??l),i.get(l)&&!s.includes("=")&&(a+=1)}return r}function or(e,t,n){let o=new Set;for(let[i,r]of t)n.has(r)&&(o.add(i),vn.has(r)&&!e[i].includes("=")&&o.add(i+1));return e.filter((i,r)=>!o.has(r))}function ir(e,t,n){return e.splice(n,0,...t),e}function rs(e,t){let n=t.find(i=>Et.has(i));if(n===void 0)return;let o=[...new Set(e.values())].filter(i=>Et.has(i));return o.length===1?o[0]:n}function rr(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,i={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return i;let r=is(e);if(!r)return i;let a;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return i;let l=[...r].find(([c,d])=>d==="--fields")?.[0]??-1;if(l<0)return i;a=ir(or(e,r,new Set(["--fields"])),["--fields",o[s+1]],l)}else{let s=rs(r,o);if(s===void 0)return i;let l=new Set([...vn,...Et]),c=[...r].find(([d,m])=>l.has(m))?.[0]??-1;if(c<0)return i;a=ir(or(e,r,l),[s],c)}return{...n,suggested_retry:k(a),suggested_retry_args: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]="1c4a4bc4-d26a-5f51-bac0-2a132dad1f56")}catch{}})();async function ar(e,t){await Hi(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 sr(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await yi({pmRoot:e.pmRoot,result:le()})}catch(o){t=o}let n=await D(e.pmRoot);if(await wi({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]="63db65f1-fdbe-513d-b71a-87490ec9b69e")}catch{}})();var lr=new WeakMap;function St(e,t){lr.set(e,t)}function ue(e){return lr.get(e)}function cr(e){return e.length>0?[e[0]]:[]}function as(e){let t=["","Intent:",` ${e.why}`],n=cr(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 dr(e,t){return t==="detailed"?ss(e):as(e)}function F(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var ls={cal:"calendar",ctx:"context"};function cs(e,t){return e.commands.find(n=>n.name()===t)??null}function ds(e,t){let n=e;for(let o of t){let i=cs(n,o);if(!i)return null;n=i}return n}function bn(e,t,n,o){let i=ds(e,t.split(" ").filter(r=>r.length>0));i&&i.addHelpText("after",dr(n,o))}function Cn(e){return e.includes("--explain")?"detailed":"compact"}function ie(e){return e.includes("--all")||e.includes("--explain")}var fe={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 install ./my-package --project","pm install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm extension catalog --project","pm extension catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list-all --limit 50","pm list-all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-in-progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list-blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' 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" --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 takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause"]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of P){let n=fe[e];n&&(fe[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var Ee={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},mr=V.filter(e=>e.lifecycle==="deprecated");for(let e of mr){let t=fe[e.alias];fe[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[Ee,...Object.values(fe)])e.examples=e.examples.map(t=>{for(let n of mr){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function ms(e){let t=F(e??"");return t?ls[t]??t:""}function xn(e){let t=ms(e);return t?fe[t]??Ee:Ee}function pr(e,t){let n=xn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:cr(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function ps(){let e=V.filter(({lifecycle:n})=>n==="permanent"),t=V.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(" ")} (${qo(n)})`)].join(`
4
+ `)}function us(e,t,n,o){let i=new Set(Wi);e.configureHelp({visibleCommands(r){let a=t.visibleCommands(r);return n?a.filter(s=>(ue(s)??Y(s.name()))!=="internal"):r!==e?a:a.filter(s=>o.has(s))},visibleOptions(r){let a=t.visibleOptions(r);return r!==e||n?a:a.filter(s=>i.has(s.flags))}})}function fs(e,t,n,o){let i=new Set(Bi("core")),r=e.createHelp();r.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let a=()=>`${r.formatHelp(e,r)}${o}
5
+ `,s=t.visibleCommands(e);for(let l of s)ue(l)===void 0&&(l.name()==="help"||i.has(l.name()))&&n.add(l);for(let l of s)ue(l)==="core"&&(n.add(l),Vi(a()).within_budget||n.delete(l))}function ur(e,t=process.argv.slice(2)){let n=e.createHelp(),o=ie(t),i=new Set;us(e,n,o,i);let r=Cn(t),a=dr(Ee,r);e.addHelpText("after",a),o&&e.addHelpText("after",ps()),fs(e,n,i,a);for(let[d,m]of Object.entries(fe))bn(e,d,m,r);let s=F(A(t).commandPathTokens.join(" ")),l=Ue(s);if(l){bn(e,l.parent,{why:l.description,examples:[l.example],tips:[`Action path: pm ${l.command}`,vt(l.accepted_flags)]},r);return}let c=_t.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.`]},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]="b70452a1-26dc-5f66-bb87-67a5bde7bd30")}catch{}})();function kn(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:i}of P){if(t&&!P.some(c=>c.canonical.startsWith(`${o} `)))continue;let r=e.commands.findIndex(c=>c.name()===n);if(r<0)continue;let a=e.commands[r],s=e;for(let c of i.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===c)??s.command(c).description(`Discover ${c} operations.`);let l=i[i.length-1];if(s.commands.some(c=>c.name()===l))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(r,1),a.name(l),St(a,Y(o)),s.enablePositionalOptions(),s.addCommand(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]="392093b2-4fed-53dc-a686-dae8e6f0a91e")}catch{}})();function Tt(e){let{why:t,title:n,...o}=e;return o}var gs=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function hs(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!gs.has(e.code)}function wr(e){return`urn:pm-cli:error:${e}`}function b(e){return{...e,type:wr(e.code)}}var Se={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},fr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},gr={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},At={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},ys={guide:Se,shell:Se,completion:Se,"completion-statuses":Se,"completion-tags":Se,"completion-types":Se,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:fr,cal:fr,reindex:gr,"search-advanced":gr,"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 ws(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return ys[t]}function En(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function _s(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 vs(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 Z(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let i=n.map(r=>({role:typeof r?.role=="string"?r.role.trim():"",value:typeof r?.value=="string"?r.value.trim():""})).filter(r=>r.role.length>0&&r.value.length>0);i.length>0&&(e.parsed_positionals=i);return}let o=_s(n);o&&(e[t]=o)}function Ae(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Sn(t,"attempted_command",e.attempted_command),Z(t,"normalized_args",e.normalized_args),Z(t,"parsed_positionals",e.parsed_positionals),Z(t,"provided_fields",e.provided_fields),Z(t,"missing",e.missing),Z(t,"missing_required_fields",e.missing_required_fields),Z(t,"suggested_flags",e.suggested_flags),Z(t,"allowed_values",e.allowed_values),Z(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),Z(t,"suggested_retry_args",e.suggested_retry_args),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=vs(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 ge(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function bs(e){let t=Ae(e);if(!t)return[];let n=["Recovery bundle:"];if(An(n,"suggested_retry",t.suggested_retry),An(n,"attempted_command",t.attempted_command),ge(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(ge(n,"provided_fields",t.provided_fields,", "),ge(n,"missing",t.missing,", "),ge(n,"missing_required_fields",t.missing_required_fields,", "),ge(n,"suggested_flags",t.suggested_flags,", "),ge(n,"allowed_values",t.allowed_values,", "),ge(n,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&n.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&n.push(" candidate_commands_truncated: true"),t.option_scope!==void 0&&n.push(` option_scope: ${t.option_scope}`),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),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 _r(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=bs(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
6
+ `)}function vr(e,t){return t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),hs(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 Cs(e,t){if(e.flag)return e.flag;let n=i=>{let r=i.split("=",1)[0];return M([r]).length>0&&!["--help","--no-changed-fields","--version"].includes(r)&&t.some(a=>a===r||a.startsWith(`${r}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(i=>i[0]).find(i=>n(i))}function xs(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(r=>r===n||r.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let i=t.indexOf(n);return t[i+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=M(e.recovery?.normalized_args??[]),o=W(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,r=Cs(e,i),a=xs(e,i,r);return{surface:r??e.recovery?.missing?.[0]??wn(i)??"command",...a!==void 0?{rejected_value:a}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Es(e,t){return vr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:ks(e,t)},e)}function Tn(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 mi(Es(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function Rn(e){return vr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function Rt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Ss(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 he(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 hr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function As(e){return wn(e?.normalized_args)}function Os(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 Ts(e,t){let n=e?.normalized_args,o=e?.provided_fields,i=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!i))for(let r of o){let a=n.findIndex(s=>s===r);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=i,k(s)}}}function Rs(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Ot(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function Is(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 Q(e,t,n){if(!n)return e;let o=Rt(t),i=Ot(n.code,e.code),r=Ot(n.type,wr(i)),a=he(n.examples)??e.examples,s=he(n.nextSteps)??e.nextSteps,l=he(n.verification_errors)??e.verificationErrors,c=e.code==="command_failed"&&n.code?Rs(o):void 0,d=Ae(n.recovery),m=d&&e.recovery?Ae({...e.recovery,...d}):d??e.recovery;return{...e,code:i,type:r,title:c??e.title,happened:o.length>0?o:e.happened,required:Ot(n.required,e.required),why:Ot(n.why,e.why),examples:a,nextSteps:s,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:Is(n,m)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,tombstone:n.tombstone,availableDependencies:n.available_dependencies,recovery:m}}function Ps(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let i=o[1],r=Vo(process.cwd(),i);return Q(b(r?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${i}, but found a tracker at ${r}.`,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 ${r} <command>`,`PM_PATH=${r} pm <command>`],nextSteps:[`Re-run with "--pm-path ${r}" or export PM_PATH=${r}.`]}:{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 $s(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let i=o[1],r=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(i),a=r?`The item ID "${i}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${i}" exists in the active tracker scope.`;return Q(b({code:"item_not_found",title:"Item ID not found",flag:"id",value:i,happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:r?["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 Ns(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:Q(b({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function Ds(e,t,n){return t.includes("is locked")?Q(b({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function Ms(e,t,n){let o=t.match(/^Missing required option /),i=t.match(/^Missing required options /);if(!o&&!i)return null;let r=!!i,a=r?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",l=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return Q(b({code:"missing_required_option",title:r?"Missing required options":`Missing required option ${s}`,happened:t,required:r?"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 Fs(e,t,n){return t.startsWith("No update flags provided")?Q(b({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 Ls(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=Ae(n?.recovery),i=As(o),r=i?`pm ${i} --help`:"pm <command> --help",a=Os(t),s=Ae({...o,allowed_values:o?.allowed_values??a}),l=Ts(o,a),c=l?[l,r]:[r,"pm contracts --command <command> --flags-only --json"],d=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${r}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return Q(b({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),o=Ps(e,n,t)??$s(e,n,t)??Ns(e,n,t)??Ds(e,n,t)??Ms(e,n,t)??Fs(e,n,t)??Ls(e,n,t);return o||Q(b({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 js(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 Us(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function qs(e){if(!(!Array.isArray(e)||e.length===0))return k(e)}function Pn(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 z(e,t={}){let n=Pn(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:qs(o),r=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Ae({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:r,...t})}function On(e,t){return!t||e.includes(t)?e:[...e,t]}var Hs=new Set(["--add","--add-json","--remove"]),zs=new Set(["command","cmd","path"]);function Gs(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(Hs.has(o))return o}}function Ws(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let i=e[o];if(i!=="--add"&&i!=="--remove")continue;let r=e[o+1];if(typeof r!="string"||!zs.has(r))return;let a=[];for(let c=o+2;c<e.length;c+=1){let d=e[c];if(d.startsWith("--")&&d.length>2)break;a.push(d)}if(a.length<2)return;let s=`${r}=${a.join(" ")}`,l=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return k(l)}}function Vs(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let r=Us(i[1]),a=r.startsWith("--type"),s=o?.suggestedRetryCommand,l=Pn(o?.providedOptionFlags),c=[r],d=js(t,r,n),m=s?On(d,s):d,p=a?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?On(p,`Replay with preserved arguments: ${s}`):p,g=l&&l.length>0?On(u,`Already provided options: ${l.join(", ")}`):u;return b({code:"missing_required_option",title:`Missing required option ${r}`,happened:`Commander rejected the command because ${r} was not provided.`,required:`Pass ${r} with a valid value before running the command.`,why:a?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:g,recovery:z(o,{missing:c})})}function Bs(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let i=o[1];return b({code:"missing_required_argument",title:`Missing required argument ${i}`,happened:`Command invocation omitted positional argument ${i}.`,required:`Provide ${i} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:z(n,{missing:[i]})})}function Ks(e,t,n){return b({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:z(t,{suggested_flags:n})})}var Js={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 Ys(e){let t=he(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Xs(e,t,n,o,i){let r=o.otherCommands.slice(0,3),a=o.candidateTotal-r.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,r.length?`${e} is accepted by ${r.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,i?`Replay with suggested correction: ${i}`:void 0].filter(l=>typeof l=="string")}function Zs(e,t){if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};let n=e.normalizedInvocationArgs;if(n===void 0)return{};if(n.filter(r=>r===t||r.startsWith(`${t}=`)).length!==1)return{};let o=n.findIndex(r=>r===t||r.startsWith(`${t}=`));if(o<0||n.includes("--")||!n[o]?.includes("=")&&o!==n.length-1&&n[o+1]?.startsWith("-")!==!0)return{};let i=M(n.filter((r,a)=>a!==o));return{retryCommand:k(i),suggestedRetryArgs:i}}function Qs(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},r=o[1],a=Pn(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=Zs(i,r);if(t==="update"&&(r==="--file"||r==="--doc"))return Ks(r,n,a);let c=Ys(i),d=Xs(r,t,a,c,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(r.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,`pm ${t?B(t)?.canonical??t:"<command>"} --help`].filter(p=>typeof p=="string");return b({code:"unknown_option",title:`Unknown option ${r}`,happened:`Commander does not recognize option ${r} for this command path.`,required:Js[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:r,value:r,examples:m,nextSteps:d,recovery:z(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:l,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:i.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function el(e,t,n,o,i){let r=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return b({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:hr([t.installCommand,...n]),nextSteps:hr([r,...a]),recovery:z(i)})}function tl(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=he(t?.unknownCommandExamples),r=he(t?.unknownCommandNextSteps),a=ws(o),s=i??["pm --help"],l=r??["Verify spelling and active extensions, then rerun."],c=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!d||!c.has(d))?el(o,a,s,l,t):b({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:z(t)})}function nl(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=he(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let i=e?.suggestedRetryCommand;return b({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...i?[i]:[],`pm ${B(t)?.canonical??t} --help`],nextSteps:i?[`Retry with the declared hyphenated action: ${i}`]:["Choose one value from recovery.allowed_values."],recovery:z(e,{allowed_values:o,suggested_retry:i})})}function ol(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=Gs(o);if(!i)return null;let r=Ws(o);return b({code:"linked_test_value_not_quoted",title:`Linked-test ${i} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${i} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${i} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...r?[r]:[],'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:[...r?[`Replay with the value re-joined into one argument: ${r}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:z(n,r?{suggested_retry:r}:{})})}var il=new Set(["comments","docs","files","learnings","notes","test"]);function rl(e,t,n){if(!/too many arguments/i.test(e)||!il.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(c=>c===t),r=o[i+1],a=o[i+2],s=n?.verifiedCollectionItemId?.trim();if(r?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let l=`pm ${t} ${s} --add <value>`;return b({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:z(n,{parsed_positionals:[{role:"transposed_subcommand",value:r},{role:"item_id",value:s}],suggested_retry:l})})}var al=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"]),yr=new Set(["context","ctx"]);function sl(e,t,n){if(!/too many arguments/i.test(e)||!yr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(c=>yr.has(c)),r=i===-1?1:i+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let c=!1;for(let d of o.slice(r)){if(c){c=!1;continue}let m=d.split("=")[0];if(al.has(m)){c=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let l=`pm get ${s}`;return b({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:z(n,{suggested_retry:l})})}function $n(e,t,n,o){let i=Rt(e),r=Vs(i,t,n,o)??Bs(i,t,o)??Qs(i,t,o)??tl(i,o)??nl(o)??rl(i,t,o)??ol(i,t,o)??sl(i,t,o);return r||b({code:"invalid_command_usage",title:"Invalid command usage",happened:i,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:z(o)})}function br(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: ${k(n.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
7
+ `):on(_r(n),n.required).output}function Cr(e,t){return Rn(In(e,t))}function Nn(e,t,n){return Tn(In(e,n),t)}function xr(e,t,n,o){let i=$n(e,t,n,o);return on(_r(i),i.required).output}function Dn(e,t,n,o){return Rn($n(e,t,n,o))}function It(e,t,n,o,i){return Tn($n(e,t,n,i),o)}function kr(e,t){let n=Er(e);return Tn(n,t)}function Er(e){let t=Rt(e);return Ss(t)?b({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."]}):b({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 Sr(e){return Rn(Er(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]="667ad638-d21d-5a49-a00e-1335cb3f10be")}catch{}})();var Be=Go.join("|"),ll={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},cl={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}},Ar=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function dl(e,t){let n=cl[e];if(!n)return[];let o=H(t);for(let[i,r]of Object.entries(n))if(H(i)===o)return r;return[]}function Mn(e,t,n){if(n.length===0)return e;if(t){let a=n.find(d=>d.declared_command_match===!0),{token_accounting:s,...l}=JSON.parse(e),c={...l,...a?{extension_command_failure:{code:"extension_command_activation_failed",extension:a.name,layer:a.layer,error:a.error,recovery_commands:a.recovery_commands??[]}}:{},failed_extensions:n};return JSON.stringify(s===void 0?c:ce(c,d=>`${JSON.stringify(d,null,2)}
8
8
  `),null,2)}let o=n.map(a=>`- ${a.layer}:${a.name}: ${a.error}`).join(`
9
9
  `),i=n.find(a=>a.declared_command_match===!0);if(!i)return`${e}
10
10
  Extension activation failures:
@@ -16,23 +16,23 @@ ${r}`:""}
16
16
 
17
17
  ${e}
18
18
  Extension activation failures:
19
- ${o}`}function Fn(e){return A(e).commandPathTokens[0]??x(e)??"<command>"}function ll(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let i=o.shift();if(!i)continue;let r=M(E(i)),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r),o.push(...i.commands)}for(let i of t.keys()){let r=M(i),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r)}return[...n].sort((i,r)=>i.localeCompare(r))}function Ar(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" ");if(n===o)return 0;if(i.includes(o))return 1;if(i.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let r=o.length>=5?2:1,a=Number.POSITIVE_INFINITY;for(let s of i){let l=tn(s,o,r);l!==null&&(a=Math.min(a,l))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function Tr(e){return H(e).slice(2).replace(/-/g,"")}function Ln(e){return k(e)}function cl(e){let t=V(e)?.canonical??Xt[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=rl[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function Or(e){let t=Ki(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function dl(e,t){let n=Or(e);if(n.length===0)return[];let o=[];for(let i of t.values()){let r=new Set,a=i.source;if(a)for(let l of[a.name,a.package]){let c=Or(l??"");c.length>0&&r.add(c)}if(r.size===0)continue;[...r].some(l=>l===n||l.includes(n)||n.includes(l))&&o.push(i.command)}return[...new Set(o)].sort((i,r)=>i.localeCompare(r))}function Ve(e,t){let n=new Set,o=t??xe(e);for(let i of o){i.flag.startsWith("--")&&n.add(H(i.flag));for(let r of i.aliases??[])r.startsWith("--")&&n.add(H(r))}return[...n].sort((i,r)=>i.localeCompare(r))}function ml(e,t){if(!e.startsWith("--"))return[];let n=Tr(e);if(n.length===0)return[];let o=n.length>=8?2:1,i=[];for(let r of t){let a=Tr(r);if(a===n)continue;if(n.length>=3&&a.startsWith(n)){i.push({flag:r,rank:0,distance:a.length-n.length});continue}let s=tn(n,a,o);s===null||s<=0||i.push({flag:r,rank:1,distance:s})}return i.sort((r,a)=>r.rank!==a.rank?r.rank-a.rank:r.distance!==a.distance?r.distance-a.distance:r.flag.localeCompare(a.flag)).map(r=>r.flag).slice(0,3)}var It,pl=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 ul(){if(It)return It;let e=new Map;for(let t of ft)if(!pl.has(t))for(let n of Ve(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return It=e,It}function fl(e,t){if(!e.startsWith("--"))return[];let n=ul().get(H(e));if(!n)return[];let o=t?.trim().toLowerCase(),i=new Set(Ve(o));return[...new Set(n.filter(r=>r!==o).map(r=>({command:r,sharedFlagCount:Ve(r).filter(a=>i.has(a)).length})).sort((r,a)=>r.sharedFlagCount!==a.sharedFlagCount?a.sharedFlagCount-r.sharedFlagCount:r.command.localeCompare(a.command)).map(({command:r})=>V(r)?.canonical??r))]}function gl(e,t,n){for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--"))continue;let r=i.indexOf("="),a=r>=0?i.slice(0,r):i;if(H(a)!==H(t))continue;let s=[...e];return s[o]=r>=0?`${n}${i.slice(r)}`:n,s}}function hl(e){let t=new Set(e.commandPaths),n=r=>Math.min(Ar(r,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Ar(r,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,i=(r,a)=>{if(!Number.isFinite(a)||!t.has(r))return;let s=o.get(r);(s===void 0||a<s)&&o.set(r,a)};for(let r of e.commandPaths)i(r,n(r));for(let[r,a]of Object.entries(Xt))r!=="read"&&i(a,n(r));return[...o.entries()].sort(([r,a],[s,l])=>a!==l?a-l:r.localeCompare(s)).map(([r])=>r)}function yl(e){let t=V(e.normalizedUnknown),n=tr(e.commandPaths,e.primaryToken),o=hl(e),i=dl(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return _n([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...i],e.commandPaths,e.primaryToken).filter(r=>!e.normalizedUnknown.includes(" ")||r!==e.normalizedUnknown)}function wl(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function _l(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 jn(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let i=M(o[1]);if(i.length===0)return;let r=ll(t,n);if(r.length===0)return;let a=cl(i);if(a&&!r.includes(a.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[a.installCommand,`pm ${a.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${i}" is provided by the "${a.packageAlias}" package. Install it with: ${a.installCommand}. Command after installation: pm ${a.canonicalPath}.`],suggestedRetryCommand:a.installCommand};let s=i.split(" ")[0],l=yl({commandPaths:r,normalizedUnknown:i,primaryToken:s,extensionDescriptors:n}),c=wl(r),d=(l.length>0?l:_n(c,r)).slice(0,3),m=_l(d,l.length>0),p=l.length>0?`Did you mean: ${d.join(", ")}?`:null;return{unknownCommandExamples:m,unknownCommandNextSteps:[...p?[p]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...p?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function vl(e){return Array.from(new Set(e))}function bl(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 Cl(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(r=>r.trim().toLowerCase()===n))}function Ke(e,t){if(t.length===0)return!0;let n=e;for(let[o,i]of t.entries()){let r=xl(n,i);if(!r){let a=n.registeredArguments;return a.length>0&&(n.commands.length===0||a[0]?.required===!0)&&(a.at(-1)?.variadic===!0||t.length-o<=a.length)}n=r}return!0}async function kl(e,t,n,o){try{let i=R(process.cwd(),e.path);if(!await K(J(i)))return{allowedTypes:Be};let r=await N(i),a=e.noExtensions?void 0:ae(),s=re(r,a),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 yt(i,d,r.id_prefix,r.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Be,pmRoot:i,settings:r,typeToFolder:s.type_to_folder,verifiedCollectionItemId:l}}catch{return{allowedTypes:Be}}}function El(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?vl([...sl(t,n[1]),...ml(n[1],Ve(t))]):void 0,i=n?fl(n[1],t):[],r=n!==null&&Ve(t).includes(H(n[1]));return{match:n,suggestions:o,otherCommands:i,scope:r?"declared_on_path":i.length>0?"declared_elsewhere":"declared_nowhere"}}function Sl(e,t,n){if(!t||!n||n.length===0)return;let o=gl(e,t[1],n[0]);return o?Ln(o):void 0}function Al(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Cl(bl(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let i=x(t);if(i)return er(t,i,[o])}function Tl(e,t){if(!/too many arguments/i.test(e))return;let n=de(t),o=W(t.slice(n));if(o?.alias!=="schema")return;let i=n+o.canonical_argv.length-1,r=t[i+1]?.trim().toLowerCase(),a=t[i+2]?.trim().toLowerCase();if(!r||!a)return;let s=`${r}-${a}`;if(!Sr.includes(s))return;let l=[...t.slice(0,i+1),s,...t.slice(i+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${r} ${a}`,unknownSubcommandAllowedValues:[...Sr],suggestedRetryCommand:Ln(l)}}async function Je(e,t,n,o={}){let r=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",a=qe(process.argv.slice(2)).argv,s=U(a),l=de(a),c=W(a.slice(l))?.alias??x(a),d=Ln(a),m=X(a),p=await kl(s,r,a,c),u=p.allowedTypes,g=jn(r,t,n),h=El(r,c),y=Tl(r,a),S=y?.suggestedRetryCommand??Sl(a,h.match,h.suggestions)??Al(r,a);return{message:r,commandName:c,allowedTypes:u,attemptedCommand:d,normalizedInvocationArgs:[...a],providedOptionFlags:m,unknownOptionSuggestions:h.suggestions,unknownOptionOtherCommands:h.otherCommands.length>0?h.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:h.otherCommands.length>0?h.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:h.otherCommands.length>12||void 0,unknownOptionScope:h.scope,suggestedRetryCommand:S,verifiedCollectionItemId:p.verifiedCollectionItemId,...y,...g,...o}}async function Un(e,t,n,o={}){let i=await Je(e,t,n,o),{message:r,commandName:a,allowedTypes:s,unknownCommandExamples:l,unknownCommandNextSteps:c,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:y,unknownOptionScope:S,unknownSubcommandPath:T,unknownSubcommandToken:G,unknownSubcommandAllowedValues:j,suggestedRetryCommand:we,verifiedCollectionItemId:Yt,failedExtensions:lt}=i,Ne=Cr(r,a,s,{unknownCommandExamples:l,unknownCommandNextSteps:c,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:y,unknownOptionScope:S,unknownSubcommandPath:T,unknownSubcommandToken:G,unknownSubcommandAllowedValues:j,suggestedRetryCommand:we,verifiedCollectionItemId:Yt,failedExtensions:lt}),_e=await di("help_format",{message:Ne,command:a,allowed_types:s});return _e.handled&&typeof _e.result=="string"?_e.result:Ne}async function qn(e,t,n,o=!1,i={}){let r=await Je(e,t,n,i),a=Rt(r.message,r.commandName,r.allowedTypes,f.USAGE,{unknownCommandExamples:r.unknownCommandExamples,unknownCommandNextSteps:r.unknownCommandNextSteps,attemptedCommand:r.attemptedCommand,normalizedInvocationArgs:r.normalizedInvocationArgs,providedOptionFlags:r.providedOptionFlags,unknownOptionSuggestions:r.unknownOptionSuggestions,unknownOptionOtherCommands:r.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:r.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:r.unknownOptionOtherCommandsTruncated,unknownOptionScope:r.unknownOptionScope,unknownSubcommandPath:r.unknownSubcommandPath,unknownSubcommandToken:r.unknownSubcommandToken,unknownSubcommandAllowedValues:r.unknownSubcommandAllowedValues,suggestedRetryCommand:r.suggestedRetryCommand,verifiedCollectionItemId:r.verifiedCollectionItemId,failedExtensions:r.failedExtensions}),s=o?Tt(a):a,l=U(r.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(l?le(s,c=>`${JSON.stringify(c,null,2)}
21
- `):s,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]="939abfaf-7563-5490-bd76-90d188aa0940")}catch{}})();async function Rr(e,t,n,o){if(n)return null;let i=e.some(a=>a==="--for"||a.startsWith("--for=")),r=x(e)==="contracts"&&e.includes("--full");return i||r?await o(t):null}import{Option as Ol}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]="2f731313-580e-5554-bf61-f160121a298b")}catch{}})();function v(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Pr(e,t){let n=new Map;for(let o of e){let i=v(o.command);for(let r of t){if(r.layer!==o.layer||r.name!==o.name)continue;let a=v(r.command),s=a.split(" "),l=s.at(-1),c=s.slice(1).join(" "),d=c?`${s[0]}-${l} ${c}`:`${s[0]}-${l}`;if(l&&i===d){n.set(i,a);break}}}return n}function Hn(e,t,n,o){if(!t||!n)return;let i,r=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>r&&p.every((u,g)=>c[g]===u)&&(i=m,r=p.length)}}let a=i?.flags.find(s=>s.long===n||s.short===n);if(a)return Pt(a).takesValue}function P(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ee(e){return typeof e=="boolean"?e:void 0}function Pt(e){let t=P(e.value_type)??P(e.type),n=P(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||ee(e.required)===!0||ee(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function Rl(e){if(ee(e.visible)===!1)return null;let n=P(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=P(e.short),i=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",r=P(e.value_name),a=r?` <${r}>`:"",s=P(e.description)??"Extension-provided option.",l=[];ee(e.required)===!0&&l.push("required"),ee(e.enabled)===!1&&l.push("disabled");let c=l.length>0?` [${l.join(", ")}]`:"";return`${i}${n}${a} ${s}${c}`}function $r(e){let t=[...new Set(e.map(Rl).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 ml(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let i=o.shift();if(!i)continue;let r=F(E(i)),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r),o.push(...i.commands)}for(let i of t.keys()){let r=F(i),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r)}return[...n].sort((i,r)=>i.localeCompare(r))}function Or(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" ");if(n===o)return 0;if(i.includes(o))return 1;if(i.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let r=o.length>=5?2:1,a=Number.POSITIVE_INFINITY;for(let s of i){let l=tn(s,o,r);l!==null&&(a=Math.min(a,l))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function Tr(e){return H(e).slice(2).replace(/-/g,"")}function Ln(e){return k(e)}function pl(e){let t=B(e)?.canonical??Xt[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=ll[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function Rr(e){let t=Ji(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function ul(e,t){let n=Rr(e);if(n.length===0)return[];let o=[];for(let i of t.values()){let r=new Set,a=i.source;if(a)for(let l of[a.name,a.package]){let c=Rr(l??"");c.length>0&&r.add(c)}if(r.size===0)continue;[...r].some(l=>l===n||l.includes(n)||n.includes(l))&&o.push(i.command)}return[...new Set(o)].sort((i,r)=>i.localeCompare(r))}function Ke(e,t){let n=new Set,o=t??oe(e);for(let i of o){i.flag.startsWith("--")&&n.add(H(i.flag));for(let r of i.aliases??[])r.startsWith("--")&&n.add(H(r))}return[...n].sort((i,r)=>i.localeCompare(r))}function fl(e,t){if(!e.startsWith("--"))return[];let n=Tr(e);if(n.length===0)return[];let o=n.length>=8?2:1,i=[];for(let r of t){let a=Tr(r);if(a===n)continue;if(n.length>=3&&a.startsWith(n)){i.push({flag:r,rank:0,distance:a.length-n.length});continue}let s=tn(n,a,o);s===null||s<=0||i.push({flag:r,rank:1,distance:s})}return i.sort((r,a)=>r.rank!==a.rank?r.rank-a.rank:r.distance!==a.distance?r.distance-a.distance:r.flag.localeCompare(a.flag)).map(r=>r.flag).slice(0,3)}var Pt,gl=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function hl(){if(Pt)return Pt;let e=new Map;for(let t of gt)if(!gl.has(t))for(let n of Ke(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return Pt=e,Pt}function yl(e,t){if(!e.startsWith("--"))return[];let n=hl().get(H(e));if(!n)return[];let o=t?.trim().toLowerCase(),i=new Set(Ke(o));return[...new Set(n.filter(r=>r!==o).map(r=>({command:r,sharedFlagCount:Ke(r).filter(a=>i.has(a)).length})).sort((r,a)=>r.sharedFlagCount!==a.sharedFlagCount?a.sharedFlagCount-r.sharedFlagCount:r.command.localeCompare(a.command)).map(({command:r})=>B(r)?.canonical??r))]}function wl(e,t,n){for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--"))continue;let r=i.indexOf("="),a=r>=0?i.slice(0,r):i;if(H(a)!==H(t))continue;let s=[...e];return s[o]=r>=0?`${n}${i.slice(r)}`:n,s}}function _l(e){let t=new Set(e.commandPaths),n=r=>Math.min(Or(r,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Or(r,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,i=(r,a)=>{if(!Number.isFinite(a)||!t.has(r))return;let s=o.get(r);(s===void 0||a<s)&&o.set(r,a)};for(let r of e.commandPaths)i(r,n(r));for(let[r,a]of Object.entries(Xt))r!=="read"&&i(a,n(r));return[...o.entries()].sort(([r,a],[s,l])=>a!==l?a-l:r.localeCompare(s)).map(([r])=>r)}function vl(e){let t=B(e.normalizedUnknown),n=nr(e.commandPaths,e.primaryToken),o=_l(e),i=ul(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return _n([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...i],e.commandPaths,e.primaryToken).filter(r=>!e.normalizedUnknown.includes(" ")||r!==e.normalizedUnknown)}function bl(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function Cl(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 jn(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let i=F(o[1]);if(i.length===0)return;let r=ml(t,n);if(r.length===0)return;let a=pl(i);if(a&&!r.includes(a.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[a.installCommand,`pm ${a.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${i}" is provided by the "${a.packageAlias}" package. Install it with: ${a.installCommand}. Command after installation: pm ${a.canonicalPath}.`],suggestedRetryCommand:a.installCommand};let s=i.split(" ")[0],l=vl({commandPaths:r,normalizedUnknown:i,primaryToken:s,extensionDescriptors:n}),c=bl(r),d=(l.length>0?l:_n(c,r)).slice(0,3),m=Cl(d,l.length>0),p=l.length>0?`Did you mean: ${d.join(", ")}?`:null;return{unknownCommandExamples:m,unknownCommandNextSteps:[...p?[p]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...p?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function xl(e){return Array.from(new Set(e))}function kl(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 El(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 Sl(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(r=>r.trim().toLowerCase()===n))}function Je(e,t){if(t.length===0)return!0;let n=e;for(let[o,i]of t.entries()){let r=Sl(n,i);if(!r){let a=n.registeredArguments;return a.length>0&&(n.commands.length===0||a[0]?.required===!0)&&(a.at(-1)?.variadic===!0||t.length-o<=a.length)}n=r}return!0}async function Al(e,t,n,o){try{let i=R(process.cwd(),e.path);if(!await K(J(i)))return{allowedTypes:Be};let r=await D(i),a=e.noExtensions?void 0:se(),s=ae(r,a),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 wt(i,d,r.id_prefix,r.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Be,pmRoot:i,settings:r,typeToFolder:s.type_to_folder,verifiedCollectionItemId:l}}catch{return{allowedTypes:Be}}}function Ol(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?xl([...dl(t,n[1]),...fl(n[1],Ke(t))]):void 0,i=n?yl(n[1],t):[],r=n!==null&&Ke(t).includes(H(n[1]));return{match:n,suggestions:o,otherCommands:i,scope:r?"declared_on_path":i.length>0?"declared_elsewhere":"declared_nowhere"}}function Tl(e,t,n){if(!t||!n||n.length===0)return;let o=wl(e,t[1],n[0]);return o?Ln(o):void 0}function Rl(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?El(kl(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let i=x(t);if(i)return tr(t,i,[o])}function Il(e,t){if(!/too many arguments/i.test(e))return;let n=me(t),o=W(t.slice(n));if(o?.alias!=="schema")return;let i=n+o.canonical_argv.length-1,r=t[i+1]?.trim().toLowerCase(),a=t[i+2]?.trim().toLowerCase();if(!r||!a)return;let s=`${r}-${a}`;if(!Ar.includes(s))return;let l=[...t.slice(0,i+1),s,...t.slice(i+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${r} ${a}`,unknownSubcommandAllowedValues:[...Ar],suggestedRetryCommand:Ln(l)}}async function Ye(e,t,n,o={}){let r=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",a=He(process.argv.slice(2)).argv,s=U(a),l=me(a),c=W(a.slice(l))?.alias??x(a),d=Ln(a),m=X(a),p=await Al(s,r,a,c),u=p.allowedTypes,g=jn(r,t,n),h=Ol(r,c),y=Il(r,a),S=y?.suggestedRetryCommand??Tl(a,h.match,h.suggestions)??Rl(r,a);return{message:r,commandName:c,allowedTypes:u,attemptedCommand:d,normalizedInvocationArgs:[...a],providedOptionFlags:m,unknownOptionSuggestions:h.suggestions,unknownOptionOtherCommands:h.otherCommands.length>0?h.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:h.otherCommands.length>0?h.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:h.otherCommands.length>12||void 0,unknownOptionScope:h.scope,suggestedRetryCommand:S,verifiedCollectionItemId:p.verifiedCollectionItemId,...y,...g,...o}}async function Un(e,t,n,o={}){let i=await Ye(e,t,n,o),{message:r,commandName:a,allowedTypes:s,unknownCommandExamples:l,unknownCommandNextSteps:c,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:y,unknownOptionScope:S,unknownSubcommandPath:O,unknownSubcommandToken:G,unknownSubcommandAllowedValues:j,suggestedRetryCommand:ve,verifiedCollectionItemId:Yt,failedExtensions:ct}=i,De=xr(r,a,s,{unknownCommandExamples:l,unknownCommandNextSteps:c,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:y,unknownOptionScope:S,unknownSubcommandPath:O,unknownSubcommandToken:G,unknownSubcommandAllowedValues:j,suggestedRetryCommand:ve,verifiedCollectionItemId:Yt,failedExtensions:ct}),be=await di("help_format",{message:De,command:a,allowed_types:s});return be.handled&&typeof be.result=="string"?be.result:De}async function qn(e,t,n,o=!1,i={}){let r=await Ye(e,t,n,i),a=It(r.message,r.commandName,r.allowedTypes,f.USAGE,{unknownCommandExamples:r.unknownCommandExamples,unknownCommandNextSteps:r.unknownCommandNextSteps,attemptedCommand:r.attemptedCommand,normalizedInvocationArgs:r.normalizedInvocationArgs,providedOptionFlags:r.providedOptionFlags,unknownOptionSuggestions:r.unknownOptionSuggestions,unknownOptionOtherCommands:r.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:r.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:r.unknownOptionOtherCommandsTruncated,unknownOptionScope:r.unknownOptionScope,unknownSubcommandPath:r.unknownSubcommandPath,unknownSubcommandToken:r.unknownSubcommandToken,unknownSubcommandAllowedValues:r.unknownSubcommandAllowedValues,suggestedRetryCommand:r.suggestedRetryCommand,verifiedCollectionItemId:r.verifiedCollectionItemId,failedExtensions:r.failedExtensions}),s=o?Tt(a):a,l=U(r.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(l?ce(s,c=>`${JSON.stringify(c,null,2)}
21
+ `):s,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]="939abfaf-7563-5490-bd76-90d188aa0940")}catch{}})();async function Ir(e,t,n,o){if(n)return null;let i=e.some(a=>a==="--for"||a.startsWith("--for=")),r=x(e)==="contracts"&&e.includes("--full");return i||r?await o(t):null}import{Option as Pl}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]="2f731313-580e-5554-bf61-f160121a298b")}catch{}})();function v(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function $r(e,t){let n=new Map;for(let o of e){let i=v(o.command);for(let r of t){if(r.layer!==o.layer||r.name!==o.name)continue;let a=v(r.command),s=a.split(" "),l=s.at(-1),c=s.slice(1).join(" "),d=c?`${s[0]}-${l} ${c}`:`${s[0]}-${l}`;if(l&&i===d){n.set(i,a);break}}}return n}function Hn(e,t,n,o){if(!t||!n)return;let i,r=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>r&&p.every((u,g)=>c[g]===u)&&(i=m,r=p.length)}}let a=i?.flags.find(s=>s.long===n||s.short===n);if(a)return $t(a).takesValue}function $(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ee(e){return typeof e=="boolean"?e:void 0}function $t(e){let t=$(e.value_type)??$(e.type),n=$(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||ee(e.required)===!0||ee(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function $l(e){if(ee(e.visible)===!1)return null;let n=$(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=$(e.short),i=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",r=$(e.value_name),a=r?` <${r}>`:"",s=$(e.description)??"Extension-provided option.",l=[];ee(e.required)===!0&&l.push("required"),ee(e.enabled)===!1&&l.push("disabled");let c=l.length>0?` [${l.join(", ")}]`:"";return`${i}${n}${a} ${s}${c}`}function Nr(e){let t=[...new Set(e.map($l).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 Nr(e){let t=new Map;for(let i of e){let r=v(i.target_command);if(r.length===0)continue;let a=t.get(r)??[];a.push(...i.flags),t.set(r,a)}let n=[...t.entries()].sort(([i],[r])=>i.localeCompare(r)),o=new Map;for(let[i,r]of n){let a=$r(r);a&&o.set(i,a)}return o}function Dr(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Ir(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let i=o.trim();i.length===0||n.has(i)||(n.add(i),t.push(i))}return t}function Il(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 Pl(e){let t=new Map;for(let n of e){let o=v(n.command);if(o.length===0)continue;let i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,r=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:Dr(o,n.action),description:i,intent:r,examples:Ir(n.examples),failure_hints:Ir(n.failure_hints),arguments:Il(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 $l(e){let t=new Map;for(let n of e){let o=v(n.target_command);if(o.length===0)continue;let i=t.get(o)??[];i.push(...n.flags),t.set(o,i)}return t}function Nl(e,t,n){let o=new Set;for(let i of e){let r=v(i);r.length>0&&o.add(r)}for(let i of t.keys())o.add(i);for(let i of n.keys())o.add(i);return o}function Dl(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function Mr(e,t,n,o=new Map){let i=Pl(t),r=$l(n),a=Nl(e,i,r),s=new Map,l=[...a].sort((c,d)=>c.localeCompare(d));for(let c of l){let d=Dl(c,i,o)??i.get(c),m=r.get(c)??(d?r.get(d.command):void 0)??[];if(d){s.set(c,{...d,command:c,flags:m});continue}s.set(c,{command:c,action:Dr(c,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function Ml(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function Fr(e,t){for(let n of t.arguments)e.argument(Ml(n),n.description??"Extension argument.")}function Lr(e){if(ee(e.visible)===!1)return null;let n=P(e.long),o=P(e.short),i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=n&&n.startsWith("--")&&n.length>2?n:null,a=[i,r].filter(s=>s!==null);return a.length>0?a:null}function Fl(e){let t=Lr(e);if(!t)return null;let{valueName:n}=Pt(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Ll(e){let t=Lr(e);if(!t)return null;let{valueName:n}=Pt(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function jr(e){let t=P(e.description)??"Extension-provided option.",n=[];ee(e.required)===!0&&n.push("required"),ee(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function Ur(e,t){let n=P(t.long),o=P(t.short);return e.options.some(i=>{let r=i;return n!==null&&r.long===n||o!==null&&r.short===o})}function zn(e,t){for(let n of t){if(Ur(e,n))continue;let o=Ll(n);if(!o)continue;let i=jr(n),r=new Ol(o,i);if(r.negate=!1,n.list!==!0){e.addOption(r);continue}e.addOption(r.argParser((a,s=[])=>[...Array.isArray(s)?s:[s],a]))}}function Gn(e,t){return $r(t.filter(n=>!Ur(e,n)))}function jl(e){let t=Fl(e);if(!t)return null;let n=P(e.long),o=P(e.short),i=n&&n.startsWith("--")&&n.length>2?n:null,r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:a,valueName:s}=Pt(e),l=ee(e.required)===!0;return{flags:t,long:i,short:r,description:jr(e),takes_value:a,value_required:a,value_name:s,variadic:!1,required:l,aliases:[],alias_for:null}}function qr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let i=jl(o);!i||n.has(i.flags)||(n.add(i.flags),t.push(i))}return t}function Hr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(i=>i.flags));for(let i of t)o.has(i.flags)||(o.add(i.flags),n.push(i));return n}function zr(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 Dr(e){let t=new Map;for(let i of e){let r=v(i.target_command);if(r.length===0)continue;let a=t.get(r)??[];a.push(...i.flags),t.set(r,a)}let n=[...t.entries()].sort(([i],[r])=>i.localeCompare(r)),o=new Map;for(let[i,r]of n){let a=Nr(r);a&&o.set(i,a)}return o}function Mr(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Pr(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let i=o.trim();i.length===0||n.has(i)||(n.add(i),t.push(i))}return t}function Nl(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 Dl(e){let t=new Map;for(let n of e){let o=v(n.command);if(o.length===0)continue;let i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,r=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:Mr(o,n.action),description:i,intent:r,examples:Pr(n.examples),failure_hints:Pr(n.failure_hints),arguments:Nl(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 Ml(e){let t=new Map;for(let n of e){let o=v(n.target_command);if(o.length===0)continue;let i=t.get(o)??[];i.push(...n.flags),t.set(o,i)}return t}function Fl(e,t,n){let o=new Set;for(let i of e){let r=v(i);r.length>0&&o.add(r)}for(let i of t.keys())o.add(i);for(let i of n.keys())o.add(i);return o}function Ll(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function Fr(e,t,n,o=new Map){let i=Dl(t),r=Ml(n),a=Fl(e,i,r),s=new Map,l=[...a].sort((c,d)=>c.localeCompare(d));for(let c of l){let d=Ll(c,i,o)??i.get(c),m=r.get(c)??(d?r.get(d.command):void 0)??[];if(d){s.set(c,{...d,command:c,flags:m});continue}s.set(c,{command:c,action:Mr(c,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function jl(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function Lr(e,t){for(let n of t.arguments)e.argument(jl(n),n.description??"Extension argument.")}function jr(e){if(ee(e.visible)===!1)return null;let n=$(e.long),o=$(e.short),i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=n&&n.startsWith("--")&&n.length>2?n:null,a=[i,r].filter(s=>s!==null);return a.length>0?a:null}function Ul(e){let t=jr(e);if(!t)return null;let{valueName:n}=$t(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function ql(e){let t=jr(e);if(!t)return null;let{valueName:n}=$t(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Ur(e){let t=$(e.description)??"Extension-provided option.",n=[];ee(e.required)===!0&&n.push("required"),ee(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function qr(e,t){let n=$(t.long),o=$(t.short);return e.options.some(i=>{let r=i;return n!==null&&r.long===n||o!==null&&r.short===o})}function zn(e,t){for(let n of t){if(qr(e,n))continue;let o=ql(n);if(!o)continue;let i=Ur(n),r=new Pl(o,i);if(r.negate=!1,n.list!==!0){e.addOption(r);continue}e.addOption(r.argParser((a,s=[])=>[...Array.isArray(s)?s:[s],a]))}}function Gn(e,t){return Nr(t.filter(n=>!qr(e,n)))}function Hl(e){let t=Ul(e);if(!t)return null;let n=$(e.long),o=$(e.short),i=n&&n.startsWith("--")&&n.length>2?n:null,r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:a,valueName:s}=$t(e),l=ee(e.required)===!0;return{flags:t,long:i,short:r,description:Ur(e),takes_value:a,value_required:a,value_name:s,variadic:!1,required:l,aliases:[],alias_for:null}}function Hr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let i=Hl(o);!i||n.has(i.flags)||(n.add(i.flags),t.push(i))}return t}function zr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(i=>i.flags));for(let i of t)o.has(i.flags)||(o.add(i.flags),n.push(i));return n}function Gr(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 Wn(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 Ye(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Wn(o).includes(n))??null}function te(e,t){let n=e;for(let o of t){let i=Ye(n,o);if(!i)return null;n=i}return n}var Bn=new WeakSet;function Gr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];o>0&&F.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let r=Ye(n,i);if(r){n=r;continue}let a=n.command(i);Bn.add(a),o<t.length-1?(a.description("Extension-provided command group."),a.action(()=>{a.help()})):a.description("Extension-provided command path."),n=a}return n}function Ul(e,t){let n=t.join(" "),o=F.find(a=>n===a.canonical||n.startsWith(`${a.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let i=e,r=[];for(let a of t){let s=Ye(i,a);if(!s)return null;r.push(a);let l=s.commands.length>0||F.some(c=>c.canonical.startsWith(`${r.join(" ")} `));if(!Bn.has(s)&&(r.length===t.length||!l))return{core_path:r.join(" "),extension_path:t.join(" ")};i=s}return null}function ql(e,t,n,o,i=!1){let r=t.split(" ").filter(d=>d.length>0),a=Ul(e,r),s=te(e,r),l=F.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Bn.has(s)));if(!a||a.core_path===t&&s!==null&&!n.has(t)&&!i||l&&!n.has(t))return null;let c=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${c}`}function Wr(e,t,n,o,i){return[...new Set([...t,...n.keys()])].filter(r=>r.trim().length>0).sort((r,a)=>r.localeCompare(a)).filter(r=>{let a=ql(e,r,o,n.get(r),t.includes(r));return a?(i(a),!o.has(r)&&te(e,r.split(" "))!==null):!0})}function Br(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]="93ca07c1-857b-57ae-8530-a315a24d0fe5")}catch{}})();var Hl=new Set(["__proto__","prototype","constructor"]),Vr=Symbol("looseOptionOccurrences");function Xe(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function zl(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 Vn(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let a=n.indexOf("=");if(a>=0)return{consumed:1,key:n.slice(1,a).trim(),value:n.slice(a+1)};let s=n.slice(1).trim(),l=e[t+1];return typeof l=="string"&&!l.startsWith("-")?{consumed:2,key:s,value:l}:{consumed:1,key:s,value:!0}}let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(2,o).trim(),value:n.slice(o+1)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let i=n.slice(2).trim(),r=e[t+1];return typeof r=="string"&&!r.startsWith("-")?{consumed:2,key:i,value:r}:{consumed:1,key:i,value:!0}}function $t(e){return Hl.has(e)}function Kr(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Jo(t)}function Ze(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let i=Xe(n.slice(2));i.length>0&&!$t(i)&&t.push(i)}if(o.startsWith("-")&&!o.startsWith("--")){let i=Xe(o.slice(1));i.length>0&&!$t(i)&&t.push(i)}return[...new Set(t)]}function Jr(e){let t=new Set;for(let n of e)for(let o of Ze(n))t.add(o);return t}function Gl(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=Xe(t.slice(2));if(n.length>0&&!$t(n))return n}return Ze(e)[0]??null}function Wl(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 Kn(e,t,n){if(t.length===0)return;let o=new Set,i=new Map,r=[],a=[];for(let s of t){let l=Ze(s),c=Wl(s);c!==null&&a.push(c);for(let d of l)o.add(d),s.enabled===!1&&i.set(d,c);s.required===!0&&s.enabled!==!1&&l.length>0&&r.push({keys:l,label:c})}for(let s of Object.keys(e)){if(!o.has(s)){let c=a.length>0?` Expected one of: ${[...new Set(a)].join(", ")}.`:"";throw new C(`Unknown option '--${s}' for extension command '${n}'.${c}`,f.USAGE)}let l=i.get(s);if(l)throw new C(`Option '${l}' is disabled for extension command '${n}'.`,f.USAGE)}for(let s of r)if(!s.keys.some(l=>Object.hasOwn(e,l)))throw new C(`Missing required option '${s.label}' for extension command '${n}'.`,f.USAGE)}function Bl(e){return typeof e=="string"||e==null?e:String(e)}function Vl(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 Kl(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 Jl={string:Bl,number:Vl,boolean:Kl};function Nt(e,t){return Array.isArray(e)?e.map(n=>Nt(n,t)):Jl[t](e)}function Yr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(i=>i!=null&&i!==""):Yo(e);return t?o.map(i=>Nt(i,t)):o}function Yl(e,t,n,o){return n?Yr(e,t,o):t?Nt(e,t):e}function Xl(e,t,n){let o=e[Vr];if(!o||o.length===0)return n;let i=new Set(t);return o.filter(r=>i.has(r.key)).map(r=>r.value)}function Xr(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[i,r]of Object.entries(e))o[i]=r;for(let i of t){let r=Gl(i);if(!r)continue;let a=i.list===!0,s=Ze(i);for(let d of s)if(!(d===r||!Object.hasOwn(o,d))){if(Object.hasOwn(o,r)){if(!a){delete o[d];continue}let m=o[r],p=o[d];o[r]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[d];continue}o[r]=o[d],delete o[d]}let l=Kr(i),c=i.repeatable===!0;if(!Object.hasOwn(o,r)){i.default!==void 0&&(o[r]=Yl(i.default,l,a,c));continue}if(a){o[r]=Yr(Xl(n,s,o[r]),l,c);continue}l&&(o[r]=Nt(o[r],l))}return o}function Zr(e){let t=Object.create(null),n=[];Object.defineProperty(t,Vr,{value:n});let o=0;for(;o<e.length;){let i=Vn(e,o);if(!i){o+=1;continue}let r=Xe(i.key);if(r.length===0||$t(r)){o+=i.consumed;continue}zl(t,r,i.value),n.push({...i,key:r}),o+=i.consumed}return t}function Qr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=Vn(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function Jn(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let a of t){let s=Kr(a);for(let l of Ze(a))n.add(l),s==="boolean"&&o.add(l)}if(n.size===0)return[...e];let i=[],r=0;for(;r<e.length;){if(e[r]==="--"){i.push(...e.slice(r+1));break}let a=Vn(e,r);if(a){let s=Xe(a.key);if(n.has(s)){let l=e[r],c=o.has(s)&&!l.includes("=")?1:a.consumed;r+=c;continue}}i.push(e[r]),r+=1}return i}import Ae 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]="989fc265-7deb-5456-8a83-0f1fa8d2d9b2")}catch{}})();async function Yn(e,t={},n=[]){let o={readSettings:N,loadExtensions:Me,activateExtensions:Fe,resolveImplicitPmRoot:en,...t};try{let i=await o.readSettings(e),r=await o.loadExtensions({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(r);return[...r.failed,...a.failed].map(s=>{let l=(r.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,g)=>p.length>0&&g.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(i){return[{layer:"runtime",name:"extension-loader",error:i instanceof Error?i.message:String(i)}]}}async function ea(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await Yn(t,n,o),r={readSettings:N,loadExtensions:Me,activateExtensions:Fe,resolveImplicitPmRoot:en,...n};try{let a=r.resolveImplicitPmRoot(process.cwd());if(Ae.resolve(a)===Ae.resolve(t))return i;let[s,l]=await Promise.all([r.readSettings(t),r.readSettings(a)]),[c,d]=await Promise.all([r.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),r.loadExtensions({pmRoot:a,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,g)=>u.localeCompare(g));if(p.length===0)return i;i.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Ae.resolve(t)} extension_discovery_root=${c.roots.project}; cwd_storage_root=${Ae.resolve(a)} 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 ${Ae.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${Ae.resolve(t)} install <package> --project".`})}catch{}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6fa59b21-fcd4-5056-ae4c-379d57bb7757")}catch{}})();var ta={core:0,standard:1,full:2,internal:3};function na(e,t,n=!0){let o=t.get(O(e));if(o)return o;if(!n)return;let i=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(i.length===0)return;let r=i.reduce((s,l)=>ta[l.tier]<ta[s]?l.tier:s,"internal"),a=new Set(i.map(({family:s})=>s));return{tier:r,family:a.size===1?i[0].family:"extensions"}}function oa(e,t){if(t.length===0)return e;let n=te(e,t);if(n)return n;let o=t.join(" ");if(O(o)!==o||!ft.some(i=>i===o)&&!Ti(o)&&!je(o)&&!Ke(e,t))return null;for(let i=t.length-1;i>0;i-=1){let r=te(e,t.slice(0,i));if(r)return r}return t.length===1?e:null}function Zl(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function ia(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 Ql(e){let t=new Map;for(let n of e){let o=n,i=ia(n);if(!i||typeof o.long!="string"||o.long.trim().length===0)continue;let r=t.get(i)??[];r.push(o.long.trim()),t.set(i,r)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(i=>i.trim()).filter(i=>i.length>0))].sort((i,r)=>i.localeCompare(r)));return t}function ec(e){return k(e)}function tc(e){let t=e.options??[],n=Ql(t);return t.map(o=>{let i=o,r=typeof i.flags=="string"?i.flags.trim():"",a=typeof i.description=="string"?i.description.trim():"",s=ia(o),c=(s?n.get(s)??[]:[]).filter(y=>y!==i.long).map(y=>y.trim()).filter(y=>y.length>0),d=a.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,p=i.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),u=r.includes("<"),g=u||r.includes("["),h={flags:r,long:typeof i.long=="string"?i.long:null,short:typeof i.short=="string"?i.short:null,description:a,takes_value:g,value_required:u,value_name:Zl(r),variadic:i.variadic===!0,required:p,aliases:c,alias_for:m};return i.defaultValue!==void 0&&(h.default_value=i.defaultValue),h})}function nc(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let i=o.alias_for,r=t.get(i);if(!r)continue;let a=o.long,s=new Set([...r.aliases??[],a]);r.aliases=[...s].sort((l,c)=>l.localeCompare(c))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function oc(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let i=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",r=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:i.trim(),required:o.required===!0||r?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:r}})}function ic(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(r=>r.name()!=="help"||e.parent===null).filter(r=>!n||(pe(r)??Y(r.name()))!=="internal").map(r=>{let a=M(E(r)),s=a,l=pe(r),c=na(a,t,l!==void 0),d=B.find(({alias:m})=>m===a);return{name:r.name().trim(),aliases:Wn(r),description:r.description().trim(),tier:c?.tier??l??Y(s),family:c?.family??bt(s),...d?{alias_for:d.canonical,alias_lifecycle:d.lifecycle,...d.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((r,a)=>r.name.localeCompare(a.name))}function rc(e,t,n){if(!n)return t;let o=n.examples??[],i=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?i.length>0?[...i]:[...t.tips]:[],detail_mode:e}}function ac(e,t,n,o,i){let r=e!==void 0&&xn(e)===ke,a=r?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:mr(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":r?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:rc(n,a,o),intentSource:s}}function sc(e,t){return e===void 0?null:t?.tier??Y(e)}function lc(e,t){return e===void 0?null:t?.family??bt(e)}function cc(e,t,n){if(!(t!==e||!n))return B.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:oa(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function dc(e,t,n,o,i=new Map,r=!1){if(!e){let s=oc(t),l=ic(t,i,r),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:Y(n.split(" ")[0]),family:bt(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 a=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&&a.has(s)||l.some(c=>a.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 mc(e,t,n,o,i){let r=Cn(n),a=oe(n),s=M(E(t)),l=M(o.join(" ")),c=l.length>s.length?l:s,d=je(c),m=d?.command??s,p=m.length>0?m:void 0,u=p,g=p?i.get(O(p)):void 0,h=p?na(p,i,pe(t)!==void 0):void 0,{narrative:y,intentSource:S}=ac(p,t.description().trim(),r,g,d!==void 0),T=nc(Hr(tc(t),qr(g))),G=dc(d,t,m,T,i,a),j=cc(e,t,a);return{format:"pm_help_v1",detail_mode:r,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:sc(u,h),capability_family:lc(u,h),description:d?.description??t.description(),usage:G.usage,intent:d?.description??y.intent,intent_source:S,examples:d?[d.example]:y.examples,tips:d?[_t(d.accepted_flags)]:y.tips,arguments:G.arguments,options:G.options,subcommands:G.subcommands,has_subcommands:G.subcommands.length>0,...j===void 0?{}:{command_aliases:j}}}async function ra(e,t,n,o=t){let i=U(t);if(!i.json)return!1;let r=A(t);if(!r.requested)return!1;let a=oa(e,r.commandPathTokens);if(!a){if(!i.quiet){let s=`unknown command '${O(r.commandPathTokens.join(" "))}'`,l=jn(s,e,n),c=Rt(s,"help",Be,f.USAGE,{...l,attemptedCommand:ec(t),normalizedInvocationArgs:[...t],providedOptionFlags:X(t)}),d=i.tokenAccounting?le(c,m=>`${JSON.stringify(m,null,2)}
28
- `):c;be(`${JSON.stringify(d,null,2)}
29
- `)}return process.exitCode=f.USAGE,!0}if(!i.quiet){let s=mc(e,a,t,r.commandPathTokens,n),l=A(o).commandPathTokens;s.requested_path=l;let c=V(l.join(" "));c&&(s.resolved_path=c.canonical),a===e&&!oe(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),_i(`${JSON.stringify(s,null,2)}
30
- `)}return process.exitCode=f.SUCCESS,!0}function pc(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 uc(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",i=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${i.length>0?i.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function fc(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let i of[...t.required_create_fields,...t.required_create_repeatables])o.add(i);return{progressive:n,strict:o}}function gc(e,t,n,o){let i=new Set(n),r=o.filter(l=>!i.has(l)),a=l=>l.length>0?l.map(c=>Qt("create",c)).join(", "):"none";e.push(` required in strict mode: ${a(r)}`);let s=r.map(Xi).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 hc(e,t,n){let o=Ri(n);if(!o)return pc(e,t);let i=Wo(o,t);if(!i){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
32
- `)}let r=n.indexOf("--"),a=r<0?n:n.slice(0,r),s=a.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),l=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],c=e==="create"&&l?.toLowerCase()==="strict",d=fc(e,i),m=dt(i,e,d.progressive),p=dt(i,e,c?d.strict:d.progressive),u=h=>h.length>0?h.map(y=>Qt(e,y)).join(", "):"none",g=["",`Type-aware option policies for ${i.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=dt(i,e,d.strict);gc(g,i,m.required,h.required)}return uc(g,i),p.errors.length>0&&g.push(` config errors: ${p.errors.join("; ")}`),g.join(`
33
- `)}function aa(e,t,n){let o=x(n);if(o!=="create"&&o!=="update")return;let i=Ye(e,o);i&&i.addHelpText("after",hc(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]="840b471e-c996-57e2-b97c-3a84bd68f050")}catch{}})();function yc(e,t){let n=De(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function wc(e){return De(e.status)?.toLowerCase()??"pending"}function _c(e){return e.mandatory===!0}function vc(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 ca(e){let t=[];return e.forEach((n,o)=>{if(!_c(n.definition))return;let i=wc(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:yc(n.definition,o),status:i})}),t.sort(vc),t}function sa(e){return Array.isArray(e)&&e.length>0}var bc=new Set(["create","beads import","todos import"]),Cc=new Set(["restore","update","close","delete","append","claim","release"]),xc=new Set(["comments","notes","learnings"]),kc=new Set(["files","docs","test"]),Ec=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 Xn(e,t){let n=t.force===!0;return bc.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Cc.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:xc.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:kc.has(e)?{isMutation:sa(t.add)||sa(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function Sc(e,t,n){if(Xn(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return ji(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>Ec.has(i.trim().toLowerCase())):!1}function la(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Ac(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let i=[];if(De(t[1])||i.push("source"),De(n.to)||i.push("--to"),i.length!==0)throw new C(`Schema migration requires ${i.join(", ")}.`,f.USAGE,{code:"schema_migration_input_required",required:i.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:i,suggested_flags:i.filter(r=>r.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function Tc(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||la(n.status)!==la(i.schema.workflow.in_progress_status))return;let r=t[0];if(!r)return;let a=re(i,ae()),s=await yt(o,r,i.id_prefix,i.item_format,a.type_to_folder);if(!s)return;let l=await Ei(s,{schema:i.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 Zn(e,t,n,o,i){if(!Sc(e,t,n)||(Ac(e,t,n),!await K(J(i))))return;let r=await Ce(i);o.json!==!0&&await Tc(e,t,n,i,r.settings);let a=Li({author:gt(o.author,r.settings.author_default),payload:{command:e,args:t,options:n},settings:r.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)_(`warning:${s}`)}function da(e,t,n){if(n.length===0)return;let o=Xn(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let i=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),r=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 (${i.join(",")}). ${r}`,f.CONFLICT)}async function Qn(e,t,n,o){if(!Xn(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await K(J(n)))return;let{settings:r,metadata:a,warnings:s}=await Ce(n);for(let l of s)_(`warning:${l}`);if(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(xi(r),await ki(n,r,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let l=re(r,ae());await Ui(n,r.item_format,"item_format:pre_mutation_sync",l.type_to_folder,r.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]="697f96fe-38a0-5530-b54b-22cb442c130f")}catch{}})();function eo(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=v(n);o.length!==0&&t.push(o)}return t}function Oe(e){let t=v(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(i=>i.length>0);for(let i of eo(e.commandArgs))o.push(...i.split(" ").filter(r=>r.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,O(i)]))]}function to(e,t){let n=v(e);if(n.length===0)return!1;let o=Oe(t);for(let i of o)if(i===n||i.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(i=>n.startsWith(`${i} `)):!1}function Mt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...I(n.commands),...I(n.command_handlers),...I(n.command_overrides),...I(n.flag_commands),...I(n.parser_overrides),...ma(n.preflight_ownership),...ma(n.renderer_ownership)]:[]}function I(e){return e??[]}function ma(e){return I(e).flatMap(t=>t.commands)}function Qe(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var pa=new Set(["hooks","parser","preflight","renderers"]),ua=new Set(["commands","schema","services","importers"]),Oc=new Set(["reindex","search","search-advanced"]),Rc=new Set(["--template"]);function Te(e,t){for(let n of t)if(e.has(n))return!0;return!1}function no(e){let t=v(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Oc.has(n??t)}function oo(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 Ft(e){return v(e.commandPath??"")==="create"&&oo(e,Rc)}function io(e){return e.some(t=>{let n=v(t);return n==="templates"||n.startsWith("templates ")})}function Dt(e,t){return e.some(n=>to(n,t))||Ft(t)&&io(e)}function ro(e){return[I(e.hooks).length,(e.preflight_overrides??0)-I(e.preflight_ownership).length,I(e.item_types).length,I(e.item_fields).length,I(e.relationship_kinds).length,I(e.service_overrides).length,I(e.assurance_providers).length,I(e.renderer_overrides).length-I(e.renderer_ownership).length].some(n=>n>0)}function ao(e,t){let n=e.activation?.commands??[];if(n.length>0)return Dt(n,t);let o=Mt(e);if(Dt(o,t)||Qe(e).has("search")&&no(t.commandPath))return!0;if(e.contributions)return ro(e.contributions)}function Lt(e,t){let n=ao(e,t);if(n!==void 0)return n;let o=Qe(e);return!!(Te(o,pa)||Te(o,ua))}function et(e,t){return e.effective.length===0?!1:tt(t)!=="all"?e.effective.some(o=>Lt(o,t)):e.effective.some(o=>{let i=Qe(o);return Mt(o).length>0||Te(i,pa)||Te(i,ua)||i.has("search")})}function tt(e){if(v(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=Oe(e).filter(i=>i.split(" ").every(r=>!r.startsWith("-"))).sort((i,r)=>r.length-i.length)[0]??v(e.commandPath??"");if(t.length===0)return"all";let n=Ft(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function so(e){return tt(e)==="all"?void 0:t=>Lt(t,e)}function Re(e){let t=A(e);if(t.requested&&t.commandPathTokens.length>0){let[i,...r]=t.commandPathTokens;return{commandPath:i,commandArgs:r,allowCommandPrefixMatch:!0}}let n=D(e),o=n.findIndex(i=>i.trim().length>0&&!i.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function lo(e){let t=e.args.map(String);if(v(E(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.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]="2b424635-df90-55ee-beb0-d39a79d242f3")}catch{}})();var jt=Symbol.for("pm.readOutputInvocationProvenance");function ie(e,t){let n=Reflect.get(e,jt);n!==void 0&&Reflect.set(t,jt,n)}function co(e,t,n){let o=ui(t,n);if(!o)return;let i=e;for(;i.parent;)i=i.parent;let r=i.rawArgs,a=new Set(X(r.slice(2))),s=pi.find(d=>d.command===o),l=Object.values(s.dimensions).flatMap(d=>d.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),c=Reflect.get(n,jt);Reflect.set(n,jt,{canonical_include_modes:c?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),ie(n,e)}function mo(e,t,n,o){co(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:r,modes:a}=hi(t,i,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;ie(o,e);let s=gi(t);for(let c of a){let d=s.get(c),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let l=r.length>0?r.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");xt(e,n)}function Ic(e){let t=e.optsWithGlobals(),n=E(e);if(O(n)===n)return t;let o=e.opts();for(let i=e.parent;i?.parent;i=i.parent)for(let r of Object.keys(i.opts()))!(r in o)&&i.getOptionValueSource(r)==="default"&&delete t[r];return t}function Ie(e,t,n=[]){let i={...Ic(e)};ie(e,i),delete i.json,delete i.quiet,delete i.path,delete i.pmPath,delete i.noExtensions,delete i.extensions,delete i.profile,delete i.pager,delete i.changedFields,delete i.fullChangedFields,delete i.idOnly,delete i.lean,delete i.tokenAccounting,delete i.outputInclude,delete i.outputLimit,delete i.outputBudget,delete i.outputFormat,delete i.outputSession;let r=Zr(t);for(let[a,s]of Object.entries(r))i[a]===void 0&&(i[a]=s);if(n.length>0){let a=Jr(n),s=xe(E(e)).map(d=>({long:d.flag,short:d.short,aliases:d.aliases})),l={...r};for(let d of a)i[d]!==void 0&&(l[d]=i[d]);Kn(l,[...s,...n],E(e));let c=Xr(i,n,r);return ie(i,c),c}return i}function Ut(e,t){let n=v(t);return n.length===0?[]:e.flags.filter(o=>O(v(o.target_command))===O(n)).flatMap(o=>o.flags)}function nt(e,t,n){let o=Ut(e,t),i=[t],r=[];for(let a of n){if(a.startsWith("-"))break;i.push(a);let s=Ut(e,i.join(" "));s.length>0&&(r=s)}return r.length>0?r:o}function qt(e){return e.arguments??[]}function fa(e){let t=qt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function po(e,t){if(!e)return!1;let n=v(t);return e.importers.some(o=>v(`${o.importer} import`)===n)||e.exporters.some(o=>v(`${o.exporter} export`)===n)}function uo(e,t){let n=qt(e),o=n.filter(l=>l.required).length,r=n.some(l=>l.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new C(`Missing required argument for extension command '${e.command}'. Usage: ${fa(e)}${s}`,f.USAGE);if(t.length>r){let l=t.slice(r).join(" ");throw new C(`Too many arguments for extension command '${e.command}': ${l}. Usage: ${fa(e)}${s}`,f.USAGE)}}function Pc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function $c(e,t,n){if(n.length>0){Kn(t,n,e.command);return}let o=Object.keys(t).filter(i=>t[i]!==void 0).sort();if(o.length!==0)throw new C(`Unknown option '${o.map(Pc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,f.USAGE)}function fo(e,t,n,o){e&&(uo(e,t),$c(e,n,o))}import{Command as Nc}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]="47557320-4bb4-5120-82db-a0b98af6ccf3")}catch{}})();var Dc=new Set(["--version","-V"]);function ot(e){let t=D(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function ga(e){if(D(e)[0]!=="item"||!e.includes("--dry-run"))return;let n=new Nc().configureOutput({writeErr:()=>{}}).exitOverride(),o=new Set;for(let r of Ue)for(let a of[r.flag,r.short,...r.aliases??[]]){if(a===void 0||o.has(a))continue;o.add(a);let s=r.value_name!==void 0||r.flag==="--pm-path";n.option(`${a}${s?" <value>":""}`)}try{n.parseOptions(e)}catch{}let i=n.opts();return{path:i.pmPath??i.path}}var Mc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),go=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"]),ha=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"]),Fc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Lc=new Set(["claim","close-task","pause-task","release","start-task","test"]),Ht={setup:!0,listQuery:!0,mutation:!0,operation:!0},jc=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=>Dc.has(t))}function ho(e){if(it(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||A(e).requested)return Ht;let t=x(e);if(!t)return Ht;let n=t.trim().toLowerCase(),o=D(e),i=W(o)?.alias;return F.some(r=>r.alias===i)?{...Ht,targetCommandName:i}:Mc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:go.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:ha.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Fc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:Ht}function yo(e){return e.length===0||A(e).requested||e.includes("--explain")&&x(e)===void 0}function wo(e,t){return ot(t)||it(t)?!1:oe(t)||A(t).requested?!0:!!x(t)}function _o(e){if(it(e))return!1;let t=x(e);return t?jc.has(t):!1}function Uc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,i=e.normalizedTokens.map(c=>{let d=c.indexOf("=");return d>=0?c.slice(0,d):c}).find(c=>c==="--literal"||c==="--regex"||c==="--replacement"),r=i?e.argv.map(c=>{let d=c.indexOf("=");return(d>=0?c.slice(0,d):c)===o?d>=0?`${i}${c.slice(d)}`:i:c}):e.argv,a=Le(r),s=i&&n>=0?`${o}=[redacted]`:t,l=i&&e.normalizedDisplay.includes("=")?`${i}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:l,sourceDisplay:s}}function vo(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),i=o.length>0?o.join(" "):"the canonical flag",r=ha.has(t)||Lc.has(t),a=r?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=r?"mutating option":"option",l=Uc({argv:e.argv,normalizedDisplay:i,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.`,f.USAGE,{code:a,examples:[k(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:k(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]="afcf2608-3360-5030-b5ea-b101df5829e7")}catch{}})();var qc=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"]),Hc=new Set(["parse","preflight","execute","unknown"]),zc=new Set(["usage","validation","conflict","runtime","unknown"]);function he(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let i=o.trim();if(i.length>0)return i}}}function bo(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function zt(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 Co(e){if(!e)return;let t=e.trim().toLowerCase();if(qc.has(t))return t}function xo(e){if(!e)return;let t=e.trim().toLowerCase();if(Hc.has(t))return t}function ko(e){if(!e)return;let t=e.trim().toLowerCase();if(zc.has(t))return t}function Eo(e){let t=he(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(bo(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let i=zt(e,"failed");if(typeof i=="number"&&i>0)return`failed_runs:${i}`;let r=e?.run_results;if(Array.isArray(r)){let a=r.filter(s=>Zt(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function So(e,t){if(!e)return t===f.USAGE?"invalid_command_usage":t===f.NOT_FOUND?"item_not_found":t===f.CONFLICT?"lock_conflict":t===f.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function Ao(){let e=Zt(se()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=zt(e,"exit_code","exitCode"),o=t??n??f.SUCCESS,i=Vi(o),r=he(e,"error_code","errorCode")??So(i,o),a=ko(he(e,"error_category","errorCategory"))??(i?void 0:ct(r)),s=i?void 0:Eo(e)??`command_exit_${o}`,l=Co(he(e,"command_resolution","commandResolution"))??vt({ok:i,errorCode:r,errorCategory:a}),c=xo(he(e,"resolution_stage","resolutionStage"))??"execute";return{ok:i,error:s,exit_code:o,error_code:r,error_category:a,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]="a441a914-7d0e-5ed4-8bb9-8b94c540f0a1")}catch{}})();var To="PM_CLI_PACKAGE_ROOT",xa=Symbol("pm.deprecatedAliasInvocation"),Bt=new Map;for(let e of B){let t=e.alias.split(" ")[0],n=Bt.get(t)??[];n.push(e),Bt.set(t,n)}for(let e of Bt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function Gc(){return Ho(import.meta.url,["../.."])}(typeof process.env[To]!="string"||process.env[To]?.trim().length===0)&&(process.env[To]=Gc());var Pe=null,L=null;function Wc(e){Pe=e}function Bc(e){$=e}var rt=null,ye=null,$=new Map,Do=250,Vc=new Set([f.USAGE,f.NOT_FOUND,f.CONFLICT]),Kc=new Set(["1","true","yes","on"]),Jc=Ge(()=>import("./chunks/register-setup-BBX67YMA.js")),Yc=Ge(()=>import("./chunks/register-list-query-DYCGUQEW.js")),Xc=Ge(()=>import("./chunks/register-mutation-5PT3NW3A.js")),Zc=Ge(()=>import("./chunks/register-operations-QDDQOAAV.js"));function Wt(e){return k(e)}function ka(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 Qc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=X(t),i=new Set(o.map(d=>me(d)??d)),r=ka(e),a=t.find(d=>w.commands.some(m=>m.name()===d)),s=a?w.commands.find(d=>d.name()===a):void 0,l=new Set([...w.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>me(m)).filter(m=>m!==void 0))),c=r?.filter(d=>{let m=me(d)??d;return i.has(m)?!1:l.has(m)||Hn(t,a,m,$)!==void 0});return c&&c.length>0?c:void 0}function ed(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],r=i?me(i):void 0,a=e.find(p=>w.commands.some(u=>u.name()===p)),s=a?w.commands.find(p=>p.name()===a):void 0,l=r?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(r)):void 0,c=Hn(e,a,r,$),d=r?l?.isBoolean()===!0||c===!1?[r]:[r,"<value>"]:[],m=r?Wt([...e,...d]):t;return m===t?void 0:m}function td(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let i=e[o];i!=null&&(n[o]=i)}return n}function nd(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,...td(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Ea(e,t,n){let o=Le(t),i=D(o),r=de(i),[a,s]=r===void 0?[]:i.slice(r,r+2),l=o.includes("--explain"),c=ir(o,e?.code,e?.recovery),d=c&&(a==="history-redact"||a==="history"&&s==="redact")?{...c,...c.attempted_command?{attempted_command:Wt(o)}:{},...c.normalized_args?{normalized_args:[...o]}:{},...c.suggested_retry?{suggested_retry:Wt(o)}:{},...c.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:c;if(d?.recovery_mode==="compact"&&!l)return{...e,recovery:d};let m=Wt(o),p=X(o),u=Qc(n,o,d),g=ed(o,m,u,d),h=nd({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:g,existingRecovery:d});return{...e,recovery:h}}async function st(e){let t=L;L=null,await rr(t,e);let n=Pe;if(Pe=null,!n){pt();return}let o=[],i=li();try{await ar({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?i?.map(r=>r.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Zo(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:se(),affected:i}))}catch(r){o=[`afterCommand hooks failed: ${r instanceof Error?r.message:String(r)}`]}finally{pt()}!n.globalOptions.json&&o.length>0&&_(`[pm] warning: afterCommand hook_warnings=${q(o)}`),n.profileEnabled&&o.length>0&&_(`profile:extensions hook_warnings=${q(o)}`)}async function Sa(){await Mi()}function Aa(e){return Kc.has((process.env[e]??"").trim().toLowerCase())}function Ta(e){return Aa("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Vc.has(Math.trunc(e))}async function Vt(e){return Ta(e.exit_code)?(await Sa(),Fi(e),!0):!1}async function Oa(e){let t=ce(e.error),n=Er(t);e.bootstrapGlobal.json?_(JSON.stringify(xr(t,f.GENERIC_FAILURE),null,2)):_(t),process.exitCode=f.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await Sa(),fn(e.error);let r=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:f.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=r.errorCategory,i=r.commandResolution,He(!1,t,{error_code:n.code,error_category:o,exit_code:f.GENERIC_FAILURE,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||_(`Failed to report error: ${ce(r)}`)}try{await st({ok:!1,error:t,exit_code:f.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||_(`Failed to run error hooks: ${ce(r)}`)}try{await ze()}catch(r){e.bootstrapGlobal.json||_(`Failed to flush error reporting: ${ce(r)}`)}}var od={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"},Oo=new Map;function Ro(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Ra(e,t){return e.options.some(n=>n.long===t)}function Ia(e,t){return e.options.some(n=>n.short===t)}function Io(e,t,n,o){let i=t.trim();if(!i)return;let r=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(Ia(e,i))return;if(o){e.option(`${i} <value>`,`${r} (repeatable)`,yn);return}e.option(`${i} <value>`,r);return}let a=i.startsWith("--")?i:`--${i}`;if(!Ra(e,a)){if(o){e.option(`${a} <value>`,`${r} (repeatable)`,yn);return}e.option(`${a} <value>`,r)}}async function Pa(e,t){let n=od[e];if(!n)return[];let o=`${t}:${n}`,i=Oo.get(o);if(i)return i;if(!await K(J(t)))return Oo.set(o,[]),[];let r=await N(t),s=(mn(r.schema).command_to_fields.get(n)??[]).flatMap(l=>[l.cli_flag,...l.cli_aliases].map(d=>({long:`--${d}`,type:Ro(l.type),value_type:Ro(l.type)})));return Oo.set(o,s),s}async function $a(e,t){let n=U(t),o=R(process.cwd(),n.path);if(!await K(J(o)))return;let i=ye?.key===Lo(o)?ye.snapshot:null,r=i===null?await N(o):i.settings,a=mn(r.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=te(e,l.path.split(" "));if(c)for(let d of a.command_to_fields.get(l.command)??[]){let m=d.description??"";Io(c,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)Io(c,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function Mo(e,t,n,o,i){let r=x(n);if(!(r!=="create"&&r!=="update"))try{let a=i??await N(t),s=re(a,o);aa(e,s,n)}catch{}}function Po(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Na(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Fo(e){return e.some(t=>t==="--profile")}function Lo(e){return`pm-root:${e}`}function $o(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 Da(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=${q(t.activationWarnings)}`))}function Kt(e,t,n){if(!e)return;let o=v(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 Jt(e,t=Ce){let n=Lo(e);if(ye?.key===n)return ye.snapshot;try{let o=Date.now(),{settings:i,warnings:r}=await t(e),a=await Qo({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...r]};return ye={key:n,snapshot:s},s}catch{return ye={key:n,snapshot:null},null}}async function $e(e,t,n=N){let o=t?tt(t):"all",i=Na(e,o);if(rt?.key===i)return rt.snapshot;try{let r=await n(e),a=await Me({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?so(t):void 0}),s=await Fe({...a,loaded:a.loaded}),l=[...new Set(s.commands.handlers.map(u=>v(u.command)))].filter(u=>u.length>0).sort((u,g)=>u.localeCompare(g)),c=Nr(s.registrations.flags),d=Pr(s.commands.handlers,s.registrations.commands),m=Mr(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:r,commandHandlers:l,commandFlagHelp:c,commandDescriptors:m,commandAliases:d,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:u,module:g})=>({name:u,module:g}))};return rt={key:i,snapshot:p},p}catch{return rt={key:i,snapshot:null},null}}async function Ma(e){let t=We(e);if(t.noExtensions){let a=R(process.cwd(),t.path);return await K(J(a))&&$o((await Ce(a)).warnings),null}let n=R(process.cwd(),t.path),o=await Jt(n);if(!o)return null;$o(o.settingsReadWarnings);let i={commandPath:E(e),commandArgs:lo(e)};if(!et(o.discovery,i))return Kt(t.profile,o,i),null;let r=await $e(n,i);return r?(Da(t,r),{hooks:r.hooks,commands:r.commands,parsers:r.parsers,preflight:r.preflight,services:r.services,renderers:r.renderers,registrations:r.registrations,pmRoot:n}):null}async function Fa(e){let t=await $e(e);return t?new Map(t.commandDescriptors):$}async function La(e,t){return(await Ai({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function ja(e,t,n){let o=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return Si(e,Qi.forActiveExtensionHost({pmRoot:e,author:o}),o,v(n))}async function Ua(e,t,n,o=[]){let i=E(e),r=Jn(e.args.map(String),o),a={...t},s={...n},l=R(process.cwd(),n.path),c=await ut({command:i,args:r,options:a,global:s,pm_root:l});n.profile&&c.warnings.length>0&&_(`profile:extensions parser_warnings=${q(c.warnings)}`),r=c.context.args,a=c.context.options,s=c.context.global,fo($.get(v(i)),r,a,o),ve(void 0),mt({command:i,args:r,options:{...a},global:{...s},pm_root:l});let d=await nn({command:i,args:r,options:a,global:s,pm_root:l,sdk:ja(l,s,i)});if(s.profile&&d.warnings.length>0&&_(`profile:extensions command_handler_warnings=${q(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 "${i}" failed in extension handler (${m}).${u}`,f.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new C(`Command "${i}" is provided by extensions and is not currently available.`,f.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ve(d.result),d.result}var ya=Symbol("pm.wrappedActionHandler");function id(e,t){let n=e[e.length-1];return n instanceof No?n:t}function wa(e,t,n){e&&n.length>0&&_(`profile:extensions ${t}=${q(n)}`)}function rd(e){let t=$.get(v(e.commandPath));if(!t||!po(e.activeRegistrations,e.commandPath))return;let n=qt(t).length===0?Qr(e.commandArgs):Jn(e.commandArgs,e.extensionFlagDefinitions);uo(t,n)}function ad(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 qa(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[ya]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let s=id(a,n),l=Date.now();hn(s);let c=We(s),d=O(E(s));if(["package inventory","packages inventory","extension inventory"].includes(d))return await i.apply(this,a);let m=R(process.cwd(),c.path),p=s.args.map(String),u=ae(),g=u?nt(u,d,p):[],h=await Pa(d,m),y=Ie(s,p,[...g,...h]),S=await ut({command:d,args:p,options:y,global:c,pm_root:m});wa(c.profile,"parser_warnings",S.warnings),p=S.context.args,y=S.context.options,ie(s,y),c=S.context.global,rd({activeRegistrations:u,commandPath:d,commandArgs:p,extensionFlagDefinitions:g}),c=await Ji(c),xt(s,c),ad(s,a,p),Ct(s,y),ve(void 0),mt({command:d,args:p,options:{...y},global:{...c},pm_root:m});let T=await nn({command:d,args:p,options:y,global:c,pm_root:m,sdk:ja(m,c,d)});if(wa(c.profile,"command_handler_warnings",T.warnings),T.handled){ve(T.result),rn(T.result,{...c,command:d,commandArgs:p,commandOptions:y,pmRoot:m}),c.profile&&_(`profile:command=${d} took_ms=${Date.now()-l}`);return}return await i.apply(this,a)},o[ya]=!0}for(let i of n.commands)t(i)};t(e)}async function Gt(e){$=new Map,ne({overrides:[]}),e&&await Mo(e.rootProgram,e.pmRoot,e.invocationArgv,Ko(),e.settings)}function sd(e,t,n,o){if(t?.flags&&t.flags.length>0){zn(e,t.flags);let i=Gn(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function Ha(e,t,n){let o={core:0,standard:1,full:2,internal:3},i=(r,a)=>{let s=a.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");Et(r,c);for(let d of r.commands)i(d,[...a,d.name()])};for(let r of e.commands)t.has(r.name())||i(r,[r.name()])}async function za(e,t){let n=U(t),o=R(process.cwd(),n.path);if(n.noExtensions){await Gt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await Jt(o),r=Re(t);if(!i){await Gt();return}if(!et(i.discovery,r)){await Gt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),Kt(Fo(t),i,r);return}let a=await $e(o,r);if(!a){await Gt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}ne(a.services),$=new Map(a.commandDescriptors),await Mo(e,o,t,a.registrations,a.settings);let s=Wr(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,d=>Br(a.activationWarnings,_,d)),l=new Set(e.commands.map(d=>d.name())),c=d=>{let m=d.split(" ").filter(T=>T.length>0),p=a.commandDescriptors.get(d),u=te(e,m),g=a.commandFlagHelp.get(d),h=p?zr(p):null;if(u){sd(u,p,g,h);return}let y=Gr(e,m);p?.description&&y.description(p.description);let S=g;p&&(Fr(y,p),p.flags.length>0&&(zn(y,p.flags),S=Gn(y,p.flags)??void 0)),S&&y.addHelpText("after",S),h&&y.addHelpText("after",h),y.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...T)=>{let G=T[T.length-1],j=G instanceof No?G:y,we=We(j),Yt=Date.now(),lt=nt(a.registrations,d,j.args.map(String)),Ne=Ie(j,j.args.map(String),lt),_e=await Ua(j,Ne,we,lt);await Yi(we,_e),rn(_e,{...we,command:d,commandArgs:j.args.map(String),commandOptions:Ne,pmRoot:o}),we.profile&&_(`profile:command=${d} took_ms=${Date.now()-Yt}`)})};for(let d of s)c(d);Ha(e,l,a.commandDescriptors)}var at=zo(import.meta.url,["../.."])??"0.0.0",w=an(at);async function _a(e){if(!L)return;let t=Reflect.get(e,xa);typeof t=="string"&&await Zi(t)}async function va(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}function Ga(e,t){t&&ot(t)||(e.hook("preAction",async(n,o)=>{Pe=null,L=null,pt(),hn(o);let i=o.optsWithGlobals(),r=We(o),a=O(E(o)),s=o.args.map(String),l=Ie(o,s),c={...r};fi(a,{...l,outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),mo(o,a,c,l),await va(o,void 0,()=>qi(a,c));let d=R(process.cwd(),r.path),m=await Ma(o);if(!m){Pe=ei({commandName:a,commandArgs:s,commandOptions:l,globalOptions:c,pmRoot:d}),L=await gn({command:a,pm_version:at,args:s,options:l,global:c,pm_root:d}),await _a(e),pn(a,s,l,{source_context:L?.source_context,source_context_source:L?.source_context_source}),un(a),await Qn(a,l,d,Po()),await Zn(a,s,l,c,d);return}ti(m.hooks),ni(m.commands),oi(m.parsers),ii(m.preflight),ne(m.services),ri(m.renderers),ai(m.registrations);let p=nt(m.registrations,a,s);l=Ie(o,s,p),mo(o,a,c,l);let u=await ut({command:a,args:s,options:l,global:c,pm_root:m.pmRoot});c.profile&&u.warnings.length>0&&_(`profile:extensions parser_warnings=${q(u.warnings)}`),s=u.context.args,l=u.context.options,ie(o,l),c=u.context.global,Ct(o,l);let g=await ci({command:a,args:s,options:l,global:c,pm_root:m.pmRoot,decision:Po()});c.profile&&g.warnings.length>0&&_(`profile:extensions preflight_warnings=${q(g.warnings)}`),s=g.context.args,l=g.context.options,ie(o,l),c=g.context.global,Ct(o,l);let h=g.decision;await Qn(a,l,m.pmRoot,h),await Zn(a,s,l,c,m.pmRoot);let y=h.run_extension_migrations?await va(o,[],()=>La(m.registrations.migrations,m.pmRoot)):[];c.profile&&y.length>0&&_(`profile:extensions migration_warnings=${q(y)}`);let S=ca(m.registrations.migrations);Pe={hooks:m.hooks,commandName:a,commandArgs:s,commandOptions:{...l},globalOptions:{...c},pmRoot:m.pmRoot,profileEnabled:!!c.profile,migrationBlockers:S},ve(void 0),mt({command:a,args:s,options:{...l},global:{...c},pm_root:m.pmRoot}),L=await gn({command:a,pm_version:at,args:s,options:l,global:c,pm_root:m.pmRoot}),await _a(e),pn(a,s,l,{source_context:L?.source_context,source_context_source:L?.source_context_source}),un(a);let T=await Xo(m.hooks,{command:a,args:s,options:{...l},global:{...c},pm_root:m.pmRoot});c.profile&&T.length>0&&_(`profile:extensions hook_warnings=${q(T)}`),h.enforce_mandatory_migration_gate&&da(a,l,S)}),e.hook("postAction",async()=>{let n=Ao();He(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 st(n)}))}Ga(w);var ba=Symbol("pmCliIdempotentTopLevelRegistration");function Wa(e){let t=e;if(t[ba])return;t[ba]=!0;let n=e.command.bind(e);e.command=((o,...i)=>{let r=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===r||a.aliases().includes(r))?new No(r):n(o,...i)})}async function ld(e,t){if(Wa(e),t.setup){let{registerSetupCommands:n}=await Jc();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Yc(),o=typeof t.targetCommandName=="string"&&go.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Xc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Zc();n(e)}}function cd(e){return async t=>{let n=ct(t.errorCode),o=vt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await zi({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:at,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 Ba(e){if(e.bootstrapGlobal.noExtensions||ot(e.invocationArgv))return;let t=Re(e.invocationArgv),n=await Jt(e.bootstrapPmRoot);if(n&&et(n.discovery,t)){let o=await $e(e.bootstrapPmRoot,t);Va(o);return}n&&Kt(Fo(e.invocationArgv),n,t),ne({overrides:[]})}function Va(e){if(!e){ne({overrides:[]});return}ne(e.services)}async function jo(e){He(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await st({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 Ka(){He(!0,void 0,{exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await st({ok:!0,exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=f.SUCCESS}async function Ja(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof C)&&(cn(e.error)||!n))return!1;let o=ce(e.error),i=e.error instanceof C?e.error.exitCode:ln(t),r=e.error instanceof C?e.error.context:void 0,a=Ea(r,e.invocationArgv,o),s=br(o,a),l=e.bootstrapGlobal.lean?Tt(Nn(o,i,a)):Nn(o,i,a),c=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?le(l,u=>`${JSON.stringify(u,null,2)}
34
- `):l,null,2):vr(o,a);e.jsonErrors?be(`${c}
35
- `):_(c);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:i,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Vt({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:L?.source_context});return await jo({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(fn(dn(e.error,o)),await ze(Do)),process.exitCode=i,!0}async function Ya(e,t){let n=O(A(e.invocationArgv).commandPathTokens.join(" "))||Fn(e.invocationArgv),o=`unknown command '${n}'`,i=R(process.cwd(),e.bootstrapGlobal.path),r=await Fa(i),a=Re(e.invocationArgv),s=await Yn(i,{},Oe(a)),l=await Je({message:o},w,r,{failedExtensions:s}),c=Dn(l.message,l.commandName,l.allowedTypes,{unknownCommandExamples:l.unknownCommandExamples,unknownCommandNextSteps:l.unknownCommandNextSteps,attemptedCommand:l.attemptedCommand,normalizedInvocationArgs:l.normalizedInvocationArgs,providedOptionFlags:l.providedOptionFlags,unknownOptionSuggestions:l.unknownOptionSuggestions,suggestedRetryCommand:l.suggestedRetryCommand,failedExtensions:s}),{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:c.code,errorMessage:c.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await Vt({command:n,error_code:c.code,error_category:d,exit_code:f.USAGE,error_message:c.detail,command_resolution:m,resolution_stage:"parse"}),u=e.jsonErrors?await qn({message:o},w,r,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await Un({message:o},w,r,{failedExtensions:s}),g=Mn(u,e.jsonErrors,s);await jo({errorMessage:o,exitCode:f.USAGE,classificationCode:c.code,errorCategory:d,commandResolution:m,resolutionStage:"parse"}),e.jsonErrors?be(`${g}
36
- `):_(g),p&&await ze(Do),process.exitCode=f.USAGE}async function Xa(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let i=A(e.invocationArgv);return i.requested&&!Ke(w,i.commandPathTokens)?(await Ya(e,t),!0):(await Ka(),!0)}async function Za(e,t){let n=await Je(e.error,w,$),o=Dn(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:i,commandResolution:r}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),a=await Vt({command:e.attemptedCommand,error_code:o.code,error_category:i,exit_code:f.USAGE,error_message:o.detail,command_resolution:r,resolution_stage:"parse",source_context:L?.source_context}),s=e.jsonErrors?await qn(e.error,w,$,e.bootstrapGlobal.lean===!0):await Un(e.error,w,$),l=await ea(o.code,e.bootstrapPmRoot,{},Oe(Re(e.invocationArgv))),c=Mn(s,e.jsonErrors,l);await jo({errorMessage:n.message,exitCode:f.USAGE,classificationCode:o.code,errorCategory:i,commandResolution:r,resolutionStage:"parse"}),e.jsonErrors?be(`${c}
37
- `):_(c),a&&await ze(Do),process.exitCode=f.USAGE}function Qa(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 es(e){let t=e.error.code,n=String(e.error.message??"");if(!await Xa(e,t,n)){if(t==="commander.version"){await Ka();return}await Za(e,t)}}async function Uo(e){let t=U(e.invocationArgv),n=R(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:x(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:cd({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Ba({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Ja(o,sn(e.error))){if(Qa(e.error)){await es(o);return}await Oa({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}function dd(e,t,n){let o=n.requested?n.commandPathTokens:D(t),i=W(o);if(i&&!te(e,[...i.canonical_argv]))throw new Ca(f.USAGE,"commander.unknownCommand",`unknown command '${i.alias}'`)}function md(e,t){let n=de(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let a=de(t.slice(n+1));if(a===void 0)return;n+=a+1}let o=Bt.get(t[n]),i=t.slice(n).filter(a=>!["--global","--project","--local"].includes(a)),r=o?.find(a=>a.alias.split(" ").every((s,l)=>i[l]===s));r?.lifecycle==="deprecated"&&Reflect.set(e,xa,r.alias)}async function pd(e,t){w=an(at),w.hook("preAction",(r,a)=>{t.configurationOnly=["item mutate","item complete"].includes(E(a))&&a.optsWithGlobals().dryRun===!0}),Ga(w,e),rt=null,ye=null,$=new Map,si();let n=[...e],o,i;try{let r=qe(e);n=r.argv,md(w,e);let a=[process.argv[0],process.argv[1],...n],s=n.length===0,l=U(n);if(l.authorMissingValue)throw new C("--author requires a non-empty value.",f.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=Ni(l.author),vo(r),i=Oi(n);let c=ho(n);await ld(w,c),kn(w,!0),wo(w,n)?await za(w,n):($=new Map,ne({overrides:[]})),_o(n)&&await $a(w,n),kn(w);let m=A(n);if(dd(w,n,m),yo(n)&&pr(w,n),qa(w),await ra(w,n,$,e))return;if(m.requested&&!Ke(w,m.commandPathTokens))throw new Ca(f.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||oe(n)&&x(n)===void 0){w.outputHelp();return}if(ot(n)){await w.parseAsync(a);return}let u=R(process.cwd(),l.path),g=await N(u),h=await Rr(n,u,l.noExtensions,$e);await vi({pmRoot:u,packages:h?.contextIntentPackages},()=>bi({env:{...process.env,PM_PATH:u},argv:a,cwd:process.cwd()},()=>Ci(g.agent_identity.harness_signals,()=>w.parseAsync(a),{probesEnabled:g.agent_identity?.probes_enabled})))}catch(r){await Uo({error:r,invocationArgv:n})}finally{i?.(),o?.()}}async function Dp(e=process.argv.slice(2)){let t=e;try{t=qe(e).argv}catch{}let n=ga(t),o={configurationOnly:n!==void 0},i=()=>o.configurationOnly,r=async()=>{try{await Di(process.env,()=>pd(e,o))}catch(a){await Uo({error:a,invocationArgv:[...e]})}};if(n!==void 0){let a=R(process.cwd(),U(t).path),s=R(process.cwd(),n.path),l=Vo(process.cwd());await ht(a,()=>ht(s,()=>ht(l,r,i),i),i)}else await r()}var Mp={activationCommandMatchesProbe:to,applyDynamicExtensionRootHelpVisibility:Ha,bootstrapProfileEnabled:Fo,buildBootstrapActivationProbe:Re,buildPostActionTelemetryOutcome:Ao,buildPmCliRecoveryContext:Ea,buildRuntimeExtensionDiscoverySnapshotCacheKey:Lo,buildRuntimeExtensionActivationScope:tt,buildRuntimeExtensionSnapshotCacheKey:Na,buildRuntimeExtensionFilterForProbe:so,addRuntimeFieldOption:Io,collectActivationCommandCandidates:Oe,collectExtensionFlagDefinitionsForCommand:Ut,collectExtensionFlagDefinitionsForInvocation:nt,collectLeadingCommandArgs:eo,collectParsedActivationCommandArgs:lo,collectRuntimeFieldLooseFlagDefinitionsForCommand:Pa,commandHasLongOption:Ra,commandHasShortOption:Ia,commandPathNeedsSearchExtensions:no,commandPathNeedsTemplateExtensions:Ft,describeUnknownError:ce,defaultPreflightDecision:Po,discoveryNeedsActivationForProbe:et,emitExtensionProfile:Da,emitExtensionSkippedProfile:Kt,emitSettingsReadWarnings:$o,ensureIdempotentTopLevelCommandRegistration:Wa,enforceExplicitRetryForFlagTypos:vo,envFlagEnabled:Aa,executeRegisteredRuntimeMigrations:La,extractCommandScopedOptions:Ie,extensionActivationCommands:Mt,extensionCapabilities:Qe,extensionNeedsActivationForProbe:Lt,extensionProvidesTemplatesRuntime:io,hasAnyCapability:Te,hasGlobalExtensionContributions:ro,handleGenericRunPmCliError:Oa,handleRunPmCliCommanderError:es,handleRunPmCliError:Uo,handleRunPmCliHelpDisplayError:Xa,handleRunPmCliKnownError:Ja,handleRunPmCliCommanderUsageError:Za,handleUnknownHelpCommandError:Ya,inferMissingFieldsFromErrorMessage:ka,inferPostActionErrorCode:So,inferPostActionFailureMessage:Eo,invocationRequestsVersion:it,isCommanderError:cn,loadRuntimeExtensionCommandDescriptorsForRecovery:Fa,loadRuntimeExtensionDiscoverySnapshot:Jt,loadRuntimeExtensionSnapshot:$e,maybeLoadRuntimeExtensions:Ma,maybeAttachCreateUpdatePolicyHelpText:Mo,maybeLogHandledCliErrorToSentry:Vt,matchesStaticExtensionCommand:Dt,normalizeTelemetryCommandResolution:Co,normalizeTelemetryErrorCategory:ko,normalizeTelemetryResolutionStage:xo,normalizeThrownExitCode:ln,probeUsesAnyFlag:oo,prepareExtensionServicesForRunPmCliError:Ba,readRecordBoolean:bo,readRecordNumber:zt,readRecordString:he,recordCliReadOutputInvocationProvenance:co,registerDynamicExtensionCommandPaths:za,registerRuntimeSchemaFieldFlags:$a,resolveCoreCommandRegistrationSelection:ho,resolveStaticExtensionActivationDecision:ao,resolveUnknownHelpToken:Fn,readThrownExitCode:sn,runAndClearAfterCommandHooks:st,runRequiredExtensionCommand:Ua,shouldAttachRichHelpTextForInvocation:yo,shouldLogHandledErrorToSentry:Ta,shouldRegisterDynamicExtensionPaths:wo,shouldRegisterRuntimeSchemaFlags:_o,shouldHandleRunPmCliCommanderError:Qa,setActiveExtensionHookContextForTest:Wc,setActiveRuntimeExtensionCommandDescriptorsForTest:Bc,setRecoveredExtensionServices:Va,toLooseFieldDefinitionType:Ro,isImporterOrExporterCommandPath:po,validateDynamicExtensionCommandInvocation:fo,wrapProgramActionsForExtensionHandlers:qa,wrapThrownErrorForSentry:dn};export{Mp as _testOnly,Dp as runPmCli};
27
+ `)}`}function Wn(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:Wn(o).includes(n))??null}function te(e,t){let n=e;for(let o of t){let i=Xe(n,o);if(!i)return null;n=i}return n}var Vn=new WeakSet;function Wr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];o>0&&P.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let r=Xe(n,i);if(r){n=r;continue}let a=n.command(i);Vn.add(a),o<t.length-1?(a.description("Extension-provided command group."),a.action(()=>{a.help()})):a.description("Extension-provided command path."),n=a}return n}function zl(e,t){let n=t.join(" "),o=P.find(a=>n===a.canonical||n.startsWith(`${a.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let i=e,r=[];for(let a of t){let s=Xe(i,a);if(!s)return null;r.push(a);let l=s.commands.length>0||P.some(c=>c.canonical.startsWith(`${r.join(" ")} `));if(!Vn.has(s)&&(r.length===t.length||!l))return{core_path:r.join(" "),extension_path:t.join(" ")};i=s}return null}function Gl(e,t,n,o,i=!1){let r=t.split(" ").filter(d=>d.length>0),a=zl(e,r),s=te(e,r),l=P.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Vn.has(s)));if(!a||a.core_path===t&&s!==null&&!n.has(t)&&!i||l&&!n.has(t))return null;let c=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${c}`}function Vr(e,t,n,o,i){return[...new Set([...t,...n.keys()])].filter(r=>r.trim().length>0).sort((r,a)=>r.localeCompare(a)).filter(r=>{let a=Gl(e,r,o,n.get(r),t.includes(r));return a?(i(a),!o.has(r)&&te(e,r.split(" "))!==null):!0})}function Br(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]="93ca07c1-857b-57ae-8530-a315a24d0fe5")}catch{}})();var Wl=new Set(["__proto__","prototype","constructor"]),Kr=Symbol("looseOptionOccurrences");function Ze(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function Vl(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 Bn(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let a=n.indexOf("=");if(a>=0)return{consumed:1,key:n.slice(1,a).trim(),value:n.slice(a+1)};let s=n.slice(1).trim(),l=e[t+1];return typeof l=="string"&&!l.startsWith("-")?{consumed:2,key:s,value:l}:{consumed:1,key:s,value:!0}}let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(2,o).trim(),value:n.slice(o+1)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let i=n.slice(2).trim(),r=e[t+1];return typeof r=="string"&&!r.startsWith("-")?{consumed:2,key:i,value:r}:{consumed:1,key:i,value:!0}}function Nt(e){return Wl.has(e)}function Jr(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Jo(t)}function Qe(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let i=Ze(n.slice(2));i.length>0&&!Nt(i)&&t.push(i)}if(o.startsWith("-")&&!o.startsWith("--")){let i=Ze(o.slice(1));i.length>0&&!Nt(i)&&t.push(i)}return[...new Set(t)]}function Yr(e){let t=new Set;for(let n of e)for(let o of Qe(n))t.add(o);return t}function Bl(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=Ze(t.slice(2));if(n.length>0&&!Nt(n))return n}return Qe(e)[0]??null}function Kl(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 Kn(e,t,n){if(t.length===0)return;let o=new Set,i=new Map,r=[],a=[];for(let s of t){let l=Qe(s),c=Kl(s);c!==null&&a.push(c);for(let d of l)o.add(d),s.enabled===!1&&i.set(d,c);s.required===!0&&s.enabled!==!1&&l.length>0&&r.push({keys:l,label:c})}for(let s of Object.keys(e)){if(!o.has(s)){let c=a.length>0?` Expected one of: ${[...new Set(a)].join(", ")}.`:"";throw new C(`Unknown option '--${s}' for extension command '${n}'.${c}`,f.USAGE)}let l=i.get(s);if(l)throw new C(`Option '${l}' is disabled for extension command '${n}'.`,f.USAGE)}for(let s of r)if(!s.keys.some(l=>Object.hasOwn(e,l)))throw new C(`Missing required option '${s.label}' for extension command '${n}'.`,f.USAGE)}function Jl(e){return typeof e=="string"||e==null?e:String(e)}function Yl(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 Xl(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 Zl={string:Jl,number:Yl,boolean:Xl};function Dt(e,t){return Array.isArray(e)?e.map(n=>Dt(n,t)):Zl[t](e)}function Xr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(i=>i!=null&&i!==""):Yo(e);return t?o.map(i=>Dt(i,t)):o}function Ql(e,t,n,o){return n?Xr(e,t,o):t?Dt(e,t):e}function ec(e,t,n){let o=e[Kr];if(!o||o.length===0)return n;let i=new Set(t);return o.filter(r=>i.has(r.key)).map(r=>r.value)}function Zr(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[i,r]of Object.entries(e))o[i]=r;for(let i of t){let r=Bl(i);if(!r)continue;let a=i.list===!0,s=Qe(i);for(let d of s)if(!(d===r||!Object.hasOwn(o,d))){if(Object.hasOwn(o,r)){if(!a){delete o[d];continue}let m=o[r],p=o[d];o[r]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[d];continue}o[r]=o[d],delete o[d]}let l=Jr(i),c=i.repeatable===!0;if(!Object.hasOwn(o,r)){i.default!==void 0&&(o[r]=Ql(i.default,l,a,c));continue}if(a){o[r]=Xr(ec(n,s,o[r]),l,c);continue}l&&(o[r]=Dt(o[r],l))}return o}function Qr(e){let t=Object.create(null),n=[];Object.defineProperty(t,Kr,{value:n});let o=0;for(;o<e.length;){let i=Bn(e,o);if(!i){o+=1;continue}let r=Ze(i.key);if(r.length===0||Nt(r)){o+=i.consumed;continue}Vl(t,r,i.value),n.push({...i,key:r}),o+=i.consumed}return t}function ea(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=Bn(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function Jn(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let a of t){let s=Jr(a);for(let l of Qe(a))n.add(l),s==="boolean"&&o.add(l)}if(n.size===0)return[...e];let i=[],r=0;for(;r<e.length;){if(e[r]==="--"){i.push(...e.slice(r+1));break}let a=Bn(e,r);if(a){let s=Ze(a.key);if(n.has(s)){let l=e[r],c=o.has(s)&&!l.includes("=")?1:a.consumed;r+=c;continue}}i.push(e[r]),r+=1}return i}import Oe 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]="989fc265-7deb-5456-8a83-0f1fa8d2d9b2")}catch{}})();async function Yn(e,t={},n=[]){let o={readSettings:D,loadExtensions:Fe,activateExtensions:Le,resolveImplicitPmRoot:en,...t};try{let i=await o.readSettings(e),r=await o.loadExtensions({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(r);return[...r.failed,...a.failed].map(s=>{let l=(r.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),c=[...l?.contributions?.commands??[],...l?.contributions?.command_handlers??[],...l?.activation?.commands??[]].map(F).filter((p,u,g)=>p.length>0&&g.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(F),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(i){return[{layer:"runtime",name:"extension-loader",error:i instanceof Error?i.message:String(i)}]}}async function ta(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await Yn(t,n,o),r={readSettings:D,loadExtensions:Fe,activateExtensions:Le,resolveImplicitPmRoot:en,...n};try{let a=r.resolveImplicitPmRoot(process.cwd());if(Oe.resolve(a)===Oe.resolve(t))return i;let[s,l]=await Promise.all([r.readSettings(t),r.readSettings(a)]),[c,d]=await Promise.all([r.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),r.loadExtensions({pmRoot:a,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,g)=>u.localeCompare(g));if(p.length===0)return i;i.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Oe.resolve(t)} extension_discovery_root=${c.roots.project}; cwd_storage_root=${Oe.resolve(a)} 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 ${Oe.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${Oe.resolve(t)} install <package> --project".`})}catch{}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6fa59b21-fcd4-5056-ae4c-379d57bb7757")}catch{}})();var na={core:0,standard:1,full:2,internal:3};function oa(e,t,n=!0){let o=t.get(T(e));if(o)return o;if(!n)return;let i=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(i.length===0)return;let r=i.reduce((s,l)=>na[l.tier]<na[s]?l.tier:s,"internal"),a=new Set(i.map(({family:s})=>s));return{tier:r,family:a.size===1?i[0].family:"extensions"}}function ia(e,t){if(t.length===0)return e;let n=te(e,t);if(n)return n;let o=t.join(" ");if(T(o)!==o||!gt.some(i=>i===o)&&!Oi(o)&&!Ue(o)&&!Je(e,t))return null;for(let i=t.length-1;i>0;i-=1){let r=te(e,t.slice(0,i));if(r)return r}return t.length===1?e:null}function tc(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function ra(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 nc(e){let t=new Map;for(let n of e){let o=n,i=ra(n);if(!i||typeof o.long!="string"||o.long.trim().length===0)continue;let r=t.get(i)??[];r.push(o.long.trim()),t.set(i,r)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(i=>i.trim()).filter(i=>i.length>0))].sort((i,r)=>i.localeCompare(r)));return t}function oc(e){return k(e)}function ic(e){let t=e.options??[],n=nc(t);return t.map(o=>{let i=o,r=typeof i.flags=="string"?i.flags.trim():"",a=typeof i.description=="string"?i.description.trim():"",s=ra(o),c=(s?n.get(s)??[]:[]).filter(y=>y!==i.long).map(y=>y.trim()).filter(y=>y.length>0),d=a.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,p=i.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),u=r.includes("<"),g=u||r.includes("["),h={flags:r,long:typeof i.long=="string"?i.long:null,short:typeof i.short=="string"?i.short:null,description:a,takes_value:g,value_required:u,value_name:tc(r),variadic:i.variadic===!0,required:p,aliases:c,alias_for:m};return i.defaultValue!==void 0&&(h.default_value=i.defaultValue),h})}function rc(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let i=o.alias_for,r=t.get(i);if(!r)continue;let a=o.long,s=new Set([...r.aliases??[],a]);r.aliases=[...s].sort((l,c)=>l.localeCompare(c))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function ac(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let i=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",r=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:i.trim(),required:o.required===!0||r?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:r}})}function sc(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(r=>r.name()!=="help"||e.parent===null).filter(r=>!n||(ue(r)??Y(r.name()))!=="internal").map(r=>{let a=F(E(r)),s=a,l=ue(r),c=oa(a,t,l!==void 0),d=V.find(({alias:m})=>m===a);return{name:r.name().trim(),aliases:Wn(r),description:r.description().trim(),tier:c?.tier??l??Y(s),family:c?.family??Ct(s),...d?{alias_for:d.canonical,alias_lifecycle:d.lifecycle,...d.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((r,a)=>r.name.localeCompare(a.name))}function lc(e,t,n){if(!n)return t;let o=n.examples??[],i=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?i.length>0?[...i]:[...t.tips]:[],detail_mode:e}}function cc(e,t,n,o,i){let r=e!==void 0&&xn(e)===Ee,a=r?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:pr(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":r?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:lc(n,a,o),intentSource:s}}function dc(e,t){return e===void 0?null:t?.tier??Y(e)}function mc(e,t){return e===void 0?null:t?.family??Ct(e)}function pc(e,t,n){if(!(t!==e||!n))return V.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:ia(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function uc(e,t,n,o,i=new Map,r=!1){if(!e){let s=ac(t),l=sc(t,i,r),c=new Set(l.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...l,..._t.filter(({parent:d,action:m})=>d===n&&!c.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:Y(n.split(" ")[0]),family:Ct(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 a=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&&a.has(s)||l.some(c=>a.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 fc(e,t,n,o,i){let r=Cn(n),a=ie(n),s=F(E(t)),l=F(o.join(" ")),c=l.length>s.length?l:s,d=Ue(c),m=d?.command??s,p=m.length>0?m:void 0,u=p,g=p?i.get(T(p)):void 0,h=p?oa(p,i,ue(t)!==void 0):void 0,{narrative:y,intentSource:S}=cc(p,t.description().trim(),r,g,d!==void 0),O=rc(zr(ic(t),Hr(g))),G=uc(d,t,m,O,i,a),j=pc(e,t,a);return{format:"pm_help_v1",detail_mode:r,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:dc(u,h),capability_family:mc(u,h),description:d?.description??t.description(),usage:G.usage,intent:d?.description??y.intent,intent_source:S,examples:d?[d.example]:y.examples,tips:d?[vt(d.accepted_flags)]:y.tips,arguments:G.arguments,options:G.options,subcommands:G.subcommands,has_subcommands:G.subcommands.length>0,...j===void 0?{}:{command_aliases:j}}}async function aa(e,t,n,o=t){let i=U(t);if(!i.json)return!1;let r=A(t);if(!r.requested)return!1;let a=ia(e,r.commandPathTokens);if(!a){if(!i.quiet){let s=`unknown command '${T(r.commandPathTokens.join(" "))}'`,l=jn(s,e,n),c=It(s,"help",Be,f.USAGE,{...l,attemptedCommand:oc(t),normalizedInvocationArgs:[...t],providedOptionFlags:X(t)}),d=i.tokenAccounting?ce(c,m=>`${JSON.stringify(m,null,2)}
28
+ `):c;xe(`${JSON.stringify(d,null,2)}
29
+ `)}return process.exitCode=f.USAGE,!0}if(!i.quiet){let s=fc(e,a,t,r.commandPathTokens,n),l=A(o).commandPathTokens;s.requested_path=l;let c=B(l.join(" "));c&&(s.resolved_path=c.canonical),a===e&&!ie(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),_i(`${JSON.stringify(s,null,2)}
30
+ `)}return process.exitCode=f.SUCCESS,!0}function gc(e,t){let n=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${t.types.join("|")}`];return e==="create"&&n.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),n.join(`
31
+ `)}function hc(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",i=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${i.length>0?i.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function yc(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let i of[...t.required_create_fields,...t.required_create_repeatables])o.add(i);return{progressive:n,strict:o}}function wc(e,t,n,o){let i=new Set(n),r=o.filter(l=>!i.has(l)),a=l=>l.length>0?l.map(c=>Qt("create",c)).join(", "):"none";e.push(` required in strict mode: ${a(r)}`);let s=r.map(Zi).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 _c(e,t,n){let o=Ri(n);if(!o)return gc(e,t);let i=Wo(o,t);if(!i){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
32
+ `)}let r=n.indexOf("--"),a=r<0?n:n.slice(0,r),s=a.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),l=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],c=e==="create"&&l?.toLowerCase()==="strict",d=yc(e,i),m=mt(i,e,d.progressive),p=mt(i,e,c?d.strict:d.progressive),u=h=>h.length>0?h.map(y=>Qt(e,y)).join(", "):"none",g=["",`Type-aware option policies for ${i.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=mt(i,e,d.strict);wc(g,i,m.required,h.required)}return hc(g,i),p.errors.length>0&&g.push(` config errors: ${p.errors.join("; ")}`),g.join(`
33
+ `)}function sa(e,t,n){let o=x(n);if(o!=="create"&&o!=="update")return;let i=Xe(e,o);i&&i.addHelpText("after",_c(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]="840b471e-c996-57e2-b97c-3a84bd68f050")}catch{}})();function vc(e,t){let n=Me(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function bc(e){return Me(e.status)?.toLowerCase()??"pending"}function Cc(e){return e.mandatory===!0}function xc(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 da(e){let t=[];return e.forEach((n,o)=>{if(!Cc(n.definition))return;let i=bc(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:vc(n.definition,o),status:i})}),t.sort(xc),t}function la(e){return Array.isArray(e)&&e.length>0}var kc=new Set(["create","beads import","todos import"]),Ec=new Set(["restore","update","close","delete","append","claim","release"]),Sc=new Set(["comments","notes","learnings"]),Ac=new Set(["files","docs","test"]),Oc=new Set(["activate","add","add-field","add-status","add-type","apply","compact","create","deactivate","delete","disable","edit","enable","import","infer","install","materialize","migrate","redact","remove","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type","repair","run","save","set","unset","update","upgrade"]);function Xn(e,t){let n=t.force===!0;return kc.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Ec.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:Sc.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:Ac.has(e)?{isMutation:la(t.add)||la(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function Tc(e,t,n){if(Xn(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return ji(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>Oc.has(i.trim().toLowerCase())):!1}function ca(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Rc(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let i=[];if(Me(t[1])||i.push("source"),Me(n.to)||i.push("--to"),i.length!==0)throw new C(`Schema migration requires ${i.join(", ")}.`,f.USAGE,{code:"schema_migration_input_required",required:i.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:i,suggested_flags:i.filter(r=>r.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function Ic(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||ca(n.status)!==ca(i.schema.workflow.in_progress_status))return;let r=t[0];if(!r)return;let a=ae(i,se()),s=await wt(o,r,i.id_prefix,i.item_format,a.type_to_folder);if(!s)return;let l=await Ei(s,{schema:i.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 Zn(e,t,n,o,i){if(!Tc(e,t,n)||(Rc(e,t,n),!await K(J(i))))return;let r=await ke(i);o.json!==!0&&await Ic(e,t,n,i,r.settings);let a=Li({author:ht(o.author,r.settings.author_default),payload:{command:e,args:t,options:n},settings:r.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)_(`warning:${s}`)}function ma(e,t,n){if(n.length===0)return;let o=Xn(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let i=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),r=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 (${i.join(",")}). ${r}`,f.CONFLICT)}async function Qn(e,t,n,o){if(!Xn(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await K(J(n)))return;let{settings:r,metadata:a,warnings:s}=await ke(n);for(let l of s)_(`warning:${l}`);if(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(xi(r),await ki(n,r,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let l=ae(r,se());await Ui(n,r.item_format,"item_format:pre_mutation_sync",l.type_to_folder,r.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]="697f96fe-38a0-5530-b54b-22cb442c130f")}catch{}})();function eo(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=v(n);o.length!==0&&t.push(o)}return t}function Re(e){let t=v(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(i=>i.length>0);for(let i of eo(e.commandArgs))o.push(...i.split(" ").filter(r=>r.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,T(i)]))]}function to(e,t){let n=v(e);if(n.length===0)return!1;let o=Re(t);for(let i of o)if(i===n||i.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(i=>n.startsWith(`${i} `)):!1}function Ft(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...I(n.commands),...I(n.command_handlers),...I(n.command_overrides),...I(n.flag_commands),...I(n.parser_overrides),...pa(n.preflight_ownership),...pa(n.renderer_ownership)]:[]}function I(e){return e??[]}function pa(e){return I(e).flatMap(t=>t.commands)}function et(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var ua=new Set(["hooks","parser","preflight","renderers"]),fa=new Set(["commands","schema","services","importers"]),Pc=new Set(["reindex","search","search-advanced"]),$c=new Set(["--template"]);function Te(e,t){for(let n of t)if(e.has(n))return!0;return!1}function no(e){let t=v(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Pc.has(n??t)}function oo(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 Lt(e){return v(e.commandPath??"")==="create"&&oo(e,$c)}function io(e){return e.some(t=>{let n=v(t);return n==="templates"||n.startsWith("templates ")})}function Mt(e,t){return e.some(n=>to(n,t))||Lt(t)&&io(e)}function ro(e){return[I(e.hooks).length,(e.preflight_overrides??0)-I(e.preflight_ownership).length,I(e.item_types).length,I(e.item_fields).length,I(e.relationship_kinds).length,I(e.service_overrides).length,I(e.assurance_providers).length,I(e.renderer_overrides).length-I(e.renderer_ownership).length].some(n=>n>0)}function ao(e,t){let n=e.activation?.commands??[];if(n.length>0)return Mt(n,t);let o=Ft(e);if(Mt(o,t)||et(e).has("search")&&no(t.commandPath))return!0;if(e.contributions)return ro(e.contributions)}function jt(e,t){let n=ao(e,t);if(n!==void 0)return n;let o=et(e);return!!(Te(o,ua)||Te(o,fa))}function tt(e,t){return e.effective.length===0?!1:nt(t)!=="all"?e.effective.some(o=>jt(o,t)):e.effective.some(o=>{let i=et(o);return Ft(o).length>0||Te(i,ua)||Te(i,fa)||i.has("search")})}function nt(e){if(v(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=Re(e).filter(i=>i.split(" ").every(r=>!r.startsWith("-"))).sort((i,r)=>r.length-i.length)[0]??v(e.commandPath??"");if(t.length===0)return"all";let n=Lt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function so(e){return nt(e)==="all"?void 0:t=>jt(t,e)}function Ie(e){let t=A(e);if(t.requested&&t.commandPathTokens.length>0){let[i,...r]=t.commandPathTokens;return{commandPath:i,commandArgs:r,allowCommandPrefixMatch:!0}}let n=M(e),o=n.findIndex(i=>i.trim().length>0&&!i.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function lo(e){let t=e.args.map(String);if(v(E(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.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]="b9f5ccc6-1a28-5269-983a-fd6e0d0e1a74")}catch{}})();var Ut=Symbol.for("pm.readOutputInvocationProvenance");function re(e,t){let n=Reflect.get(e,Ut);n!==void 0&&Reflect.set(t,Ut,n)}function co(e,t,n){let o=ui(t,n);if(!o)return;let i=e;for(;i.parent;)i=i.parent;let r=i.rawArgs,a=new Set(X(r.slice(2))),s=pi.find(d=>d.command===o),l=Object.values(s.dimensions).flatMap(d=>d.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),c=Reflect.get(n,Ut);Reflect.set(n,Ut,{canonical_include_modes:c?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),re(n,e)}function Nc(e){let t=e.optsWithGlobals(),n=E(e);if(T(n)===n)return t;let o=e.opts();for(let i=e.parent;i?.parent;i=i.parent)for(let r of i.options){let a=r.attributeName(),s=i.getOptionValueSource(a)==="cli";if(s&&!e.options.some(l=>l.long===r.long))throw new C(`Unknown option '${r.long}' for ${n}`,f.USAGE,{code:"unknown_option",flag:r.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(a)!=="cli"){let l=i.getOptionValue(a);e.setOptionValueWithSource(a,l,"cli")}a in o?t[a]=o[a]:delete t[a]}return t}function mo(e,t,n,o){co(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:r,modes:a}=hi(t,i,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;re(o,e);let s=gi(t);for(let c of a){let d=s.get(c),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let l=r.length>0?r.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 Pe(e,t,n=[]){let i={...Nc(e)};re(e,i),delete i.json,delete i.quiet,delete i.path,delete i.pmPath,delete i.noExtensions,delete i.extensions,delete i.profile,delete i.pager,delete i.changedFields,delete i.fullChangedFields,delete i.idOnly,delete i.lean,delete i.tokenAccounting,delete i.outputInclude,delete i.outputLimit,delete i.outputBudget,delete i.outputFormat,delete i.outputSession;let r=Qr(t);for(let[a,s]of Object.entries(r))i[a]===void 0&&(i[a]=s);if(n.length>0){let a=Yr(n),s=oe(E(e)).map(d=>({long:d.flag,short:d.short,aliases:d.aliases})),l={...r};for(let d of a)i[d]!==void 0&&(l[d]=i[d]);Kn(l,[...s,...n],E(e));let c=Zr(i,n,r);return re(i,c),c}return i}function qt(e,t){let n=v(t);return n.length===0?[]:e.flags.filter(o=>T(v(o.target_command))===T(n)).flatMap(o=>o.flags)}function ot(e,t,n){let o=qt(e,t),i=[t],r=[];for(let a of n){if(a.startsWith("-"))break;i.push(a);let s=qt(e,i.join(" "));s.length>0&&(r=s)}return r.length>0?r:o}function Ht(e){return e.arguments??[]}function ga(e){let t=Ht(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function po(e,t){if(!e)return!1;let n=v(t);return e.importers.some(o=>v(`${o.importer} import`)===n)||e.exporters.some(o=>v(`${o.exporter} export`)===n)}function uo(e,t){let n=Ht(e),o=n.filter(l=>l.required).length,r=n.some(l=>l.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new C(`Missing required argument for extension command '${e.command}'. Usage: ${ga(e)}${s}`,f.USAGE);if(t.length>r){let l=t.slice(r).join(" ");throw new C(`Too many arguments for extension command '${e.command}': ${l}. Usage: ${ga(e)}${s}`,f.USAGE)}}function Dc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Mc(e,t,n){if(n.length>0){Kn(t,n,e.command);return}let o=Object.keys(t).filter(i=>t[i]!==void 0).sort();if(o.length!==0)throw new C(`Unknown option '${o.map(Dc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,f.USAGE)}function fo(e,t,n,o){e&&(uo(e,t),Mc(e,n,o))}import{Command as ha}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]="368c57a5-6fd3-5780-8e38-3d9aea4ac3fd")}catch{}})();var Fc=new Set(["--version","-V"]);function it(e){let t=M(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function ya(e){if(M(e)[0]!=="item"||!e.includes("--dry-run"))return;let n=new ha().configureOutput({writeErr:()=>{}}).exitOverride(),o=new Set;for(let r of qe)for(let a of[r.flag,r.short,...r.aliases??[]]){if(a===void 0||o.has(a))continue;o.add(a);let s=r.value_name!==void 0||r.flag==="--pm-path";n.option(`${a}${s?" <value>":""}`)}try{n.parseOptions(e)}catch{}let i=n.opts();return{path:i.pmPath??i.path}}var Lc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),go=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"]),wa=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"]),jc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Uc=new Set(["claim","close-task","pause-task","release","start-task","test"]),ye={setup:!0,listQuery:!0,mutation:!0,operation:!0},qc=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 rt(e){return e.some(t=>Fc.has(t))}function Hc(e,t){if(!P.some(o=>o.canonical_argv[0]===t))return;let n=new ha().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of Gi(t,oe(t))){let i=o.takes_value?o.value_required?" <value>":" [value]":"";for(let r of[o.flag,o.short,...o.aliases??[]])r!==void 0&&n.option(`${r}${i}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return ye;let i=W([t,...o.operands])?.alias;if(P.some(r=>r.alias===i))return{...ye,targetCommandName:i}}catch{return ye}}function ho(e){if(rt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||A(e).requested)return ye;let t=x(e);if(!t)return ye;let n=t.trim().toLowerCase(),o=M(e),i=W(o)?.alias;if(P.some(a=>a.alias===i))return{...ye,targetCommandName:i};let r=Hc(o,n==="ctx"?"context":n);return r||(Lc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:go.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:wa.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:jc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:ye)}function yo(e){return e.length===0||A(e).requested||e.includes("--explain")&&x(e)===void 0}function wo(e,t){return it(t)||rt(t)?!1:ie(t)||A(t).requested?!0:!!x(t)}function _o(e){if(rt(e))return!1;let t=x(e);return t?qc.has(t):!1}function zc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,i=e.normalizedTokens.map(c=>{let d=c.indexOf("=");return d>=0?c.slice(0,d):c}).find(c=>c==="--literal"||c==="--regex"||c==="--replacement"),r=i?e.argv.map(c=>{let d=c.indexOf("=");return(d>=0?c.slice(0,d):c)===o?d>=0?`${i}${c.slice(d)}`:i:c}):e.argv,a=je(r),s=i&&n>=0?`${o}=[redacted]`:t,l=i&&e.normalizedDisplay.includes("=")?`${i}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:l,sourceDisplay:s}}function vo(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),i=o.length>0?o.join(" "):"the canonical flag",r=wa.has(t)||Uc.has(t),a=r?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=r?"mutating option":"option",l=zc({argv:e.argv,normalizedDisplay:i,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.`,f.USAGE,{code:a,examples:[k(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:k(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]="afcf2608-3360-5030-b5ea-b101df5829e7")}catch{}})();var Gc=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"]),Wc=new Set(["parse","preflight","execute","unknown"]),Vc=new Set(["usage","validation","conflict","runtime","unknown"]);function we(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let i=o.trim();if(i.length>0)return i}}}function bo(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function zt(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 Co(e){if(!e)return;let t=e.trim().toLowerCase();if(Gc.has(t))return t}function xo(e){if(!e)return;let t=e.trim().toLowerCase();if(Wc.has(t))return t}function ko(e){if(!e)return;let t=e.trim().toLowerCase();if(Vc.has(t))return t}function Eo(e){let t=we(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(bo(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let i=zt(e,"failed");if(typeof i=="number"&&i>0)return`failed_runs:${i}`;let r=e?.run_results;if(Array.isArray(r)){let a=r.filter(s=>Zt(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function So(e,t){if(!e)return t===f.USAGE?"invalid_command_usage":t===f.NOT_FOUND?"item_not_found":t===f.CONFLICT?"lock_conflict":t===f.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function Ao(){let e=Zt(le()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=zt(e,"exit_code","exitCode"),o=t??n??f.SUCCESS,i=Ki(o),r=we(e,"error_code","errorCode")??So(i,o),a=ko(we(e,"error_category","errorCategory"))??(i?void 0:dt(r)),s=i?void 0:Eo(e)??`command_exit_${o}`,l=Co(we(e,"command_resolution","commandResolution"))??bt({ok:i,errorCode:r,errorCategory:a}),c=xo(we(e,"resolution_stage","resolutionStage"))??"execute";return{ok:i,error:s,exit_code:o,error_code:r,error_category:a,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]="a441a914-7d0e-5ed4-8bb9-8b94c540f0a1")}catch{}})();var Oo="PM_CLI_PACKAGE_ROOT",Ea=Symbol("pm.deprecatedAliasInvocation"),Vt=new Map;for(let e of V){let t=e.alias.split(" ")[0],n=Vt.get(t)??[];n.push(e),Vt.set(t,n)}for(let e of Vt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function Bc(){return Ho(import.meta.url,["../.."])}(typeof process.env[Oo]!="string"||process.env[Oo]?.trim().length===0)&&(process.env[Oo]=Bc());var $e=null,L=null;function Kc(e){$e=e}function Jc(e){N=e}var at=null,_e=null,N=new Map,Do=250,Yc=new Set([f.USAGE,f.NOT_FOUND,f.CONFLICT]),Xc=new Set(["1","true","yes","on"]),Zc=We(()=>import("./chunks/register-setup-HM3OCBH2.js")),Qc=We(()=>import("./chunks/register-list-query-QBGXO5JJ.js")),ed=We(()=>import("./chunks/register-mutation-53ZLT4RX.js")),td=We(()=>import("./chunks/register-operations-OBK2FXUU.js"));function Wt(e){return k(e)}function Sa(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=>pe(o)??o))];return n.length>0?n:void 0}function nd(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=X(t),i=new Set(o.map(d=>pe(d)??d)),r=Sa(e),a=t.find(d=>w.commands.some(m=>m.name()===d)),s=a?w.commands.find(d=>d.name()===a):void 0,l=new Set([...w.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>pe(m)).filter(m=>m!==void 0))),c=r?.filter(d=>{let m=pe(d)??d;return i.has(m)?!1:l.has(m)||Hn(t,a,m,N)!==void 0});return c&&c.length>0?c:void 0}function od(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],r=i?pe(i):void 0,a=e.find(p=>w.commands.some(u=>u.name()===p)),s=a?w.commands.find(p=>p.name()===a):void 0,l=r?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(r)):void 0,c=Hn(e,a,r,N),d=r?l?.isBoolean()===!0||c===!1?[r]:[r,"<value>"]:[],m=r?Wt([...e,...d]):t;return m===t?void 0:m}function id(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let i=e[o];i!=null&&(n[o]=i)}return n}function rd(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,...id(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Aa(e,t,n){let o=je(t),i=M(o),r=me(i),[a,s]=r===void 0?[]:i.slice(r,r+2),l=o.includes("--explain"),c=rr(o,e?.code,e?.recovery),d=c&&(a==="history-redact"||a==="history"&&s==="redact")?{...c,...c.attempted_command?{attempted_command:Wt(o)}:{},...c.normalized_args?{normalized_args:[...o]}:{},...c.suggested_retry?{suggested_retry:Wt(o)}:{},...c.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:c;if(d?.recovery_mode==="compact"&&!l)return{...e,recovery:d};let m=Wt(o),p=X(o),u=nd(n,o,d),g=od(o,m,u,d),h=rd({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:g,existingRecovery:d});return{...e,recovery:h}}async function lt(e){let t=L;L=null,await ar(t,e);let n=$e;if($e=null,!n){ut();return}let o=[],i=li();try{await sr({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?i?.map(r=>r.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Zo(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:i}))}catch(r){o=[`afterCommand hooks failed: ${r instanceof Error?r.message:String(r)}`]}finally{ut()}!n.globalOptions.json&&o.length>0&&_(`[pm] warning: afterCommand hook_warnings=${q(o)}`),n.profileEnabled&&o.length>0&&_(`profile:extensions hook_warnings=${q(o)}`)}async function Oa(){await Mi()}function Ta(e){return Xc.has((process.env[e]??"").trim().toLowerCase())}function Ra(e){return Ta("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Yc.has(Math.trunc(e))}async function Bt(e){return Ra(e.exit_code)?(await Oa(),Fi(e),!0):!1}async function Ia(e){let t=de(e.error),n=Sr(t);e.bootstrapGlobal.json?_(JSON.stringify(kr(t,f.GENERIC_FAILURE),null,2)):_(t),process.exitCode=f.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await Oa(),fn(e.error);let r=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:f.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=r.errorCategory,i=r.commandResolution,ze(!1,t,{error_code:n.code,error_category:o,exit_code:f.GENERIC_FAILURE,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||_(`Failed to report error: ${de(r)}`)}try{await lt({ok:!1,error:t,exit_code:f.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||_(`Failed to run error hooks: ${de(r)}`)}try{await Ge()}catch(r){e.bootstrapGlobal.json||_(`Failed to flush error reporting: ${de(r)}`)}}var ad={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"},To=new Map;function Ro(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Pa(e,t){return e.options.some(n=>n.long===t)}function $a(e,t){return e.options.some(n=>n.short===t)}function Io(e,t,n,o){let i=t.trim();if(!i)return;let r=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if($a(e,i))return;if(o){e.option(`${i} <value>`,`${r} (repeatable)`,yn);return}e.option(`${i} <value>`,r);return}let a=i.startsWith("--")?i:`--${i}`;if(!Pa(e,a)){if(o){e.option(`${a} <value>`,`${r} (repeatable)`,yn);return}e.option(`${a} <value>`,r)}}async function Na(e,t){let n=ad[e];if(!n)return[];let o=`${t}:${n}`,i=To.get(o);if(i)return i;if(!await K(J(t)))return To.set(o,[]),[];let r=await D(t),s=(mn(r.schema).command_to_fields.get(n)??[]).flatMap(l=>[l.cli_flag,...l.cli_aliases].map(d=>({long:`--${d}`,type:Ro(l.type),value_type:Ro(l.type)})));return To.set(o,s),s}async function Da(e,t){let n=U(t),o=R(process.cwd(),n.path);if(!await K(J(o)))return;let i=_e?.key===Lo(o)?_e.snapshot:null,r=i===null?await D(o):i.settings,a=mn(r.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=te(e,l.path.split(" "));if(c)for(let d of a.command_to_fields.get(l.command)??[]){let m=d.description??"";Io(c,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)Io(c,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function Mo(e,t,n,o,i){let r=x(n);if(!(r!=="create"&&r!=="update"))try{let a=i??await D(t),s=ae(a,o);sa(e,s,n)}catch{}}function Po(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Ma(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Fo(e){return e.some(t=>t==="--profile")}function Lo(e){return`pm-root:${e}`}function $o(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 Fa(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=${q(t.activationWarnings)}`))}function Kt(e,t,n){if(!e)return;let o=v(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 Jt(e,t=ke){let n=Lo(e);if(_e?.key===n)return _e.snapshot;try{let o=Date.now(),{settings:i,warnings:r}=await t(e),a=await Qo({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...r]};return _e={key:n,snapshot:s},s}catch{return _e={key:n,snapshot:null},null}}async function Ne(e,t,n=D){let o=t?nt(t):"all",i=Ma(e,o);if(at?.key===i)return at.snapshot;try{let r=await n(e),a=await Fe({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?so(t):void 0}),s=await Le({...a,loaded:a.loaded}),l=[...new Set(s.commands.handlers.map(u=>v(u.command)))].filter(u=>u.length>0).sort((u,g)=>u.localeCompare(g)),c=Dr(s.registrations.flags),d=$r(s.commands.handlers,s.registrations.commands),m=Fr(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:r,commandHandlers:l,commandFlagHelp:c,commandDescriptors:m,commandAliases:d,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:u,module:g})=>({name:u,module:g}))};return at={key:i,snapshot:p},p}catch{return at={key:i,snapshot:null},null}}async function La(e){let t=Ve(e);if(t.noExtensions){let a=R(process.cwd(),t.path);return await K(J(a))&&$o((await ke(a)).warnings),null}let n=R(process.cwd(),t.path),o=await Jt(n);if(!o)return null;$o(o.settingsReadWarnings);let i={commandPath:E(e),commandArgs:lo(e)};if(!tt(o.discovery,i))return Kt(t.profile,o,i),null;let r=await Ne(n,i);return r?(Fa(t,r),{hooks:r.hooks,commands:r.commands,parsers:r.parsers,preflight:r.preflight,services:r.services,renderers:r.renderers,registrations:r.registrations,pmRoot:n}):null}async function ja(e){let t=await Ne(e);return t?new Map(t.commandDescriptors):N}async function Ua(e,t){return(await Ai({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function qa(e,t,n){let o=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return Si(e,er.forActiveExtensionHost({pmRoot:e,author:o}),o,v(n))}async function Ha(e,t,n,o=[]){let i=E(e),r=Jn(e.args.map(String),o),a={...t},s={...n},l=R(process.cwd(),n.path),c=await ft({command:i,args:r,options:a,global:s,pm_root:l});n.profile&&c.warnings.length>0&&_(`profile:extensions parser_warnings=${q(c.warnings)}`),r=c.context.args,a=c.context.options,s=c.context.global,fo(N.get(v(i)),r,a,o),Ce(void 0),pt({command:i,args:r,options:{...a},global:{...s},pm_root:l});let d=await nn({command:i,args:r,options:a,global:s,pm_root:l,sdk:qa(l,s,i)});if(s.profile&&d.warnings.length>0&&_(`profile:extensions command_handler_warnings=${q(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 "${i}" failed in extension handler (${m}).${u}`,f.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new C(`Command "${i}" is provided by extensions and is not currently available.`,f.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),Ce(d.result),d.result}var _a=Symbol("pm.wrappedActionHandler");function sd(e,t){let n=e[e.length-1];return n instanceof No?n:t}function va(e,t,n){e&&n.length>0&&_(`profile:extensions ${t}=${q(n)}`)}function ld(e){let t=N.get(v(e.commandPath));if(!t||!po(e.activeRegistrations,e.commandPath))return;let n=Ht(t).length===0?ea(e.commandArgs):Jn(e.commandArgs,e.extensionFlagDefinitions);uo(t,n)}function cd(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 za(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[_a]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let s=sd(a,n),l=Date.now();hn(s);let c=Ve(s),d=T(E(s));if(["package inventory","packages inventory","extension inventory"].includes(d))return await i.apply(this,a);let m=R(process.cwd(),c.path),p=s.args.map(String),u=se(),g=u?ot(u,d,p):[],h=await Na(d,m),y=Pe(s,p,[...g,...h]),S=await ft({command:d,args:p,options:y,global:c,pm_root:m});va(c.profile,"parser_warnings",S.warnings),p=S.context.args,y=S.context.options,re(s,y),c=S.context.global,ld({activeRegistrations:u,commandPath:d,commandArgs:p,extensionFlagDefinitions:g}),c=await Yi(c),kt(s,c),cd(s,a,p),xt(s,y),Ce(void 0),pt({command:d,args:p,options:{...y},global:{...c},pm_root:m});let O=await nn({command:d,args:p,options:y,global:c,pm_root:m,sdk:qa(m,c,d)});if(va(c.profile,"command_handler_warnings",O.warnings),O.handled){Ce(O.result),rn(O.result,{...c,command:d,commandArgs:p,commandOptions:y,pmRoot:m}),c.profile&&_(`profile:command=${d} took_ms=${Date.now()-l}`);return}return await i.apply(this,a)},o[_a]=!0}for(let i of n.commands)t(i)};t(e)}async function Gt(e){N=new Map,ne({overrides:[]}),e&&await Mo(e.rootProgram,e.pmRoot,e.invocationArgv,Ko(),e.settings)}function dd(e,t,n,o){if(t?.flags&&t.flags.length>0){zn(e,t.flags);let i=Gn(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function Ga(e,t,n){let o={core:0,standard:1,full:2,internal:3},i=(r,a)=>{let s=a.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(r,c);for(let d of r.commands)i(d,[...a,d.name()])};for(let r of e.commands)t.has(r.name())||i(r,[r.name()])}async function Wa(e,t){let n=U(t),o=R(process.cwd(),n.path);if(n.noExtensions){await Gt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await Jt(o),r=Ie(t);if(!i){await Gt();return}if(!tt(i.discovery,r)){await Gt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),Kt(Fo(t),i,r);return}let a=await Ne(o,r);if(!a){await Gt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}ne(a.services),N=new Map(a.commandDescriptors),await Mo(e,o,t,a.registrations,a.settings);let s=Vr(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,d=>Br(a.activationWarnings,_,d)),l=new Set(e.commands.map(d=>d.name())),c=d=>{let m=d.split(" ").filter(O=>O.length>0),p=a.commandDescriptors.get(d),u=te(e,m),g=a.commandFlagHelp.get(d),h=p?Gr(p):null;if(u){dd(u,p,g,h);return}let y=Wr(e,m);p?.description&&y.description(p.description);let S=g;p&&(Lr(y,p),p.flags.length>0&&(zn(y,p.flags),S=Gn(y,p.flags)??void 0)),S&&y.addHelpText("after",S),h&&y.addHelpText("after",h),y.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...O)=>{let G=O[O.length-1],j=G instanceof No?G:y,ve=Ve(j),Yt=Date.now(),ct=ot(a.registrations,d,j.args.map(String)),De=Pe(j,j.args.map(String),ct),be=await Ha(j,De,ve,ct);await Xi(ve,be),rn(be,{...ve,command:d,commandArgs:j.args.map(String),commandOptions:De,pmRoot:o}),ve.profile&&_(`profile:command=${d} took_ms=${Date.now()-Yt}`)})};for(let d of s)c(d);Ga(e,l,a.commandDescriptors)}var st=zo(import.meta.url,["../.."])??"0.0.0",w=an(st);async function ba(e){if(!L)return;let t=Reflect.get(e,Ea);typeof t=="string"&&await Qi(t)}async function Ca(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}function Va(e,t){t&&it(t)||(e.hook("preAction",async(n,o)=>{$e=null,L=null,ut(),hn(o);let i=o.optsWithGlobals(),r=Ve(o),a=T(E(o)),s=o.args.map(String),l=Pe(o,s),c={...r};fi(a,{...l,outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),mo(o,a,c,l),await Ca(o,void 0,()=>qi(a,c));let d=R(process.cwd(),r.path),m=await La(o);if(!m){$e=ei({commandName:a,commandArgs:s,commandOptions:l,globalOptions:c,pmRoot:d}),L=await gn({command:a,pm_version:st,args:s,options:l,global:c,pm_root:d}),await ba(e),pn(a,s,l,{source_context:L?.source_context,source_context_source:L?.source_context_source}),un(a),await Qn(a,l,d,Po()),await Zn(a,s,l,c,d);return}ti(m.hooks),ni(m.commands),oi(m.parsers),ii(m.preflight),ne(m.services),ri(m.renderers),ai(m.registrations);let p=ot(m.registrations,a,s);l=Pe(o,s,p),mo(o,a,c,l);let u=await ft({command:a,args:s,options:l,global:c,pm_root:m.pmRoot});c.profile&&u.warnings.length>0&&_(`profile:extensions parser_warnings=${q(u.warnings)}`),s=u.context.args,l=u.context.options,re(o,l),c=u.context.global,xt(o,l);let g=await ci({command:a,args:s,options:l,global:c,pm_root:m.pmRoot,decision:Po()});c.profile&&g.warnings.length>0&&_(`profile:extensions preflight_warnings=${q(g.warnings)}`),s=g.context.args,l=g.context.options,re(o,l),c=g.context.global,xt(o,l);let h=g.decision;await Qn(a,l,m.pmRoot,h),await Zn(a,s,l,c,m.pmRoot);let y=h.run_extension_migrations?await Ca(o,[],()=>Ua(m.registrations.migrations,m.pmRoot)):[];c.profile&&y.length>0&&_(`profile:extensions migration_warnings=${q(y)}`);let S=da(m.registrations.migrations);$e={hooks:m.hooks,commandName:a,commandArgs:s,commandOptions:{...l},globalOptions:{...c},pmRoot:m.pmRoot,profileEnabled:!!c.profile,migrationBlockers:S},Ce(void 0),pt({command:a,args:s,options:{...l},global:{...c},pm_root:m.pmRoot}),L=await gn({command:a,pm_version:st,args:s,options:l,global:c,pm_root:m.pmRoot}),await ba(e),pn(a,s,l,{source_context:L?.source_context,source_context_source:L?.source_context_source}),un(a);let O=await Xo(m.hooks,{command:a,args:s,options:{...l},global:{...c},pm_root:m.pmRoot});c.profile&&O.length>0&&_(`profile:extensions hook_warnings=${q(O)}`),h.enforce_mandatory_migration_gate&&ma(a,l,S)}),e.hook("postAction",async()=>{let n=Ao();ze(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)}))}Va(w);var xa=Symbol("pmCliIdempotentTopLevelRegistration");function Ba(e){let t=e;if(t[xa])return;t[xa]=!0;let n=e.command.bind(e);e.command=((o,...i)=>{let r=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===r||a.aliases().includes(r))?new No(r):n(o,...i)})}async function md(e,t){if(Ba(e),t.setup){let{registerSetupCommands:n}=await Zc();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Qc(),o=typeof t.targetCommandName=="string"&&go.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await ed();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await td();n(e)}}function pd(e){return async t=>{let n=dt(t.errorCode),o=bt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await zi({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 Ka(e){if(e.bootstrapGlobal.noExtensions||it(e.invocationArgv))return;let t=Ie(e.invocationArgv),n=await Jt(e.bootstrapPmRoot);if(n&&tt(n.discovery,t)){let o=await Ne(e.bootstrapPmRoot,t);Ja(o);return}n&&Kt(Fo(e.invocationArgv),n,t),ne({overrides:[]})}function Ja(e){if(!e){ne({overrides:[]});return}ne(e.services)}async function jo(e){ze(!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 Ya(){ze(!0,void 0,{exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await lt({ok:!0,exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=f.SUCCESS}async function Xa(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof C)&&(cn(e.error)||!n))return!1;let o=de(e.error),i=e.error instanceof C?e.error.exitCode:ln(t),r=e.error instanceof C?e.error.context:void 0,a=Aa(r,e.invocationArgv,o),s=Cr(o,a),l=e.bootstrapGlobal.lean?Tt(Nn(o,i,a)):Nn(o,i,a),c=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?ce(l,u=>`${JSON.stringify(u,null,2)}
34
+ `):l,null,2):br(o,a);e.jsonErrors?xe(`${c}
35
+ `):_(c);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:i,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Bt({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:L?.source_context});return await jo({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(fn(dn(e.error,o)),await Ge(Do)),process.exitCode=i,!0}async function Za(e,t){let n=T(A(e.invocationArgv).commandPathTokens.join(" "))||Fn(e.invocationArgv),o=`unknown command '${n}'`,i=R(process.cwd(),e.bootstrapGlobal.path),r=await ja(i),a=Ie(e.invocationArgv),s=await Yn(i,{},Re(a)),l=await Ye({message:o},w,r,{failedExtensions:s}),c=Dn(l.message,l.commandName,l.allowedTypes,{unknownCommandExamples:l.unknownCommandExamples,unknownCommandNextSteps:l.unknownCommandNextSteps,attemptedCommand:l.attemptedCommand,normalizedInvocationArgs:l.normalizedInvocationArgs,providedOptionFlags:l.providedOptionFlags,unknownOptionSuggestions:l.unknownOptionSuggestions,suggestedRetryCommand:l.suggestedRetryCommand,failedExtensions:s}),{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:c.code,errorMessage:c.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await Bt({command:n,error_code:c.code,error_category:d,exit_code:f.USAGE,error_message:c.detail,command_resolution:m,resolution_stage:"parse"}),u=e.jsonErrors?await qn({message:o},w,r,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await Un({message:o},w,r,{failedExtensions:s}),g=Mn(u,e.jsonErrors,s);await jo({errorMessage:o,exitCode:f.USAGE,classificationCode:c.code,errorCategory:d,commandResolution:m,resolutionStage:"parse"}),e.jsonErrors?xe(`${g}
36
+ `):_(g),p&&await Ge(Do),process.exitCode=f.USAGE}async function Qa(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let i=A(e.invocationArgv);return i.requested&&!Je(w,i.commandPathTokens)?(await Za(e,t),!0):(await Ya(),!0)}async function es(e,t){let n=await Ye(e.error,w,N),o=Dn(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:i,commandResolution:r}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),a=await Bt({command:e.attemptedCommand,error_code:o.code,error_category:i,exit_code:f.USAGE,error_message:o.detail,command_resolution:r,resolution_stage:"parse",source_context:L?.source_context}),s=e.jsonErrors?await qn(e.error,w,N,e.bootstrapGlobal.lean===!0):await Un(e.error,w,N),l=await ta(o.code,e.bootstrapPmRoot,{},Re(Ie(e.invocationArgv))),c=Mn(s,e.jsonErrors,l);await jo({errorMessage:n.message,exitCode:f.USAGE,classificationCode:o.code,errorCategory:i,commandResolution:r,resolutionStage:"parse"}),e.jsonErrors?xe(`${c}
37
+ `):_(c),a&&await Ge(Do),process.exitCode=f.USAGE}function ts(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 ns(e){let t=e.error.code,n=String(e.error.message??"");if(!await Qa(e,t,n)){if(t==="commander.version"){await Ya();return}await es(e,t)}}async function Uo(e){let t=U(e.invocationArgv),n=R(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:x(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:pd({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Ka({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Xa(o,sn(e.error))){if(ts(e.error)){await ns(o);return}await Ia({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}function ud(e,t,n){let o=n.requested?n.commandPathTokens:M(t),i=W(o);if(i&&!te(e,[...i.canonical_argv]))throw new ka(f.USAGE,"commander.unknownCommand",`unknown command '${i.alias}'`)}function fd(e,t){let n=me(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let a=me(t.slice(n+1));if(a===void 0)return;n+=a+1}let o=Vt.get(t[n]),i=t.slice(n).filter(a=>!["--global","--project","--local"].includes(a)),r=o?.find(a=>a.alias.split(" ").every((s,l)=>i[l]===s));r?.lifecycle==="deprecated"&&Reflect.set(e,Ea,r.alias)}async function gd(e,t){w=an(st),w.hook("preAction",(r,a)=>{t.configurationOnly=["item mutate","item complete"].includes(E(a))&&a.optsWithGlobals().dryRun===!0}),Va(w,e),at=null,_e=null,N=new Map,si();let n=[...e],o,i;try{let r=He(e);n=r.argv,fd(w,e);let a=[process.argv[0],process.argv[1],...n],s=n.length===0,l=U(n);if(l.authorMissingValue)throw new C("--author requires a non-empty value.",f.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=Ni(l.author),vo(r),i=Ti(n);let c=ho(n);await md(w,c),kn(w,!0),wo(w,n)?await Wa(w,n):(N=new Map,ne({overrides:[]})),_o(n)&&await Da(w,n),kn(w);let m=A(n);if(ud(w,n,m),yo(n)&&ur(w,n),za(w),await aa(w,n,N,e))return;if(m.requested&&!Je(w,m.commandPathTokens))throw new ka(f.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||ie(n)&&x(n)===void 0){w.outputHelp();return}if(it(n)){await w.parseAsync(a);return}let u=R(process.cwd(),l.path),g=await D(u),h=await Ir(n,u,l.noExtensions,Ne);await vi({pmRoot:u,packages:h?.contextIntentPackages},()=>bi({env:{...process.env,PM_PATH:u},argv:a,cwd:process.cwd()},()=>Ci(g.agent_identity.harness_signals,()=>w.parseAsync(a),{probesEnabled:g.agent_identity?.probes_enabled})))}catch(r){await Uo({error:r,invocationArgv:n})}finally{i?.(),o?.()}}async function jp(e=process.argv.slice(2)){let t=e;try{t=He(e).argv}catch{}let n=ya(t),o={configurationOnly:n!==void 0},i=()=>o.configurationOnly,r=async()=>{try{await Di(process.env,()=>gd(e,o))}catch(a){await Uo({error:a,invocationArgv:[...e]})}};if(n!==void 0){let a=R(process.cwd(),U(t).path),s=R(process.cwd(),n.path),l=Bo(process.cwd());await yt(a,()=>yt(s,()=>yt(l,r,i),i),i)}else await r()}var Up={activationCommandMatchesProbe:to,applyDynamicExtensionRootHelpVisibility:Ga,bootstrapProfileEnabled:Fo,buildBootstrapActivationProbe:Ie,buildPostActionTelemetryOutcome:Ao,buildPmCliRecoveryContext:Aa,buildRuntimeExtensionDiscoverySnapshotCacheKey:Lo,buildRuntimeExtensionActivationScope:nt,buildRuntimeExtensionSnapshotCacheKey:Ma,buildRuntimeExtensionFilterForProbe:so,addRuntimeFieldOption:Io,collectActivationCommandCandidates:Re,collectExtensionFlagDefinitionsForCommand:qt,collectExtensionFlagDefinitionsForInvocation:ot,collectLeadingCommandArgs:eo,collectParsedActivationCommandArgs:lo,collectRuntimeFieldLooseFlagDefinitionsForCommand:Na,commandHasLongOption:Pa,commandHasShortOption:$a,commandPathNeedsSearchExtensions:no,commandPathNeedsTemplateExtensions:Lt,describeUnknownError:de,defaultPreflightDecision:Po,discoveryNeedsActivationForProbe:tt,emitExtensionProfile:Fa,emitExtensionSkippedProfile:Kt,emitSettingsReadWarnings:$o,ensureIdempotentTopLevelCommandRegistration:Ba,enforceExplicitRetryForFlagTypos:vo,envFlagEnabled:Ta,executeRegisteredRuntimeMigrations:Ua,extractCommandScopedOptions:Pe,extensionActivationCommands:Ft,extensionCapabilities:et,extensionNeedsActivationForProbe:jt,extensionProvidesTemplatesRuntime:io,hasAnyCapability:Te,hasGlobalExtensionContributions:ro,handleGenericRunPmCliError:Ia,handleRunPmCliCommanderError:ns,handleRunPmCliError:Uo,handleRunPmCliHelpDisplayError:Qa,handleRunPmCliKnownError:Xa,handleRunPmCliCommanderUsageError:es,handleUnknownHelpCommandError:Za,inferMissingFieldsFromErrorMessage:Sa,inferPostActionErrorCode:So,inferPostActionFailureMessage:Eo,invocationRequestsVersion:rt,isCommanderError:cn,loadRuntimeExtensionCommandDescriptorsForRecovery:ja,loadRuntimeExtensionDiscoverySnapshot:Jt,loadRuntimeExtensionSnapshot:Ne,maybeLoadRuntimeExtensions:La,maybeAttachCreateUpdatePolicyHelpText:Mo,maybeLogHandledCliErrorToSentry:Bt,matchesStaticExtensionCommand:Mt,normalizeTelemetryCommandResolution:Co,normalizeTelemetryErrorCategory:ko,normalizeTelemetryResolutionStage:xo,normalizeThrownExitCode:ln,probeUsesAnyFlag:oo,prepareExtensionServicesForRunPmCliError:Ka,readRecordBoolean:bo,readRecordNumber:zt,readRecordString:we,recordCliReadOutputInvocationProvenance:co,registerDynamicExtensionCommandPaths:Wa,registerRuntimeSchemaFieldFlags:Da,resolveCoreCommandRegistrationSelection:ho,resolveStaticExtensionActivationDecision:ao,resolveUnknownHelpToken:Fn,readThrownExitCode:sn,runAndClearAfterCommandHooks:lt,runRequiredExtensionCommand:Ha,shouldAttachRichHelpTextForInvocation:yo,shouldLogHandledErrorToSentry:Ra,shouldRegisterDynamicExtensionPaths:wo,shouldRegisterRuntimeSchemaFlags:_o,shouldHandleRunPmCliCommanderError:ts,setActiveExtensionHookContextForTest:Kc,setActiveRuntimeExtensionCommandDescriptorsForTest:Jc,setRecoveredExtensionServices:Ja,toLooseFieldDefinitionType:Ro,isImporterOrExporterCommandPath:po,validateDynamicExtensionCommandInvocation:fo,wrapProgramActionsForExtensionHandlers:za,wrapThrownErrorForSentry:dn};export{Up as _testOnly,jp as runPmCli};
38
38
  //# sourceMappingURL=main.js.map