@unbrained/pm-cli 2026.11.29 → 2026.12.1

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 (168) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/commander-usage.js +10 -10
  3. package/dist/cli/error-guidance.js +5 -5
  4. package/dist/cli/extension-command-help.js +6 -6
  5. package/dist/cli/help-json-payload.js +7 -7
  6. package/dist/cli/main.js +5 -5
  7. package/dist/cli/register-list-query.js +10 -10
  8. package/dist/cli/register-mutation.js +3 -3
  9. package/dist/cli/runtime/invocation-command-path.js +2 -0
  10. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  11. package/dist/cli-bundle/bundle-manifest.json +1 -1
  12. package/dist/cli-bundle/chunks/{chunk-JQHLOSSS.js → chunk-3HKPVOAN.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-ZSBPE36C.js → chunk-3KEMIPKG.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-JFPCL45G.js → chunk-4YQMQOUO.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-EYEQC3L2.js → chunk-4YYFY33T.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-A5ZEMOVR.js +2 -0
  17. package/dist/cli-bundle/chunks/{chunk-WLZ5KVM2.js → chunk-AHV3CSQG.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-AJLU6KLW.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-R6M5OGJH.js → chunk-C6WM6ZN4.js} +3 -3
  20. package/dist/cli-bundle/chunks/chunk-CBUC4X7Q.js +127 -0
  21. package/dist/cli-bundle/chunks/{chunk-K3MVVDLN.js → chunk-CWPR234D.js} +2 -2
  22. package/dist/cli-bundle/chunks/chunk-I4SPJQQI.js +3 -0
  23. package/dist/cli-bundle/chunks/{chunk-VI3A7UZ2.js → chunk-L2ZSSMYY.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-DBASKWBO.js → chunk-MZZ4ZJ5Z.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-CV2B4JUB.js → chunk-NA6D75V5.js} +2 -2
  26. package/dist/cli-bundle/chunks/chunk-NRQCBUYD.js +113 -0
  27. package/dist/cli-bundle/chunks/{chunk-ZK4CY24V.js → chunk-OBPO6V7H.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-3US5T6B2.js → chunk-OKEJ4U2I.js} +7 -7
  29. package/dist/cli-bundle/chunks/{chunk-3E53F7QY.js → chunk-OXC5KBIQ.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-NLHNB2L3.js → chunk-PCDTWL6V.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-LQEB6GSY.js → chunk-Q6GLSAJY.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-3TK2YOVB.js → chunk-Q6K7HWZ7.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-QDV7S2QS.js +2 -0
  34. package/dist/cli-bundle/chunks/{chunk-Q6GIFUCW.js → chunk-SY5C3U32.js} +3 -3
  35. package/dist/cli-bundle/chunks/{chunk-L7HON3BE.js → chunk-U7RBJGLF.js} +23 -23
  36. package/dist/cli-bundle/chunks/chunk-WSEIEDEK.js +2 -0
  37. package/dist/cli-bundle/chunks/{chunk-FRYNDVLN.js → chunk-XME6GIFQ.js} +2 -2
  38. package/dist/cli-bundle/chunks/{chunk-WNB62BGK.js → chunk-YSVOXCYH.js} +2 -2
  39. package/dist/cli-bundle/chunks/{chunk-KCR4NF2A.js → chunk-ZL6J6JYT.js} +6 -6
  40. package/dist/cli-bundle/chunks/{field-option-collisions-OZE43TOH.js → field-option-collisions-BBGTV7AD.js} +2 -2
  41. package/dist/cli-bundle/chunks/item-revision-3LENTXYF.js +2 -0
  42. package/dist/cli-bundle/chunks/item-transaction-66RDV7PH.js +2 -0
  43. package/dist/cli-bundle/chunks/{linked-resource-value-list-2655COY2.js → linked-resource-value-list-E2DX52LY.js} +2 -2
  44. package/dist/cli-bundle/chunks/{mutation-actor-QOKPDYM4.js → mutation-actor-NHN33ITJ.js} +2 -2
  45. package/dist/cli-bundle/chunks/{mutation-admission-JNJHB3E6.js → mutation-admission-PGKJTCG6.js} +2 -2
  46. package/dist/cli-bundle/chunks/{register-list-query-YGVUE4YZ.js → register-list-query-7S5QWDTI.js} +11 -11
  47. package/dist/cli-bundle/chunks/{register-mutation-3JVZQDHH.js → register-mutation-2F6JUBST.js} +5 -5
  48. package/dist/cli-bundle/chunks/{register-operations-LCHUHKRA.js → register-operations-ET3UKPYK.js} +2 -2
  49. package/dist/cli-bundle/chunks/{register-setup-IJ7M3VUK.js → register-setup-I63QTFCU.js} +2 -2
  50. package/dist/cli-bundle/chunks/{stage-7BD7U2BX.js → stage-4ZCF74G4.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-NO5MUY4I.js → chunk-2DGKVXFT.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-2UWKU2BQ.js +3 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-42SU4LK3.js → chunk-4SCFAWAW.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-LSVRZ4KQ.js → chunk-6BKT6XQN.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-6IY5CVGJ.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-7A6SEZEY.js +4 -0
  57. package/dist/cli-bundle/focused-chunks/{chunk-LKTRICZR.js → chunk-BHNBPCHP.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-PPCBCPIZ.js → chunk-EQCQTYKO.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-NNLENKU7.js → chunk-HTDYNY4L.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-S5VG7RFY.js → chunk-JPZGC3W4.js} +5 -5
  61. package/dist/cli-bundle/focused-chunks/{chunk-ACTBMSCH.js → chunk-KNBGHCIP.js} +3 -3
  62. package/dist/cli-bundle/focused-chunks/chunk-N64AC5G6.js +100 -0
  63. package/dist/cli-bundle/focused-chunks/{chunk-EUDAUT6T.js → chunk-OG57ESZK.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{chunk-2CQFGJQ6.js → chunk-P2H3GTJK.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-QTV6UE2Q.js → chunk-PT7RT3T6.js} +26 -26
  66. package/dist/cli-bundle/focused-chunks/chunk-QZRYGYTI.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-BPOU2S44.js → chunk-SQ72CVUH.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/chunk-SQMOF65W.js +2 -0
  69. package/dist/cli-bundle/focused-chunks/chunk-T3ILWAEV.js +2 -0
  70. package/dist/cli-bundle/focused-chunks/{chunk-KWKPX36T.js → chunk-TR22GU7M.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{chunk-TSZVCALS.js → chunk-TXTPAFHJ.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/chunk-VK3IE3TS.js +29 -0
  73. package/dist/cli-bundle/focused-chunks/{chunk-GTUPHXKR.js → chunk-VQIC3UZB.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{chunk-S4AC7OMI.js → chunk-W4JMV7GF.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/{field-option-collisions-HABQYZMQ.js → field-option-collisions-2C6DLUC4.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/item-revision-723XCQPS.js +2 -0
  77. package/dist/cli-bundle/focused-chunks/{item-transaction-YZ2PUPGM.js → item-transaction-2K4SFLJ7.js} +2 -2
  78. package/dist/cli-bundle/focused-chunks/{mutation-actor-DJ2VRLKG.js → mutation-actor-DJMZUIZI.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/mutation-admission-SDWQVVHN.js +2 -0
  80. package/dist/cli-bundle/focused-chunks/{stage-FEJT2UCG.js → stage-QBZIK3T5.js} +2 -2
  81. package/dist/cli-bundle/main.js +27 -27
  82. package/dist/cli-bundle/sdk-authoring.js +1 -1
  83. package/dist/cli-bundle/sdk-contracts.js +1 -1
  84. package/dist/cli-bundle/sdk-core.js +1 -1
  85. package/dist/cli-bundle/sdk-governance.js +1 -1
  86. package/dist/cli-bundle/sdk-graph.js +1 -1
  87. package/dist/cli-bundle/sdk-merge.js +63 -63
  88. package/dist/cli-bundle/sdk-query.js +1 -1
  89. package/dist/cli-bundle/sdk-runtime.js +1 -1
  90. package/dist/cli-bundle/sdk-testing.js +1 -1
  91. package/dist/cli-bundle/sdk.js +2 -2
  92. package/dist/core/extensions/reserved-host-flags.js +1 -1
  93. package/dist/core/shared/secret-rules.d.ts +86 -12
  94. package/dist/core/shared/secret-rules.js +7 -5
  95. package/dist/core/shared/url-credentials.d.ts +4 -2
  96. package/dist/core/shared/url-credentials.js +1 -1
  97. package/dist/sdk/cli-bootstrap.js +1 -1
  98. package/dist/sdk/cli-contracts/flag-contracts.d.ts +50 -0
  99. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  100. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +3 -1
  101. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  102. package/dist/sdk/context-intent-contracts.js +1 -1
  103. package/dist/sdk/extension/command-options.js +1 -1
  104. package/dist/sdk/lifecycle/expect-hash-admission.d.ts +15 -0
  105. package/dist/sdk/lifecycle/expect-hash-admission.js +2 -0
  106. package/dist/sdk/lifecycle/item-revision.d.ts +4 -1
  107. package/dist/sdk/lifecycle/item-revision.js +1 -1
  108. package/dist/sdk/mutation-guard.js +1 -1
  109. package/dist/sdk/output-contracts.js +1 -1
  110. package/dist/sdk/output-projection.d.ts +1 -1
  111. package/dist/sdk/output-projection.js +1 -1
  112. package/dist/sdk/public-surface.json +1 -1
  113. package/dist/sdk/query/aggregate.js +1 -1
  114. package/dist/sdk/query/context.js +1 -1
  115. package/dist/sdk/query/list.js +1 -1
  116. package/dist/sdk/query/next.js +1 -1
  117. package/dist/sdk/query/search-contracts.js +1 -1
  118. package/dist/sdk/read-output/surfaces.js +1 -1
  119. package/dist/sdk/read-output-budget.d.ts +1 -1
  120. package/dist/sdk/read-output-budget.js +1 -1
  121. package/dist/sdk/read-output-contracts.js +1 -1
  122. package/dist/sdk/read-output-rows.js +1 -1
  123. package/docs/COMMANDS.md +37 -0
  124. package/docs/CONFIGURATION.md +22 -3
  125. package/docs/MUTATION_INTEGRITY.md +226 -10
  126. package/docs/READ_OUTPUT_CONTRACTS.md +5 -0
  127. package/docs/SDK.md +35 -9
  128. package/docs/agent-task-token-baseline.json +1 -1
  129. package/marketplace.json +1 -1
  130. package/package.json +1 -1
  131. package/packages/pm-beads/package.json +1 -1
  132. package/packages/pm-calendar/package.json +1 -1
  133. package/packages/pm-command-kit/package.json +1 -1
  134. package/packages/pm-digital-twin/package.json +1 -1
  135. package/packages/pm-governance-audit/package.json +1 -1
  136. package/packages/pm-guide-shell/package.json +1 -1
  137. package/packages/pm-kanban/package.json +1 -1
  138. package/packages/pm-lifecycle-hooks/package.json +1 -1
  139. package/packages/pm-linked-test-adapters/package.json +1 -1
  140. package/packages/pm-search-advanced/package.json +1 -1
  141. package/packages/pm-templates/package.json +1 -1
  142. package/packages/pm-todos/package.json +1 -1
  143. package/packages/pm-vcs/package.json +1 -1
  144. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  145. package/plugins/pm-claude/package.json +1 -1
  146. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  147. package/plugins/pm-codex/package.json +1 -1
  148. package/plugins/pm-codex/plugin.json +1 -1
  149. package/runtime-dependencies.json +1 -1
  150. package/dist/cli-bundle/chunks/chunk-4EBHZBM2.js +0 -2
  151. package/dist/cli-bundle/chunks/chunk-CNZOC6JD.js +0 -2
  152. package/dist/cli-bundle/chunks/chunk-JV7LREUF.js +0 -3
  153. package/dist/cli-bundle/chunks/chunk-NRCGGNOE.js +0 -2
  154. package/dist/cli-bundle/chunks/chunk-PY6A7ULK.js +0 -125
  155. package/dist/cli-bundle/chunks/chunk-RWHS77ME.js +0 -113
  156. package/dist/cli-bundle/chunks/chunk-SV27NNXQ.js +0 -2
  157. package/dist/cli-bundle/chunks/item-revision-3WXNNFLP.js +0 -2
  158. package/dist/cli-bundle/chunks/item-transaction-DJ5GAITL.js +0 -2
  159. package/dist/cli-bundle/focused-chunks/chunk-5NSWNLFE.js +0 -2
  160. package/dist/cli-bundle/focused-chunks/chunk-BPBKHY6H.js +0 -100
  161. package/dist/cli-bundle/focused-chunks/chunk-BZ3PUUPG.js +0 -2
  162. package/dist/cli-bundle/focused-chunks/chunk-KLOHZNJ4.js +0 -2
  163. package/dist/cli-bundle/focused-chunks/chunk-MYWUMVCZ.js +0 -4
  164. package/dist/cli-bundle/focused-chunks/chunk-NZA2LP4Y.js +0 -27
  165. package/dist/cli-bundle/focused-chunks/chunk-TX24L7RQ.js +0 -3
  166. package/dist/cli-bundle/focused-chunks/chunk-WJAUHPXD.js +0 -2
  167. package/dist/cli-bundle/focused-chunks/item-revision-YH5R7YPW.js +0 -2
  168. package/dist/cli-bundle/focused-chunks/mutation-admission-3SECKVKY.js +0 -2
@@ -1,8 +1,8 @@
1
- import{hasSubcommandFlagContractsForCommand as X,PM_COMMAND_ALIAS_CONTRACTS as x,PM_CORE_COMMAND_NAMES as D,resolvePmCommandAlias as Y,resolvePmCommandOperation as v}from"../sdk/cli-contracts.js";import{commandOptionFlagLabel as T,resolveCommandOptionPolicyState as b,resolveTypeDefinition as K,EXIT_CODE as C,writeStderr as Q,writeStdout as Z}from"../sdk/runtime-primitives.js";import{buildDynamicExtensionHelpOptionSummaries as ee,buildExtensionInheritedHelpOptionSummaries as te,isExtensionCreatedCommand as ne,mergeHelpOptionSummaries as ie,findCommandByPath as $,findDirectChildCommand as oe,commandAliases as se}from"./extension-command-help.js";import{getPmCommandHelpVisibilityTier as S,isFullHelpDiscovery as E,normalizeHelpCommandPath as A,resolveHelpBundleForPath as re,resolveHelpDetailMode as ae,resolveHelpNarrative as le,ROOT_HELP_BUNDLE as ce}from"./help-content.js";import{getCommandPath as F}from"./registration-helpers.js";import{parseBootstrapGlobalOptions as ue,parseBootstrapHelpRequest as j,parseBootstrapCommandName as de,parseBootstrapTypeValue as pe}from"./bootstrap-args.js";import{extractProvidedOptionFlags as me,renderPmCommand as fe}from"./argv-utils.js";import{formatCommanderErrorForJson as he}from"./error-guidance.js";import{BUILTIN_TYPE_HELP_VALUES as ge,buildUnknownCommandGuidanceFromRuntime as ye,isKnownHelpCommandPath as _e}from"./commander-usage.js";import{attachOutputTokenAccounting as ve}from"../sdk/output-token-accounting.js";import{resolveCreateExplicitEmptyFlag as be}from"../sdk/agent/create-option-policy.js";import{formatPmPositionalActionFlagTip as Ce,PM_POSITIONAL_ACTION_CONTRACTS as Se,resolvePmPositionalActionContract as M}from"../sdk/cli-contracts/grammar-contracts.js";import{resolvePmCommandCapabilityFamily as O,resolvePmCommandVisibilityTier as _}from"../sdk/agent-capability-contracts.js";import{redactRefusalArgv as R}from"./runtime/refusal-credential-redaction.js";const L={core:0,standard:1,full:2,internal:3};function w(t,e,i=!0){const n=e.get(v(t));if(n)return n;if(!i)return;const o=[...e.entries()].filter(([r])=>r.startsWith(`${t} `)).map(([,r])=>r);if(o.length===0)return;const s=o.reduce((r,l)=>L[l.tier]<L[r]?l.tier:r,"internal"),c=new Set(o.map(({family:r})=>r));return{tier:s,family:c.size===1?o[0].family:"extensions"}}function P(t,e){if(e.length===0)return t;const i=$(t,e);if(i)return i;const n=e.join(" ");if(v(n)!==n||!D.some(o=>o===n)&&!X(n)&&!M(n)&&!_e(t,e))return null;for(let o=e.length-1;o>0;o-=1){const s=$(t,e.slice(0,o));if(s)return s}return e.length===1?t:null}function Ae(t){const e=t.match(/[<[]([^>\]]+)[>\]]/);if(!e)return null;const i=e[1]?.trim();return i&&i.length>0?i:null}function H(t){const e=t;if(typeof e.attributeName=="function"){const i=e.attributeName();return typeof i=="string"&&i.trim().length>0?i.trim():null}return typeof e.attributeName=="string"&&e.attributeName.trim().length>0?e.attributeName.trim():null}function N(t){const e=new Map;for(const i of t){const n=i,o=H(i);if(!o||typeof n.long!="string"||n.long.trim().length===0)continue;const s=e.get(o)??[];s.push(n.long.trim()),e.set(o,s)}for(const[i,n]of e.entries())e.set(i,[...new Set(n.map(o=>o.trim()).filter(o=>o.length>0))].sort((o,s)=>o.localeCompare(s)));return e}function Oe(t){return fe(t)}function I(t){const e=t.options??[],i=N(e);return e.map(n=>{const o=n,s=typeof o.flags=="string"?o.flags.trim():"",c=typeof o.description=="string"?o.description.trim():"",r=H(n),d=(r?i.get(r)??[]:[]).filter(f=>f!==o.long).map(f=>f.trim()).filter(f=>f.length>0),a=c.match(/^Alias for ([^ ]+)/i),u=a&&a[1]?a[1].trim():null,p=o.mandatory===!0||c.includes("[required]")||c.toLowerCase().includes("required;"),g=s.includes("<"),h=g||s.includes("["),m={flags:s,long:typeof o.long=="string"?o.long:null,short:typeof o.short=="string"?o.short:null,description:c,takes_value:h,value_required:g,value_name:Ae(s),variadic:o.variadic===!0,required:p,aliases:d,alias_for:u};return o.defaultValue!==void 0&&(m.default_value=o.defaultValue),m})}function B(t){const e=new Map,i=[];for(const n of t){if(n.alias_for&&n.long){i.push(n);continue}n.long&&e.set(n.long,n)}for(const n of i){const o=n.alias_for,s=e.get(o);if(!s)continue;const c=n.long,r=new Set([...s.aliases??[],c]);s.aliases=[...r].sort((l,d)=>l.localeCompare(d))}return t.filter(n=>!n.alias_for||!n.long?!0:!e.has(n.alias_for))}function J(t){const e=t;return(Array.isArray(e.registeredArguments)?e.registeredArguments:Array.isArray(e._args)?e._args:[]).map(n=>{const o=typeof n.name=="function"?n.name():typeof n.name=="string"?n.name:"argument",s=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():null;return{name:o.trim(),required:n.required===!0||s?.toLowerCase().startsWith("required;")===!0,variadic:n.variadic===!0,description:s}})}function U(t,e=new Map,i=!1){const n=t.createHelp().visibleCommands(t);return(i?[...new Set([...n,...t.commands])]:n).filter(s=>s.name()!=="help"||t.parent===null).filter(s=>!i||(S(s)??_(s.name()))!=="internal").map(s=>{const c=A(F(s)),r=c,l=S(s),d=w(c,e,l!==void 0),a=x.find(({alias:u})=>u===c);return{name:s.name().trim(),aliases:se(s),description:s.description().trim(),tier:d?.tier??l??_(r),family:d?.family??O(r),...a?{alias_for:a.canonical,alias_lifecycle:a.lifecycle,...a.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((s,c)=>s.name.localeCompare(c.name))}function we(t,e,i){if(!i)return e;const n=i.examples??[],o=i.failure_hints??[];return{intent:i.intent??i.description??e.intent,examples:t==="detailed"?n.length>0?[...n]:[...e.examples]:n.length>0?[n[0]]:[...e.examples],tips:t==="detailed"?o.length>0?[...o]:[...e.tips]:[],detail_mode:t}}function Pe(t,e,i,n,o){const s=t!==void 0&&re(t)===ce,c=s?{intent:e,examples:[`pm ${t} --help`],tips:[],detail_mode:i}:le(t,i),r=o?"positional_action":n?.intent||n?.description?"extension":s?e?"command_description":"unavailable":t?"help_bundle":"root_help_bundle";return{narrative:we(i,c,n),intentSource:r}}function He(t,e){return t===void 0?null:e?.tier??_(t)}function qe(t,e){return t===void 0?null:e?.family??O(t)}function xe(t,e,i){if(!(e!==t||!i))return x.map(n=>({alias:n.alias,canonical:n.canonical,canonical_argv:[...n.canonical_argv],available:P(t,n.canonical.split(" "))!==null,lifecycle:n.lifecycle,hidden:n.hidden,deprecated:n.lifecycle==="deprecated"}))}function V(t,e,i,n,o=new Map,s=!1){if(!t){const r=J(e),l=U(e,o,s),d=new Set(l.map(({name:a})=>a));return{arguments:r,options:n,subcommands:[...l,...Se.filter(({parent:a,action:u})=>a===i&&!d.has(u)).map(({action:a,description:u})=>({name:a,aliases:[],description:u,tier:_(i.split(" ")[0]),family:O(i.split(" ")[0])}))].sort((a,u)=>a.name.localeCompare(u.name)),usage:[i,r.reduce((a,u)=>u.required?a.replace(`[${u.name}${u.variadic?"...":""}]`,`<${u.name}${u.variadic?"...":""}>`):a,e.usage())].filter(a=>a.length>0).join(" ")}}const c=new Set(t.accepted_flags);return{arguments:t.slots.map(({name:r,required:l,variadic:d,value_kind:a,polymorphic:u})=>({name:r,required:l,variadic:d,description:u?`Polymorphic ${a} value; inspect the action contract before mutation.`:`${a.replaceAll("_"," ")} value.`})),options:n.filter(({long:r,aliases:l})=>r!==null&&c.has(r)||l.some(d=>c.has(d))),subcommands:[],usage:[t.command,...t.slots.map(({name:r,required:l,variadic:d})=>{const a=d?`${r}...`:r;return l?`<${a}>`:`[${a}]`})].join(" ")}}function Te(t,e){return e!==void 0&&ne(t)?{inherited_options:te(e)}:{}}function k(t,e,i,n,o){const s=ae(i),c=E(i),r=A(F(e)),l=A(n.join(" ")),d=l.length>r.length?l:r,a=M(d),u=a?.command??r,p=u.length>0?u:void 0,g=p,h=p?o.get(v(p)):void 0,m=p?w(p,o,S(e)!==void 0):void 0,{narrative:f,intentSource:W}=Pe(p,e.description().trim(),s,h,a!==void 0),z=B(ie(I(e),ee(h))),y=V(a,e,u,z,o,c),q=xe(t,e,c);return{format:"pm_help_v1",detail_mode:s,root_command:t.name(),requested_path:n,resolved_path:u.length>0?u:t.name(),visibility_tier:He(g,m),capability_family:qe(g,m),description:a?.description??e.description(),usage:y.usage,intent:a?.description??f.intent,intent_source:W,examples:a?[a.example]:f.examples,tips:a?[Ce(a.accepted_flags)]:f.tips,arguments:y.arguments,options:y.options,...Te(e,h),subcommands:y.subcommands,has_subcommands:y.subcommands.length>0,...q===void 0?{}:{command_aliases:q}}}async function Ye(t,e,i,n=e){const o=ue(e);if(!o.json)return!1;const s=j(e);if(!s.requested)return!1;const c=P(t,s.commandPathTokens);if(!c){if(!o.quiet){const r=R(e),l=`unknown command '${R(s.commandPathTokens).join(" ")}'`,d=ye(l,t,i,r),a=he(l,"help",ge,C.USAGE,{...d,attemptedCommand:Oe(r),normalizedInvocationArgs:[...r],providedOptionFlags:me(r)}),u=o.tokenAccounting?ve(a,p=>`${JSON.stringify(p,null,2)}
2
- `):a;Q(`${JSON.stringify(u,null,2)}
3
- `)}return process.exitCode=C.USAGE,!0}if(!o.quiet){const r=k(t,c,e,s.commandPathTokens,i),l=j(n).commandPathTokens;r.requested_path=l;const d=Y(l.join(" "));d&&(r.resolved_path=d.canonical),c===t&&!E(e)&&(r.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),Z(`${JSON.stringify(r,null,2)}
4
- `)}return process.exitCode=C.SUCCESS,!0}function $e(t,e){const i=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${e.types.join("|")}`];return t==="create"&&i.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),i.join(`
5
- `)}function Ee(t,e){if(e.options.length===0){t.push(" type options: none");return}t.push(" type options:");for(const i of e.options){const n=i.required?" (required)":"",o=i.aliases??[];t.push(` - ${i.key}${n}`),t.push(` values: ${i.values.length>0?i.values.join("|"):"any non-empty string"}`),t.push(` aliases: ${o.length>0?o.join("|"):"none"}`),i.description&&i.description.trim().length>0&&t.push(` description: ${i.description.trim()}`)}}function Fe(t,e){const i=t==="create"?new Set(["title","type"]):new Set,n=new Set(i);if(t==="create")for(const o of[...e.required_create_fields,...e.required_create_repeatables])n.add(o);return{progressive:i,strict:n}}function je(t,e,i,n){const o=new Set(i),s=n.filter(l=>!o.has(l)),c=l=>l.length>0?l.map(d=>T("create",d)).join(", "):"none";t.push(` required in strict mode: ${c(s)}`);const r=s.map(be).filter(l=>l!==void 0);t.push(` explicit empty assertion: ${r.length>0?r.join(", "):"none"}`),["Reminder","Meeting","Event"].includes(e.name)&&(t.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),t.push(" strict parity remains available via --create-mode strict."))}function G(t,e,i){const n=pe(i);if(!n)return $e(t,e);const o=K(n,e);if(!o){const m=e.types.join("|");return["",`Type-aware option policies: type "${n}" is not in the active registry.`,` active type values: ${m}`].join(`
6
- `)}const s=i.indexOf("--"),c=s<0?i:i.slice(0,s),r=c.findIndex(m=>m==="--create-mode"||m.startsWith("--create-mode=")),l=r<0?void 0:c[r]?.startsWith("--create-mode=")?c[r]?.slice(14):c[r+1],d=t==="create"&&l?.toLowerCase()==="strict",a=Fe(t,o),u=b(o,t,a.progressive),p=b(o,t,d?a.strict:a.progressive),g=m=>m.length>0?m.map(f=>T(t,f)).join(", "):"none",h=["",`Type-aware option policies for ${o.name}:`,` required: ${g(p.required)}`,` disabled: ${g(p.disabled)}`,` hidden: ${g(p.hidden)}`];if(t==="create"){const m=b(o,t,a.strict);je(h,o,u.required,m.required)}return Ee(h,o),p.errors.length>0&&h.push(` config errors: ${p.errors.join("; ")}`),h.join(`
7
- `)}function Me(t,e,i){const n=de(i);if(n!=="create"&&n!=="update")return;const o=oe(t,n);o&&o.addHelpText("after",G(n,e,i))}const Ke={attachCreateUpdatePolicyHelpText:Me,buildCreateUpdatePolicyHelpText:G,buildJsonHelpPayload:k,buildPositionalActionHelpProjection:V,buildHelpArgumentSummaries:J,buildHelpOptionSummaries:I,buildHelpSubcommandSummaries:U,buildOptionAliasMap:N,compactHelpOptionAliases:B,readOptionAttributeName:H,resolveCommandFromPathTokens:P,resolveExtensionCommandSurface:w};export{Ke as _testOnly,Me as attachCreateUpdatePolicyHelpText,Ye as maybeRenderBootstrapJsonHelp};
1
+ import{hasSubcommandFlagContractsForCommand as X,PM_COMMAND_ALIAS_CONTRACTS as P,PM_CORE_COMMAND_NAMES as D,resolvePmCommandAlias as Y,resolvePmCommandOperation as v}from"../sdk/cli-contracts.js";import{hasCoreInheritedFlagSurface as K}from"../sdk/cli-contracts/flag-contracts.js";import{commandOptionFlagLabel as T,resolveCommandOptionPolicyState as C,resolveTypeDefinition as Q,EXIT_CODE as b,writeStderr as Z,writeStdout as ee}from"../sdk/runtime-primitives.js";import{buildCoreInheritedHelpOptionSummaries as te,buildDynamicExtensionHelpOptionSummaries as ne,buildExtensionInheritedHelpOptionSummaries as ie,isExtensionCreatedCommand as oe,mergeHelpOptionSummaries as se,findCommandByPath as $,findDirectChildCommand as re,commandAliases as ae}from"./extension-command-help.js";import{getPmCommandHelpVisibilityTier as S,isFullHelpDiscovery as E,normalizeHelpCommandPath as A,resolveHelpBundleForPath as le,resolveHelpDetailMode as ce,resolveHelpNarrative as ue,ROOT_HELP_BUNDLE as de}from"./help-content.js";import{getCommandPath as F}from"./registration-helpers.js";import{parseBootstrapGlobalOptions as pe,parseBootstrapHelpRequest as j,parseBootstrapCommandName as me,parseBootstrapTypeValue as fe}from"./bootstrap-args.js";import{extractProvidedOptionFlags as he,renderPmCommand as ge}from"./argv-utils.js";import{formatCommanderErrorForJson as ye}from"./error-guidance.js";import{BUILTIN_TYPE_HELP_VALUES as _e,buildUnknownCommandGuidanceFromRuntime as ve,isKnownHelpCommandPath as Ce}from"./commander-usage.js";import{attachOutputTokenAccounting as be}from"../sdk/output-token-accounting.js";import{resolveCreateExplicitEmptyFlag as Se}from"../sdk/agent/create-option-policy.js";import{formatPmPositionalActionFlagTip as Ae,PM_POSITIONAL_ACTION_CONTRACTS as Oe,resolvePmPositionalActionContract as M}from"../sdk/cli-contracts/grammar-contracts.js";import{resolvePmCommandCapabilityFamily as O,resolvePmCommandVisibilityTier as _}from"../sdk/agent-capability-contracts.js";import{redactRefusalArgv as R}from"./runtime/refusal-credential-redaction.js";const L={core:0,standard:1,full:2,internal:3};function w(t,e,i=!0){const n=e.get(v(t));if(n)return n;if(!i)return;const o=[...e.entries()].filter(([r])=>r.startsWith(`${t} `)).map(([,r])=>r);if(o.length===0)return;const s=o.reduce((r,l)=>L[l.tier]<L[r]?l.tier:r,"internal"),c=new Set(o.map(({family:r})=>r));return{tier:s,family:c.size===1?o[0].family:"extensions"}}function H(t,e){if(e.length===0)return t;const i=$(t,e);if(i)return i;const n=e.join(" ");if(v(n)!==n||!D.some(o=>o===n)&&!X(n)&&!M(n)&&!Ce(t,e))return null;for(let o=e.length-1;o>0;o-=1){const s=$(t,e.slice(0,o));if(s)return s}return e.length===1?t:null}function we(t){const e=t.match(/[<[]([^>\]]+)[>\]]/);if(!e)return null;const i=e[1]?.trim();return i&&i.length>0?i:null}function q(t){const e=t;if(typeof e.attributeName=="function"){const i=e.attributeName();return typeof i=="string"&&i.trim().length>0?i.trim():null}return typeof e.attributeName=="string"&&e.attributeName.trim().length>0?e.attributeName.trim():null}function N(t){const e=new Map;for(const i of t){const n=i,o=q(i);if(!o||typeof n.long!="string"||n.long.trim().length===0)continue;const s=e.get(o)??[];s.push(n.long.trim()),e.set(o,s)}for(const[i,n]of e.entries())e.set(i,[...new Set(n.map(o=>o.trim()).filter(o=>o.length>0))].sort((o,s)=>o.localeCompare(s)));return e}function He(t){return ge(t)}function I(t){const e=t.options??[],i=N(e);return e.map(n=>{const o=n,s=typeof o.flags=="string"?o.flags.trim():"",c=typeof o.description=="string"?o.description.trim():"",r=q(n),d=(r?i.get(r)??[]:[]).filter(f=>f!==o.long).map(f=>f.trim()).filter(f=>f.length>0),a=c.match(/^Alias for ([^ ]+)/i),u=a&&a[1]?a[1].trim():null,p=o.mandatory===!0||c.includes("[required]")||c.toLowerCase().includes("required;"),g=s.includes("<"),h=g||s.includes("["),m={flags:s,long:typeof o.long=="string"?o.long:null,short:typeof o.short=="string"?o.short:null,description:c,takes_value:h,value_required:g,value_name:we(s),variadic:o.variadic===!0,required:p,aliases:d,alias_for:u};return o.defaultValue!==void 0&&(m.default_value=o.defaultValue),m})}function B(t){const e=new Map,i=[];for(const n of t){if(n.alias_for&&n.long){i.push(n);continue}n.long&&e.set(n.long,n)}for(const n of i){const o=n.alias_for,s=e.get(o);if(!s)continue;const c=n.long,r=new Set([...s.aliases??[],c]);s.aliases=[...r].sort((l,d)=>l.localeCompare(d))}return t.filter(n=>!n.alias_for||!n.long?!0:!e.has(n.alias_for))}function J(t){const e=t;return(Array.isArray(e.registeredArguments)?e.registeredArguments:Array.isArray(e._args)?e._args:[]).map(n=>{const o=typeof n.name=="function"?n.name():typeof n.name=="string"?n.name:"argument",s=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():null;return{name:o.trim(),required:n.required===!0||s?.toLowerCase().startsWith("required;")===!0,variadic:n.variadic===!0,description:s}})}function U(t,e=new Map,i=!1){const n=t.createHelp().visibleCommands(t);return(i?[...new Set([...n,...t.commands])]:n).filter(s=>s.name()!=="help"||t.parent===null).filter(s=>!i||(S(s)??_(s.name()))!=="internal").map(s=>{const c=A(F(s)),r=c,l=S(s),d=w(c,e,l!==void 0),a=P.find(({alias:u})=>u===c);return{name:s.name().trim(),aliases:ae(s),description:s.description().trim(),tier:d?.tier??l??_(r),family:d?.family??O(r),...a?{alias_for:a.canonical,alias_lifecycle:a.lifecycle,...a.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((s,c)=>s.name.localeCompare(c.name))}function qe(t,e,i){if(!i)return e;const n=i.examples??[],o=i.failure_hints??[];return{intent:i.intent??i.description??e.intent,examples:t==="detailed"?n.length>0?[...n]:[...e.examples]:n.length>0?[n[0]]:[...e.examples],tips:t==="detailed"?o.length>0?[...o]:[...e.tips]:[],detail_mode:t}}function xe(t,e,i,n,o){const s=t!==void 0&&le(t)===de,c=s?{intent:e,examples:[`pm ${t} --help`],tips:[],detail_mode:i}:ue(t,i),r=o?"positional_action":n?.intent||n?.description?"extension":s?e?"command_description":"unavailable":t?"help_bundle":"root_help_bundle";return{narrative:qe(i,c,n),intentSource:r}}function Pe(t,e){return t===void 0?null:e?.tier??_(t)}function Te(t,e){return t===void 0?null:e?.family??O(t)}function $e(t,e,i){if(!(e!==t||!i))return P.map(n=>({alias:n.alias,canonical:n.canonical,canonical_argv:[...n.canonical_argv],available:H(t,n.canonical.split(" "))!==null,lifecycle:n.lifecycle,hidden:n.hidden,deprecated:n.lifecycle==="deprecated"}))}function V(t,e,i,n,o=new Map,s=!1){if(!t){const r=J(e),l=U(e,o,s),d=new Set(l.map(({name:a})=>a));return{arguments:r,options:n,subcommands:[...l,...Oe.filter(({parent:a,action:u})=>a===i&&!d.has(u)).map(({action:a,description:u})=>({name:a,aliases:[],description:u,tier:_(i.split(" ")[0]),family:O(i.split(" ")[0])}))].sort((a,u)=>a.name.localeCompare(u.name)),usage:[i,r.reduce((a,u)=>u.required?a.replace(`[${u.name}${u.variadic?"...":""}]`,`<${u.name}${u.variadic?"...":""}>`):a,e.usage())].filter(a=>a.length>0).join(" ")}}const c=new Set(t.accepted_flags);return{arguments:t.slots.map(({name:r,required:l,variadic:d,value_kind:a,polymorphic:u})=>({name:r,required:l,variadic:d,description:u?`Polymorphic ${a} value; inspect the action contract before mutation.`:`${a.replaceAll("_"," ")} value.`})),options:n.filter(({long:r,aliases:l})=>r!==null&&c.has(r)||l.some(d=>c.has(d))),subcommands:[],usage:[t.command,...t.slots.map(({name:r,required:l,variadic:d})=>{const a=d?`${r}...`:r;return l?`<${a}>`:`[${a}]`})].join(" ")}}function Ee(t,e,i,n){return oe(t)?e===void 0?{}:{inherited_options:ie(e)}:i!==void 0&&K(i)?{inherited_options:te(i,n)}:{}}function k(t,e,i,n,o){const s=ce(i),c=E(i),r=A(F(e)),l=A(n.join(" ")),d=l.length>r.length?l:r,a=M(d),u=a?.command??r,p=u.length>0?u:void 0,g=p,h=p?o.get(v(p)):void 0,m=p?w(p,o,S(e)!==void 0):void 0,{narrative:f,intentSource:W}=xe(p,e.description().trim(),s,h,a!==void 0),z=B(se(I(e),ne(h))),y=V(a,e,u,z,o,c),x=$e(t,e,c);return{format:"pm_help_v1",detail_mode:s,root_command:t.name(),requested_path:n,resolved_path:u.length>0?u:t.name(),visibility_tier:Pe(g,m),capability_family:Te(g,m),description:a?.description??e.description(),usage:y.usage,intent:a?.description??f.intent,intent_source:W,examples:a?[a.example]:f.examples,tips:a?[Ae(a.accepted_flags)]:f.tips,arguments:y.arguments,options:y.options,...Ee(e,h,p,y.options),subcommands:y.subcommands,has_subcommands:y.subcommands.length>0,...x===void 0?{}:{command_aliases:x}}}async function Ze(t,e,i,n=e){const o=pe(e);if(!o.json)return!1;const s=j(e);if(!s.requested)return!1;const c=H(t,s.commandPathTokens);if(!c){if(!o.quiet){const r=R(e),l=`unknown command '${R(s.commandPathTokens).join(" ")}'`,d=ve(l,t,i,r),a=ye(l,"help",_e,b.USAGE,{...d,attemptedCommand:He(r),normalizedInvocationArgs:[...r],providedOptionFlags:he(r)}),u=o.tokenAccounting?be(a,p=>`${JSON.stringify(p,null,2)}
2
+ `):a;Z(`${JSON.stringify(u,null,2)}
3
+ `)}return process.exitCode=b.USAGE,!0}if(!o.quiet){const r=k(t,c,e,s.commandPathTokens,i),l=j(n).commandPathTokens;r.requested_path=l;const d=Y(l.join(" "));d&&(r.resolved_path=d.canonical),c===t&&!E(e)&&(r.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),ee(`${JSON.stringify(r,null,2)}
4
+ `)}return process.exitCode=b.SUCCESS,!0}function Fe(t,e){const i=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${e.types.join("|")}`];return t==="create"&&i.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),i.join(`
5
+ `)}function je(t,e){if(e.options.length===0){t.push(" type options: none");return}t.push(" type options:");for(const i of e.options){const n=i.required?" (required)":"",o=i.aliases??[];t.push(` - ${i.key}${n}`),t.push(` values: ${i.values.length>0?i.values.join("|"):"any non-empty string"}`),t.push(` aliases: ${o.length>0?o.join("|"):"none"}`),i.description&&i.description.trim().length>0&&t.push(` description: ${i.description.trim()}`)}}function Me(t,e){const i=t==="create"?new Set(["title","type"]):new Set,n=new Set(i);if(t==="create")for(const o of[...e.required_create_fields,...e.required_create_repeatables])n.add(o);return{progressive:i,strict:n}}function Re(t,e,i,n){const o=new Set(i),s=n.filter(l=>!o.has(l)),c=l=>l.length>0?l.map(d=>T("create",d)).join(", "):"none";t.push(` required in strict mode: ${c(s)}`);const r=s.map(Se).filter(l=>l!==void 0);t.push(` explicit empty assertion: ${r.length>0?r.join(", "):"none"}`),["Reminder","Meeting","Event"].includes(e.name)&&(t.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),t.push(" strict parity remains available via --create-mode strict."))}function G(t,e,i){const n=fe(i);if(!n)return Fe(t,e);const o=Q(n,e);if(!o){const m=e.types.join("|");return["",`Type-aware option policies: type "${n}" is not in the active registry.`,` active type values: ${m}`].join(`
6
+ `)}const s=i.indexOf("--"),c=s<0?i:i.slice(0,s),r=c.findIndex(m=>m==="--create-mode"||m.startsWith("--create-mode=")),l=r<0?void 0:c[r]?.startsWith("--create-mode=")?c[r]?.slice(14):c[r+1],d=t==="create"&&l?.toLowerCase()==="strict",a=Me(t,o),u=C(o,t,a.progressive),p=C(o,t,d?a.strict:a.progressive),g=m=>m.length>0?m.map(f=>T(t,f)).join(", "):"none",h=["",`Type-aware option policies for ${o.name}:`,` required: ${g(p.required)}`,` disabled: ${g(p.disabled)}`,` hidden: ${g(p.hidden)}`];if(t==="create"){const m=C(o,t,a.strict);Re(h,o,u.required,m.required)}return je(h,o),p.errors.length>0&&h.push(` config errors: ${p.errors.join("; ")}`),h.join(`
7
+ `)}function Le(t,e,i){const n=me(i);if(n!=="create"&&n!=="update")return;const o=re(t,n);o&&o.addHelpText("after",G(n,e,i))}const et={attachCreateUpdatePolicyHelpText:Le,buildCreateUpdatePolicyHelpText:G,buildJsonHelpPayload:k,buildPositionalActionHelpProjection:V,buildHelpArgumentSummaries:J,buildHelpOptionSummaries:I,buildHelpSubcommandSummaries:U,buildOptionAliasMap:N,compactHelpOptionAliases:B,readOptionAttributeName:q,resolveCommandFromPathTokens:H,resolveExtensionCommandSurface:w};export{et as _testOnly,Le as attachCreateUpdatePolicyHelpText,Ze as maybeRenderBootstrapJsonHelp};
8
8
  //# sourceMappingURL=help-json-payload.js.map
package/dist/cli/main.js CHANGED
@@ -1,6 +1,6 @@
1
- import{attachPreflightWarnings as Le,attachSerializedPreflightWarnings as We,emitPreflightWarning as kt,runWithPreflightWarnings as Pt}from"./preflight-warnings.js";import{assertGuardedDispatchUnchanged as je,bindInvocationExpectedRevisions as Be,invocationRewritten as Ot,parseWithInvocationRevisionScope as Ft,refuseInventoryExpectHash as Tt}from"./expected-revisions.js";import{Command as ae,CommanderError as ze}from"commander";import{PM_COMMAND_ALIAS_CONTRACTS as Dt,findPmNamespacedCommand as It,resolvePmCommandOperation as ce}from"../sdk/cli-contracts/command-aliases.js";import{createPmCliProgram as qe}from"../sdk/cli-program.js";import{runWithDiscoveredContextIntentContracts as Ht}from"../sdk/context-intent-runtime.js";import{createExtensionCommandError as Mt,describeUnknownError as D,isCommanderError as Ve,normalizeThrownExitCode as Ke,readThrownExitCode as Je,wrapThrownErrorForSentry as Ye}from"../sdk/error-runtime.js";import{createExtensionCommandSdk as Nt}from"../sdk/extension-command-context.js";import{isPmCliExpectedError as $t,snapshotPmCliErrorContext as Gt}from"../sdk/errors.js";import{runExtensionMigrations as Ut}from"../sdk/extension/migrations.js";import{repairProjectionRecovery as Lt}from"./runtime/projection-retry.js";import{repairReadOutputMutationRecovery as Wt}from"./runtime/read-output-mutation-retry.js";import{redactRefusalArgv as jt}from"./runtime/refusal-credential-redaction.js";import{redactUrlCredentialsInText as Qe,runWithUrlCredentialInvocation as Bt}from"../sdk/command-line.js";import{isTrackerRevisionGuarded as zt}from"../sdk/lifecycle/item-revision.js";import{repairSchemaFieldRecovery as qt}from"./runtime/field-route-retry.js";import{isRegistrableFieldFlagSpelling as Vt}from"../sdk/schema/field-flag-spelling.js";import{ANNOTATION_OPTION_REFUSAL_CODE as Kt,repairAnnotationOptionRecovery as Jt}from"./runtime/annotation-option-retry.js";import{CLOSE_FIELDS_REFUSAL_CODE as Yt,repairCloseFieldsRecovery as Qt}from"./runtime/close-fields-retry.js";import{resolvePmCommandScopeArgs as Xt}from"../sdk/command-line.js";import{applyInvocationAuthorOverride as Zt}from"../sdk/invocation-author.js";import{attachOutputTokenAccounting as en}from"../sdk/output-token-accounting.js";import{annotationPositionalMutationOptions as on,validateReadOutputOptions as tn}from"../sdk/read-output-contracts.js";import{runWithReproducibleProcessEnvironment as nn}from"../sdk/reproducibility/process.js";import{resolveTelemetrySourceAttribution as Xe,EXIT_CODE as h,PmCliError as G,activateExtensions as rn,clearActiveExtensionHooks as le,consumeAfterCommandAffectedItems as sn,createCoreCommandHookContext as an,createEmptyExtensionRegistrationRegistry as cn,createLazyModule as K,deriveTelemetryCommandResolution as ln,discoverExtensions as dn,emitTelemetryErrorEvent as mn,ensureSentryInit as un,ensureSentryCommandTracing as Ze,getActiveCommandResult as pn,getActiveExtensionRegistrations as gn,getSettingsPath as de,loadExtensions as fn,maybeRunFirstUseTelemetryPrompt as hn,pathExists as me,printError as y,printResult as eo,readSettings as I,readSettingsWithMetadata as oo,resetActiveExtensionRuntimeState as yn,resolveGlobalPmRoot as Cn,resolveItemTypeRegistry as _n,resolvePmCliVersion as vn,resolvePmPackageRootFromModule as wn,resolvePmRoot as R,resolveRuntimeFieldRegistry as to,resolveTelemetryErrorCategory as En,runActiveCommandHandler as no,runActiveParserOverride as ue,runActivePreflightOverride as Rn,runAfterCommandHooks as xn,runBeforeCommandHooks as bn,runWithConfigurationOnlySettings as pe,runWithHarnessDetectionSignals as Sn,runWithWorkspaceHarnessSignalDescriptors as An,sentryCaptureCliError as ro,sentryDiscardCommandSpan as kn,sentryFinishCommandSpan as Pn,sentryFlush as U,sentryLogCliUsageError as On,sentrySetCommandContext as io,sentryStartCommandSpan as Fn,setActiveCommandContext as ge,setActiveCommandResult as L,setActiveExtensionCommands as Tn,setActiveExtensionHooks as Dn,setActiveExtensionParsers as In,setActiveExtensionPreflight as Hn,setActiveExtensionRegistrations as so,setActiveExtensionRenderers as Mn,setActiveExtensionServices as O,startTelemetryCommand as ao,writeStderr as fe}from"../sdk/runtime-primitives.js";import{PmClient as Nn}from"../sdk/runtime.js";import{recordDeprecatedAliasUsage as $n}from"../sdk/telemetry.js";import{finishActiveTelemetryCommand as Gn,recordAfterCommandContextUsage as Un}from"./after-command-context-usage.js";import{extractProvidedOptionFlags as co,normalizeLongOptionFlag as W,redactSensitiveCommandArgs as Ln,renderPmCommand as Wn}from"./argv-utils.js";import{applyBootstrapPagerPolicy as jn,findBootstrapCommandTokenIndex as he,normalizeBootstrapInvocation as lo,parseBootstrapCommandName as ye,parseBootstrapGlobalOptions as k,parseBootstrapHelpRequest as Ce,stripGlobalBootstrapTokens as mo}from"./bootstrap-args.js";import{installCommandNamespaces as uo}from"./command-namespaces.js";import{appendCommanderExtensionFailures as po,formatCommanderUsageJson as go,formatCommanderUsageMessage as fo,isKnownHelpCommandPath as _e,resolveCommanderUsageContext as ho,resolveUnknownCommanderToken as yo}from"./commander-usage.js";import{loadContextIntentSnapshotForInvocation as Bn}from"./context-intent-invocation.js";import{classifyCommanderError as Co,classifyPmCliError as zn,classifyUnknownError as qn,formatPmCliErrorForDisplay as Vn,formatPmCliErrorForJson as _o,formatUnknownErrorForJson as Kn,projectLeanErrorEnvelope as Jn}from"./error-guidance.js";import{applyDynamicExtensionArguments as Yn,applyDynamicExtensionFlagOptions as vo,buildCanonicalExtensionAliases as Qn,buildDynamicExtensionCommandMetadataHelp as Xn,buildExtensionInheritedFlagHelp as wo,isExtensionCreatedCommand as Eo,buildResidualDynamicExtensionFlagHelp as Ro,collectDynamicExtensionFlagHelpByCommand as Zn,collectExtensionCommandHelpDescriptors as er,collectSafeExtensionCommandPaths as or,ensureCommandPath as tr,extensionFlagTakesValueForInvocation as xo,findCommandByPath as ve,normalizeExtensionCommandPath as P,reportExtensionCommandCollision as nr}from"./extension-command-help.js";import{collectLoosePositionalArgs as rr,stripLooseCommandOptionTokens as bo}from"../sdk/extension/command-options.js";import{loadExtensionRecoveryFailures as ir,loadUnknownCommandRecoveryFailures as sr}from"./extension-recovery.js";import{attachRichHelpText as ar,isFullHelpDiscovery as cr,setPmCommandHelpVisibilityTier as lr}from"./help-content.js";import{attachCreateUpdatePolicyHelpText as dr,maybeRenderBootstrapJsonHelp as mr}from"./help-json-payload.js";import{collectMandatoryMigrationBlockers as ur,enforceItemFormatWriteGateAndPreflightMigration as So,enforceMandatoryMigrationWriteGate as pr,enforceMutationGuardPreflight as Ao}from"./migration-gates.js";import{applyDefaultOutputFormat as gr,clearResolvedGlobalOptions as ko,collect as Po,formatHookWarnings as S,getCommandPath as H,getGlobalOptions as J,invalidateSearchCachesForMutation as fr,setResolvedGlobalOptions as hr,syncCommanderActionOptions as we}from"./registration-helpers.js";import{activationCommandMatchesProbe as yr,buildBootstrapActivationProbe as j,buildRuntimeExtensionActivationScope as Oo,buildRuntimeExtensionFilterForProbe as Fo,collectActivationCommandCandidates as Ee,collectLeadingCommandArgs as Cr,collectParsedActivationCommandArgs as To,commandPathNeedsSearchExtensions as _r,commandPathNeedsTemplateExtensions as vr,discoveryNeedsActivationForProbe as Y,extensionActivationCommands as wr,extensionCapabilities as Er,extensionNeedsActivationForProbe as Rr,extensionProvidesTemplatesRuntime as xr,hasAnyCapability as br,hasGlobalExtensionContributions as Sr,matchesStaticExtensionCommand as Ar,probeUsesAnyFlag as kr,resolveStaticExtensionActivationDecision as Pr}from"./runtime/activation.js";import{captureCommandOptionTokens as Or,refuseConflictingCommandOptionSpellings as Fr,resolveExtensionCommandRefusalListing as Tr,collectExtensionFlagDefinitionsForCommand as Dr,collectExtensionFlagDefinitionsForInvocation as Q,copyReadOutputInvocationProvenance as Re,dynamicCommandArguments as Ir,extractCommandScopedOptions as B,forwardReadOutputIncludeModes as Do,isImporterOrExporterCommandPath as Io,recordCliReadOutputInvocationProvenance as Hr,refuseUndeclaredRootOnlyOptions as Mr,validateDynamicExtensionCommandArgs as Nr,validateDynamicExtensionCommandInvocation as Ho}from"./runtime/invocation-options.js";import{LIST_QUERY_COMMAND_NAMES as $r,enforceExplicitRetryForFlagTypos as Mo,invocationRequestsVersion as Gr,isStaticExtensionInventoryInvocation as xe,resolveStructuredMutationPreviewInvocation as Ur,resolveCoreCommandRegistrationSelection as No,shouldAttachRichHelpTextForInvocation as $o,shouldRegisterDynamicExtensionPaths as Go,shouldRegisterRuntimeSchemaFlags as Uo}from"./runtime/selection.js";import{recordInvocationPromotions as Lr}from"./runtime/invocation-rewrites.js";import{buildPostActionTelemetryOutcome as Lo,inferPostActionErrorCode as Wr,inferPostActionFailureMessage as jr,normalizeTelemetryCommandResolution as Br,normalizeTelemetryErrorCategory as zr,normalizeTelemetryResolutionStage as qr,readRecordBoolean as Vr,readRecordNumber as Kr,readRecordString as Jr}from"./runtime/telemetry-outcome.js";const be="PM_CLI_PACKAGE_ROOT",Wo=Symbol("pm.deprecatedAliasInvocation"),X=new Map;for(const e of Dt){const o=e.alias.split(" ")[0],t=X.get(o)??[];t.push(e),X.set(o,t)}for(const e of X.values())e.sort((o,t)=>t.alias.split(" ").length-o.alias.split(" ").length);function Yr(){return wn(import.meta.url,["../.."])}(typeof process.env[be]!="string"||process.env[be]?.trim().length===0)&&(process.env[be]=Yr());let F=null,x=null,Z=null;function Qr(e){F=e}function Xr(e){v=e}let z=null,T=null,v=new Map;const Se=250,Zr=new Set([h.USAGE,h.NOT_FOUND,h.CONFLICT]),ei=new Set(["1","true","yes","on"]),oi=K(()=>import("./register-setup.js")),ti=K(()=>import("./register-list-query.js")),ni=K(()=>import("./register-mutation.js")),ri=K(()=>import("./register-operations.js"));function ee(e){return Wn(e)}function jo(e){const o=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!o||o.length===0)return;const t=[...new Set(o.map(n=>W(n)??n))];return t.length>0?t:void 0}function ii(e,o,t,n){if(t?.suggested_retry||n===Yt||n===Kt||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;const r=co(o),s=new Set(r.map(m=>W(m)??m)),i=jo(e),c=o.find(m=>p.commands.some(d=>d.name()===m)),u=c?p.commands.find(m=>m.name()===c):void 0,l=new Set([...p.options,...u?.options??[]].flatMap(m=>m.flags.split(/[ ,|]+/).map(d=>W(d)).filter(d=>d!==void 0))),a=i?.filter(m=>{const d=W(m)??m;return s.has(d)?!1:l.has(d)||xo(o,c,d,v)!==void 0});return a&&a.length>0?a:void 0}function si(e,o,t,n){if(n?.suggested_retry)return n.suggested_retry;const r=t?.[0],s=r?W(r):void 0,i=e.find(d=>p.commands.some(g=>g.name()===d)),c=i?p.commands.find(d=>d.name()===i):void 0,u=s?c?.options.find(d=>d.flags.split(/[ ,|]+/).includes(s)):void 0,l=xo(e,i,s,v),a=s?u?.isBoolean()===!0||l===!1?[s]:[s,"<value>"]:[],m=s?ee([...e,...a]):o;return m===o?void 0:m}function ai(e){if(!e)return{};const o=["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"],t={};for(const n of o){const r=e[n];r!==void 0&&(n==="allowed_values"||r!==null)&&(t[n]=r)}return t}function ci(e){const o=e.existingRecovery;return{attempted_command:o?.attempted_command??e.attemptedCommand,normalized_args:o?.normalized_args??[...e.invocationArgv],provided_fields:o?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:o?.missing??e.inferredMissing,...ai(o),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Bo(e,o){return{...e,recovery:o}}function li(e,o){if(o===void 0)return;const t=qt(e,o.code,o.field,Lt(e,o.code,o.recovery)),n=di(e),r=Jt(e,o.code,o.field,t,n),s=Wt(e,o.code,r,n,()=>zt(R(process.cwd(),k(e).path)));return Qt(e,o.code,s,n)}const zo=" ";function di(e){const o=e.map(r=>r===""?zo:/^--(?:pm-)?path=$/u.test(r)?`${r}${zo}`:r),t=k(o).path;if(t!==void 0&&t.trim()!=="")return[];const n=Xt({});return t!==void 0&&n.length>0?null:n}function qo(e,o,t){const n=Ln(o),r=mo(n),s=he(r),[i,c]=s===void 0?[]:r.slice(s,s+2),u=n.includes("--explain");e=e===void 0?void 0:Gt(e);const l=li(n,e),a=l&&(i==="history-redact"||i==="history"&&c==="redact")?{...l,...l.attempted_command?{attempted_command:ee(n)}:{},...l.normalized_args?{normalized_args:[...n]}:{},...l.suggested_retry?{suggested_retry:ee(n)}:{},...l.suggested_retry_args?{suggested_retry_args:[...n]}:{}}:l;if(a?.recovery_mode==="compact"&&!u)return Bo(e,a);const m=ee(n),d=co(n),g=ii(t,n,a,e?.code),f=si(n,m,g,a),E=ci({invocationArgv:n,attemptedCommand:m,providedFields:d,inferredMissing:g,suggestedRetry:f,existingRecovery:a});return Bo(e,E)}async function q(e){const o=x;x=null,await Gn(o,e);const t=F;if(F=null,!t){le();return}let n=[];const r=sn();try{await Un({pmRoot:t.pmRoot,author:t.globalOptions.author,itemIds:e.ok?r?.map(s=>s.id)??[]:[],intent:t.commandName})}catch{n.push("context_usage_feedback_write_failed")}try{n.push(...await xn(t.hooks,{command:t.commandName,args:t.commandArgs,options:{...t.commandOptions},global:{...t.globalOptions},pm_root:t.pmRoot,ok:e.ok,error:e.error,result:pn(),affected:r}))}catch(s){n=[`afterCommand hooks failed: ${s instanceof Error?s.message:String(s)}`]}finally{le()}!t.globalOptions.json&&n.length>0&&y(`[pm] warning: afterCommand hook_warnings=${S(n)}`),t.profileEnabled&&n.length>0&&y(`profile:extensions hook_warnings=${S(n)}`)}async function Vo(e,o){await un();const t=x,n=F,r=t?.command??n?.commandName??e,s=t??Xe(n?.globalOptions??o),i=v.get(P(r))?.source;io(r,n?.commandArgs??[],{...n?.commandOptions,...n?.globalOptions},{source_context:s.source_context,source_context_source:s.source_context_source,pm_version:t?.pm_version??N,extension:i})}function Ko(e){return ei.has((process.env[e]??"").trim().toLowerCase())}function Jo(e){return Ko("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Zr.has(Math.trunc(e))}async function oe(e,o){return Jo(e.exit_code)?(await Vo(e.command,o),On({...e,source_context:e.source_context??Xe(o).source_context}),!0):!1}async function Yo(e){const o=Qe(D(e.error)),t=qn(o);e.bootstrapGlobal.json?y(JSON.stringify(Le(Kn(o,h.GENERIC_FAILURE)),null,2)):y(o),process.exitCode=h.GENERIC_FAILURE;let n="runtime",r="runtime_failed";try{await Vo(e.attemptedCommand,e.bootstrapGlobal),ro(e.error);const s=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:t.code,errorMessage:t.detail,exitCode:h.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});n=s.errorCategory,r=s.commandResolution,await ie(!1,o,{error_code:t.code,error_category:n,exit_code:h.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(s){e.bootstrapGlobal.json||y(`Failed to report error: ${D(s)}`)}try{await q({ok:!1,error:o,exit_code:h.GENERIC_FAILURE,error_code:t.code,error_category:n,command_resolution:r,resolution_stage:"execute"})}catch(s){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${D(s)}`)}try{await U()}catch(s){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${D(s)}`)}}const mi={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"},Ae=new Map;function ke(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Qo(e,o){return e.options.some(t=>t.long===o)}function Xo(e,o){return e.options.some(t=>t.short===o)}function Pe(e,o,t,n){const r=o.trim();if(!r||!Vt(r))return;const s=t.length>0?t:`Runtime schema field (${o})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Xo(e,r))return;if(n){e.option(`${r} <value>`,`${s} (repeatable)`,Po);return}e.option(`${r} <value>`,s);return}const i=r.startsWith("--")?r:`--${r}`;if(!Qo(e,i)){if(n){e.option(`${i} <value>`,`${s} (repeatable)`,Po);return}e.option(`${i} <value>`,s)}}async function Zo(e,o){const t=mi[e];if(!t)return[];const n=`${o}:${t}`,r=Ae.get(n);if(r)return r;if(!await me(de(o)))return Ae.set(n,[]),[];const s=await I(o),c=(to(s.schema).command_to_fields.get(t)??[]).flatMap(u=>[u.cli_flag,...u.cli_aliases].map(a=>({long:`--${a}`,type:ke(u.type),value_type:ke(u.type)})));return Ae.set(n,c),c}async function et(e,o){const t=k(o),n=R(process.cwd(),t.path);if(!await me(de(n)))return;const r=T?.key===De(n)?T.snapshot:null,s=r===null?await I(n):r.settings,i=to(s.schema),c=[{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(const u of c){const l=ve(e,u.path.split(" "));if(l)for(const a of i.command_to_fields.get(u.command)??[]){const m=a.description??"";Pe(l,a.cli_flag,m,a.repeatable);for(const d of a.cli_aliases)Pe(l,d,`Alias for --${a.cli_flag}`,a.repeatable)}}}async function Oe(e,o,t,n,r){const s=ye(t);if(!(s!=="create"&&s!=="update"))try{const i=r??await I(o),c=_n(i,n);dr(e,c,t)}catch{}}function Fe(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function ot(e,o="all"){return o==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${o}`}function Te(e){return e.some(o=>o==="--profile")}function De(e){return`pm-root:${e}`}function Ie(e){for(const o of e)o.startsWith("settings_read_")&&kt(o,`[pm] warning: ${o} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function tt(e,o){e.profile&&(y(`profile:extensions loaded=${o.loadedCount} failed=${o.loadFailedCount} warnings=${o.loadWarnings.length} activation_failed=${o.activationFailedCount} hook_counts=before:${o.hooks.beforeCommand.length}|after:${o.hooks.afterCommand.length}|write:${o.hooks.onWrite.length}|read:${o.hooks.onRead.length}|index:${o.hooks.onIndex.length} command_overrides=${o.commands.overrides.length} command_handlers=${o.commands.handlers.length} parser_overrides=${o.parsers.overrides.length} preflight_overrides=${o.preflight.overrides.length} service_overrides=${o.services.overrides.length} renderer_overrides=${o.renderers.overrides.length}`),o.activationWarnings.length>0&&y(`profile:extensions activation_warnings=${S(o.activationWarnings)}`))}function te(e,o,t){if(!e)return;const n=P(t.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${n} effective=${o.discovery.effective.length} warnings=${o.discovery.warnings.length} discovery_ms=${o.discoveryMs}`)}async function ne(e,o=oo){const t=De(e);if(T?.key===t)return T.snapshot;try{const n=Date.now(),{settings:r,warnings:s}=await o(e),i=await dn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),c={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-n,settingsReadWarnings:[...s]};return T={key:t,snapshot:c},c}catch{return T={key:t,snapshot:null},null}}async function M(e,o,t=I){const n=o?Oo(o):"all",r=ot(e,n);if(z?.key===r)return z.snapshot;try{const s=await t(e),i=await fn({pmRoot:e,settings:s,cwd:process.cwd(),noExtensions:!1,extensionFilter:o?Fo(o):void 0}),c=await rn({...i,loaded:i.loaded}),u=[...new Set(c.commands.handlers.map(g=>P(g.command)))].filter(g=>g.length>0).sort((g,f)=>g.localeCompare(f)),l=Zn(c.registrations.flags),a=Qn(c.commands.handlers,c.registrations.commands),m=er(u,c.registrations.commands,c.registrations.flags,a),d={hooks:c.hooks,commands:c.commands,parsers:c.parsers,preflight:c.preflight,services:c.services,renderers:c.renderers,registrations:c.registrations,pmRoot:e,settings:s,commandHandlers:u,commandFlagHelp:l,commandDescriptors:m,commandAliases:a,loadWarnings:[...i.warnings],activationWarnings:[...c.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:c.failed.length,contextIntentPackages:i.loaded.map(({name:g,module:f})=>({name:g,module:f}))};return z={key:r,snapshot:d},d}catch{return z={key:r,snapshot:null},null}}async function nt(e){const o=J(e);if(o.noExtensions){const i=R(process.cwd(),o.path);return await me(de(i))&&Ie((await oo(i)).warnings),null}const t=R(process.cwd(),o.path),n=await ne(t);if(!n)return null;Ie(n.settingsReadWarnings);const r={commandPath:H(e),commandArgs:To(e)};if(!Y(n.discovery,r))return te(o.profile,n,r),null;const s=await M(t,r);return s?(tt(o,s),{hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:t}):null}async function He(e){const o=await M(e);return o?new Map(o.commandDescriptors):v}async function ui(e,o){return!e.requested||o.noExtensions||_e(p,e.commandPathTokens)?v:He(R(process.cwd(),o.path))}async function rt(e,o){return(await Ut({pmRoot:o,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function it(e,o,t){const n=o.author;return Nt(e,Nn.forActiveExtensionHost({pmRoot:e,author:n}),n,P(t))}async function st(e,o,t,n=[]){const r=H(e);let s=bo(e.args.map(String),n),i={...o};delete i.author;let c={...t};const u=R(process.cwd(),t.path),l={args:[...s],path:t.path},a=await ue({command:r,args:s,options:i,global:c,pm_root:u});t.profile&&a.warnings.length>0&&y(`profile:extensions parser_warnings=${S(a.warnings)}`),s=a.context.args,i=a.context.options,c=a.context.global,je(l,{args:s,path:c.path},i),Ho(v.get(P(r)),s,i,n),L(void 0),ge({command:r,args:s,options:{...i},global:{...c},pm_root:u});const m=await no({command:r,args:s,options:i,global:c,pm_root:u,sdk:it(u,c,r)});if(c.profile&&m.warnings.length>0&&y(`profile:extensions command_handler_warnings=${S(m.warnings)}`),!m.handled)throw m.warnings.length>0?Mt(r,m):new G(`Command "${r}" is provided by extensions and is not currently available.`,h.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),L(m.result),m.result}const at=Symbol("pm.wrappedActionHandler");function pi(e,o){const t=e[e.length-1];return t instanceof ae?t:o}function ct(e,o,t){e&&t.length>0&&y(`profile:extensions ${o}=${S(t)}`)}function gi(e){const o=v.get(P(e.commandPath));if(!o||!Io(e.activeRegistrations,e.commandPath))return;const t=Ir(o).length===0?rr(e.commandArgs):bo(e.commandArgs,e.extensionFlagDefinitions);Nr(o,t)}function fi(e,o,t){e.args=[...t],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),o.length>0&&Array.isArray(o[0])&&(o[0]=[...e.processedArgs])}function Me(e,o,t){if(!Eo(e))return;const n=v.get(P(o))?.read_output_declared===!0;return Tr(t,n)}function lt(e){const o=t=>{const n=t;if(Or(t),typeof n._actionHandler=="function"&&n[at]!==!0){const r=n._actionHandler;n._actionHandler=async function(...i){const c=pi(i,t),u=Date.now();ko(c);let l=J(c);const a=ce(H(c));if(["package inventory","packages inventory","extension inventory"].includes(a))return Tt(a,l.expectHash),await r.apply(this,i);const m=R(process.cwd(),l.path);let d=c.args.map(String);const g=gn(),f=g?Q(g,a,d):[],E=await Zo(a,m),C=Me(c,a,f);let _=B(c,d,[...f,...E],C);Fr(c,f,a),v.has(P(a))&&delete _.author,C!==void 0&&Mr(_,f,a);const A={args:[...d],path:l.path},b=await ue({command:a,args:d,options:_,global:l,pm_root:m});ct(l.profile,"parser_warnings",b.warnings),d=b.context.args,_=b.context.options,Re(c,_),l=b.context.global,je(A,{args:d,path:l.path},_),gi({activeRegistrations:g,commandPath:a,commandArgs:d,extensionFlagDefinitions:f}),l=await gr(l),hr(c,l),fi(c,i,d),we(c,_),L(void 0),ge({command:a,args:d,options:{..._},global:{...l},pm_root:m});const w=await no({command:a,args:d,options:_,global:l,pm_root:m,sdk:it(m,l,a)});if(ct(l.profile,"command_handler_warnings",w.warnings),w.handled){L(w.result),eo(w.result,{...l,command:a,commandArgs:d,commandOptions:_,pmRoot:m}),l.profile&&y(`profile:command=${a} took_ms=${Date.now()-u}`);return}return await r.apply(this,i)},n[at]=!0}for(const r of t.commands)o(r)};o(e)}async function re(e){v=new Map,O({overrides:[]}),e&&await Oe(e.rootProgram,e.pmRoot,e.invocationArgv,cn(),e.settings)}function hi(e,o,t,n){if(o?.flags&&o.flags.length>0){vo(e,o.flags);const r=Ro(e,o.flags);r&&e.addHelpText("after",r)}else t&&e.addHelpText("after",t);o&&Eo(e)&&e.addHelpText("after",wo(o)),n&&e.addHelpText("after",n)}function yi(e,o,t,n){o&&e.addHelpText("after",o),t&&e.addHelpText("after",wo(t)),n&&e.addHelpText("after",n)}function dt(e,o,t){const n={core:0,standard:1,full:2,internal:3},r=(s,i)=>{const c=i.join(" "),u=[...t.entries()].filter(([a])=>a===c||a.startsWith(`${c} `)).map(([,a])=>a),l=u.length===0?"standard":u.reduce((a,m)=>n[m.tier]<n[a]?m.tier:a,"internal");lr(s,l);for(const a of s.commands)r(a,[...i,a.name()])};for(const s of e.commands)o.has(s.name())||r(s,[s.name()])}async function mt(e,o){const t=k(o),n=R(process.cwd(),t.path);if(t.noExtensions){await re({rootProgram:e,pmRoot:n,invocationArgv:o});return}const r=await ne(n),s=j(o);if(!r){await re();return}if(!Y(r.discovery,s)){await re({rootProgram:e,pmRoot:n,invocationArgv:o,settings:r.settings}),te(Te(o),r,s);return}const i=await M(n,s);if(!i){await re({rootProgram:e,pmRoot:n,invocationArgv:o,settings:r.settings});return}O(i.services),v=new Map(i.commandDescriptors),await Oe(e,n,o,i.registrations,i.settings);const c=or(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,a=>nr(i.activationWarnings,y,a)),u=new Set(e.commands.map(a=>a.name())),l=a=>{const m=a.split(" ").filter(A=>A.length>0),d=i.commandDescriptors.get(a),g=ve(e,m),f=i.commandFlagHelp.get(a),E=d?Xn(d):null;if(g){hi(g,d,f,E);return}const C=tr(e,m);d?.description&&C.description(d.description);let _=f;d&&(Yn(C,d),d.flags.length>0&&(vo(C,d.flags),_=Ro(C,d.flags)??void 0)),yi(C,_,d,E),C.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...A)=>{const b=A[A.length-1],w=b instanceof ae?b:C,V=J(w),At=Date.now(),se=Q(i.registrations,a,w.args.map(String)),Ge=B(w,w.args.map(String),se,Me(w,a,se)),Ue=await st(w,Ge,V,se);await fr(V,Ue),eo(Ue,{...V,command:a,commandArgs:w.args.map(String),commandOptions:Ge,pmRoot:n}),V.profile&&y(`profile:command=${a} took_ms=${Date.now()-At}`)})};for(const a of c)l(a);dt(e,u,i.commandDescriptors)}const N=vn(import.meta.url,["../.."])??"0.0.0";let p=qe(N);async function ut(e){if(!x)return;const o=Reflect.get(e,Wo);typeof o=="string"&&await $n(o)}async function pt(e,o,t){const n=H(e);return["item mutate","item complete"].includes(n)&&e.optsWithGlobals().dryRun===!0?o:t()}async function gt(e,o,t){!x||!await Ze(!0)||(io(e,o,t,{source_context:x.source_context,source_context_source:x.source_context_source}),Fn(e),Z=x)}async function ie(e,o,t){const n=Z;if(!n)return;Z=null;let r=!1;try{const s=await I(n.global_pm_root);r=s.telemetry.enabled&&s.telemetry.installation_id===n.installation_id}catch{}await Ze(r)?Pn(e,o,t):kn()}async function Ci(e){const o=await nt(e);return so(o?.registrations??null),o}function ft(e,o){o&&xe(o)||(e.hook("preAction",async(t,n)=>{F=null,x=null,Z=null,le(),ko(n);const r=n.optsWithGlobals(),s=J(n),i=ce(H(n));let c=n.args.map(String);const u={args:[...c],path:s.path};let l=B(n,c),a={...s};const m=R(process.cwd(),s.path),d=await Ci(n);if(tn(i,{...l,...on(i,n.processedArgs),outputInclude:r.outputInclude,outputLimit:r.outputLimit,outputBudget:r.outputBudget,outputFormat:r.outputFormat,outputSession:r.outputSession,outputCursor:r.outputCursor}),Do(n,i,a,l),await pt(n,void 0,()=>hn(i,a)),!d){F=an({commandName:i,commandArgs:c,commandOptions:l,globalOptions:a,pmRoot:m}),x=await ao({command:i,pm_version:N,args:c,options:l,global:a,pm_root:m}),await ut(e),await gt(i,c,l),await So(i,l,m,Fe()),await Ao(i,c,l,a,m),await Be({command:n,commandPath:i,commandArgs:c,commandOptions:l,expectHash:s.expectHash,pmRoot:m,globalOptions:a});return}Dn(d.hooks),Tn(d.commands),In(d.parsers),Hn(d.preflight),O(d.services),Mn(d.renderers),so(d.registrations);const g=Q(d.registrations,i,c);l=B(n,c,g,Me(n,i,g)),Do(n,i,a,l);const f=await ue({command:i,args:c,options:l,global:a,pm_root:d.pmRoot});a.profile&&f.warnings.length>0&&y(`profile:extensions parser_warnings=${S(f.warnings)}`),c=f.context.args,l=f.context.options,Re(n,l),a=f.context.global;const E={args:[...c],path:a.path};we(n,l);const C=await Rn({command:i,args:c,options:l,global:a,pm_root:d.pmRoot,decision:Fe()});a.profile&&C.warnings.length>0&&y(`profile:extensions preflight_warnings=${S(C.warnings)}`),c=C.context.args,l=C.context.options,Re(n,l),a=C.context.global,we(n,l);const _=C.decision;await So(i,l,d.pmRoot,_),await Ao(i,c,l,a,d.pmRoot),await Be({command:n,commandPath:i,commandArgs:u.args,commandOptions:l,expectHash:s.expectHash,pmRoot:d.pmRoot,rewritten:Ot(u,[E,{args:c,path:a.path}]),globalOptions:{...a,path:s.path,noExtensions:s.noExtensions}});const A=_.run_extension_migrations?await pt(n,[],()=>rt(d.registrations.migrations,d.pmRoot)):[];a.profile&&A.length>0&&y(`profile:extensions migration_warnings=${S(A)}`);const b=ur(d.registrations.migrations);F={hooks:d.hooks,commandName:i,commandArgs:c,commandOptions:{...l},globalOptions:{...a},pmRoot:d.pmRoot,profileEnabled:!!a.profile,migrationBlockers:b},L(void 0),ge({command:i,args:c,options:{...l},global:{...a},pm_root:d.pmRoot}),x=await ao({command:i,pm_version:N,args:c,options:l,global:a,pm_root:d.pmRoot}),await ut(e),await gt(i,c,l);const w=await bn(d.hooks,{command:i,args:c,options:{...l},global:{...a},pm_root:d.pmRoot});a.profile&&w.length>0&&y(`profile:extensions hook_warnings=${S(w)}`),_.enforce_mandatory_migration_gate&&pr(i,l,b)}),e.hook("postAction",async()=>{const t=Lo();await ie(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await q(t),await U()}))}ft(p);const ht=Symbol("pmCliIdempotentTopLevelRegistration");function yt(e){const o=e;if(o[ht])return;o[ht]=!0;const t=e.command.bind(e);e.command=((n,...r)=>{const s=n.split(/\s+/u)[0];return e.commands.some(i=>i.name()===s||i.aliases().includes(s))?new ae(s):t(n,...r)})}async function _i(e,o){if(yt(e),o.setup){const{registerSetupCommands:t}=await oi();t(e)}if(o.listQuery){const{registerListQueryCommands:t}=await ti(),n=typeof o.targetCommandName=="string"&&$r.has(o.targetCommandName)?new Set([o.targetCommandName]):void 0;t(e,n?{commandFilter:n}:void 0)}if(o.mutation){const{registerMutationCommands:t}=await ni();t(e,{targetCommandName:o.targetCommandName})}if(o.operation){const{registerOperationCommands:t}=await ri();t(e)}}function $(e){return e.rawInvocationArgv??e.invocationArgv}function vi(e){return async o=>{const t=En(o.errorCode),n=ln({ok:!1,errorCode:o.errorCode,errorCategory:t});return await mn({command:o.command,args:e.invocationArgv,options:o.options,global:e.bootstrapGlobal,pm_version:N,pm_root:e.bootstrapPmRoot,error_code:o.errorCode,error_message:o.errorMessage,exit_code:o.exitCode,error_category:t,command_resolution:n,resolution_stage:o.resolutionStage}),{errorCategory:t,commandResolution:n}}}async function Ct(e){if(e.bootstrapGlobal.noExtensions||xe(e.invocationArgv))return;const o=j(e.invocationArgv),t=await ne(e.bootstrapPmRoot);if(t&&Y(t.discovery,o)){const n=await M(e.bootstrapPmRoot,o);_t(n);return}t&&te(Te(e.invocationArgv),t,o),O({overrides:[]})}function _t(e){if(!e){O({overrides:[]});return}O(e.services)}async function Ne(e){await ie(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await q({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 vt(){await ie(!0,void 0,{exit_code:h.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await q({ok:!0,exit_code:h.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=h.SUCCESS}async function wt(e,o){const t=typeof o=="number"&&Number.isFinite(o);if(!(e.error instanceof G)&&(Ve(e.error)||!t))return!1;const n=Qe(D(e.error)),r=e.error instanceof G?e.error.exitCode:Ke(o),s=e.error instanceof G||$t(e.error)?e.error.context:void 0,i=qo(s,e.invocationArgv,n),c=zn(n,i),u=Le(e.bootstrapGlobal.lean?Jn(_o(n,r,i)):_o(n,r,i)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?en(u,g=>`${JSON.stringify(g,null,2)}
2
- `):u,null,2):Vn(n,i,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?fe(`${l}
3
- `):y(l);const{errorCategory:a,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:c.code,errorMessage:c.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),d=await oe({command:e.attemptedCommand,error_code:c.code,error_category:a,exit_code:r,error_message:c.detail,command_resolution:m,resolution_stage:"execute",source_context:x?.source_context},e.bootstrapGlobal);return await Ne({errorMessage:n,exitCode:r,classificationCode:c.code,errorCategory:a,commandResolution:m,resolutionStage:"execute"}),d&&(ro(Ye(e.error,n)),await U(Se)),process.exitCode=r,!0}async function Et(e,o){const t=Ce(e.invocationArgv).commandPathTokens.join(" ")||yo(e.invocationArgv),n=ce(t),r=`unknown command '${t}'`,s=R(process.cwd(),e.bootstrapGlobal.path),i=e.bootstrapGlobal.noExtensions?v:await He(s),c=j(e.invocationArgv),u=e.bootstrapGlobal.noExtensions?[]:await ir(s,{},Ee(c)),l=await ho({message:r},p,i,{failedExtensions:u},$(e)),a=Co(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:u}),{errorCategory:m,commandResolution:d}=await e.emitTelemetryCommandError({command:n,errorCode:a.code,errorMessage:a.detail,exitCode:h.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:o??"commander.helpDisplayed"},resolutionStage:"parse"}),g=await oe({command:n,error_code:a.code,error_category:m,exit_code:h.USAGE,error_message:a.detail,command_resolution:d,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await go({message:r},p,i,e.bootstrapGlobal.lean===!0,{failedExtensions:u},$(e)):await fo({message:r},p,i,{failedExtensions:u},$(e)),E=po(f,e.jsonErrors,u);await Ne({errorMessage:r,exitCode:h.USAGE,classificationCode:a.code,errorCategory:m,commandResolution:d,resolutionStage:"parse"}),e.jsonErrors?fe(`${We(E)}
4
- `):y(E),g&&await U(Se),process.exitCode=h.USAGE}async function Rt(e,o,t){if(!(o==="commander.helpDisplayed"||o==="commander.help"||o==="commander.helpCommand")&&!t.includes("(outputHelp)"))return!1;const r=Ce(e.invocationArgv);return r.requested&&!_e(p,r.commandPathTokens)?(await Et(e,o),!0):(await vt(),!0)}async function xt(e,o){const t=await ho(e.error,p,v,{},$(e)),n=Co(t.message,t.commandName,t.allowedTypes,{unknownCommandExamples:t.unknownCommandExamples,unknownCommandNextSteps:t.unknownCommandNextSteps,attemptedCommand:t.attemptedCommand,normalizedInvocationArgs:t.normalizedInvocationArgs,providedOptionFlags:t.providedOptionFlags,unknownOptionSuggestions:t.unknownOptionSuggestions,suggestedRetryCommand:t.suggestedRetryCommand}),{errorCategory:r,commandResolution:s}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:h.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:o},resolutionStage:"parse"}),i=await oe({command:e.attemptedCommand,error_code:n.code,error_category:r,exit_code:h.USAGE,error_message:n.detail,command_resolution:s,resolution_stage:"parse",source_context:x?.source_context},e.bootstrapGlobal),c=e.jsonErrors?await go(e.error,p,v,e.bootstrapGlobal.lean===!0,{},$(e)):await fo(e.error,p,v,{},$(e)),u=await sr(n.code,e.bootstrapPmRoot,{},Ee(j(e.invocationArgv))),l=po(c,e.jsonErrors,u);await Ne({errorMessage:t.message,exitCode:h.USAGE,classificationCode:n.code,errorCategory:r,commandResolution:s,resolutionStage:"parse"}),e.jsonErrors?fe(`${We(l)}
5
- `):y(l),i&&await U(Se),process.exitCode=h.USAGE}function bt(e){if(typeof e!="object"||e===null||!("code"in e))return!1;const o=e.code;return typeof o=="string"&&(o==="commander.version"||o.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function St(e){const o=e.error.code,t=String(e.error.message??"");if(!await Rt(e,o,t)){if(o==="commander.version"){await vt();return}await xt(e,o)}}async function $e(e){const o=k(e.invocationArgv),t=R(process.cwd(),o.path),n=jt(e.invocationArgv),r={error:e.error,invocationArgv:n,rawInvocationArgv:e.invocationArgv,bootstrapGlobal:o,jsonErrors:o.json,bootstrapPmRoot:t,attemptedCommand:ye(n)??"<unknown>",emitTelemetryCommandError:vi({invocationArgv:n,bootstrapGlobal:o,bootstrapPmRoot:t})};if(await Ct({invocationArgv:e.invocationArgv,bootstrapGlobal:o,bootstrapPmRoot:t}),!await wt(r,Je(e.error))){if(bt(e.error)){await St(r);return}await Yo({error:e.error,attemptedCommand:r.attemptedCommand,bootstrapGlobal:o,emitTelemetryCommandError:r.emitTelemetryCommandError})}}function wi(e,o,t){const n=t.requested?t.commandPathTokens:mo(o),r=It(n);if(r&&!ve(e,[...r.canonical_argv]))throw new ze(h.USAGE,"commander.unknownCommand",`unknown command '${r.alias}'`)}function Ei(e,o){let t=he(o);if(t===void 0)return;if(["pm","pm-cli"].includes(o[t]?.trim().toLowerCase())){const i=he(o.slice(t+1));if(i===void 0)return;t+=i+1}const n=X.get(o[t]),r=o.slice(t).filter(i=>!["--global","--project","--local"].includes(i)),s=n?.find(i=>i.alias.split(" ").every((c,u)=>r[u]===c));s?.lifecycle==="deprecated"&&Reflect.set(e,Wo,s.alias)}function Ri(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function xi(e,o){p=qe(N),p.hook("preAction",(s,i)=>{o.configurationOnly=["item mutate","item complete"].includes(H(i))&&i.optsWithGlobals().dryRun===!0}),ft(p,e),z=null,T=null,v=new Map,yn();let t=[...e],n,r;try{const s=lo(e);t=s.argv,Lr(s.trace),Ei(p,e);const i=Ri(t),c=t.length===0,u=k(t);if(u.authorMissingValue)throw new G("--author requires a non-empty value.",h.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});n=Zt(u.author),Mo(s),r=jn(t);const l=No(t);await _i(p,l),uo(p,!0),Go(p,t)?await mt(p,t):(v=new Map,O({overrides:[]})),Uo(t)&&await et(p,t),uo(p);const m=Ce(t);wi(p,t,m),$o(t)&&ar(p,t),lt(p);const d=await ui(m,u);if(await mr(p,t,d,e))return;if(m.requested&&!_e(p,m.commandPathTokens))throw new ze(h.USAGE,"commander.helpDisplayed","(outputHelp)");if(c||cr(t)&&ye(t)===void 0){p.outputHelp();return}if(xe(t)){await p.parseAsync(i);return}const f=R(process.cwd(),u.path),E=await I(f),C=await Bn(t,f,u.noExtensions,M);await Ft(_=>Ht({pmRoot:f,packages:C?.contextIntentPackages},()=>Sn({env:{...process.env,PM_PATH:f},argv:i,cwd:process.cwd()},()=>An(E.agent_identity.harness_signals,()=>_(()=>p.parseAsync(i)),{probesEnabled:E.agent_identity?.probes_enabled}))))}catch(s){await $e({error:s,invocationArgv:t})}finally{r?.(),n?.()}}async function Cs(e=process.argv.slice(2)){let o=e;try{o=lo(e).argv}catch{}await Bt([...e,...o],()=>bi(e,o))}async function bi(e,o){const t=Ur(o),n={configurationOnly:t!==void 0},r=()=>n.configurationOnly,s=()=>Pt(k(o).json,async()=>{try{await nn(process.env,()=>xi(e,n))}catch(i){await $e({error:i,invocationArgv:[...e]})}});if(t!==void 0){const i=R(process.cwd(),k(o).path),c=R(process.cwd(),t.path),u=Cn(process.cwd());await pe(i,()=>pe(c,()=>pe(u,s,r),r),r)}else await s()}const _s={activationCommandMatchesProbe:yr,applyDynamicExtensionRootHelpVisibility:dt,bootstrapProfileEnabled:Te,buildBootstrapActivationProbe:j,buildPostActionTelemetryOutcome:Lo,buildPmCliRecoveryContext:qo,buildRuntimeExtensionDiscoverySnapshotCacheKey:De,buildRuntimeExtensionActivationScope:Oo,buildRuntimeExtensionSnapshotCacheKey:ot,buildRuntimeExtensionFilterForProbe:Fo,addRuntimeFieldOption:Pe,collectActivationCommandCandidates:Ee,collectExtensionFlagDefinitionsForCommand:Dr,collectExtensionFlagDefinitionsForInvocation:Q,collectLeadingCommandArgs:Cr,collectParsedActivationCommandArgs:To,collectRuntimeFieldLooseFlagDefinitionsForCommand:Zo,commandHasLongOption:Qo,commandHasShortOption:Xo,commandPathNeedsSearchExtensions:_r,commandPathNeedsTemplateExtensions:vr,describeUnknownError:D,defaultPreflightDecision:Fe,discoveryNeedsActivationForProbe:Y,emitExtensionProfile:tt,emitExtensionSkippedProfile:te,emitSettingsReadWarnings:Ie,ensureIdempotentTopLevelCommandRegistration:yt,enforceExplicitRetryForFlagTypos:Mo,envFlagEnabled:Ko,executeRegisteredRuntimeMigrations:rt,extractCommandScopedOptions:B,extensionActivationCommands:wr,extensionCapabilities:Er,extensionNeedsActivationForProbe:Rr,extensionProvidesTemplatesRuntime:xr,hasAnyCapability:br,hasGlobalExtensionContributions:Sr,handleGenericRunPmCliError:Yo,handleRunPmCliCommanderError:St,handleRunPmCliError:$e,handleRunPmCliHelpDisplayError:Rt,handleRunPmCliKnownError:wt,handleRunPmCliCommanderUsageError:xt,handleUnknownHelpCommandError:Et,inferMissingFieldsFromErrorMessage:jo,inferPostActionErrorCode:Wr,inferPostActionFailureMessage:jr,invocationRequestsVersion:Gr,isCommanderError:Ve,loadRuntimeExtensionCommandDescriptorsForRecovery:He,loadRuntimeExtensionDiscoverySnapshot:ne,loadRuntimeExtensionSnapshot:M,maybeLoadRuntimeExtensions:nt,maybeAttachCreateUpdatePolicyHelpText:Oe,maybeLogHandledCliErrorToSentry:oe,matchesStaticExtensionCommand:Ar,normalizeTelemetryCommandResolution:Br,normalizeTelemetryErrorCategory:zr,normalizeTelemetryResolutionStage:qr,normalizeThrownExitCode:Ke,probeUsesAnyFlag:kr,prepareExtensionServicesForRunPmCliError:Ct,readRecordBoolean:Vr,readRecordNumber:Kr,readRecordString:Jr,recordCliReadOutputInvocationProvenance:Hr,registerDynamicExtensionCommandPaths:mt,registerRuntimeSchemaFieldFlags:et,resolveCoreCommandRegistrationSelection:No,resolveStaticExtensionActivationDecision:Pr,resolveUnknownHelpToken:yo,readThrownExitCode:Je,runAndClearAfterCommandHooks:q,runRequiredExtensionCommand:st,shouldAttachRichHelpTextForInvocation:$o,shouldLogHandledErrorToSentry:Jo,shouldRegisterDynamicExtensionPaths:Go,shouldRegisterRuntimeSchemaFlags:Uo,shouldHandleRunPmCliCommanderError:bt,setActiveExtensionHookContextForTest:Qr,setActiveRuntimeExtensionCommandDescriptorsForTest:Xr,setRecoveredExtensionServices:_t,toLooseFieldDefinitionType:ke,isImporterOrExporterCommandPath:Io,validateDynamicExtensionCommandInvocation:Ho,wrapProgramActionsForExtensionHandlers:lt,wrapThrownErrorForSentry:Ye};export{_s as _testOnly,Cs as runPmCli};
1
+ import{attachPreflightWarnings as Le,attachSerializedPreflightWarnings as We,emitPreflightWarning as Pt,runWithPreflightWarnings as kt}from"./preflight-warnings.js";import{assertGuardedDispatchUnchanged as je,bindInvocationExpectedRevisions as Be,invocationRewritten as Ot,parseWithInvocationRevisionScope as Tt,refuseInventoryExpectHash as Ft}from"./expected-revisions.js";import{Command as ae,CommanderError as ze}from"commander";import{PM_COMMAND_ALIAS_CONTRACTS as Dt,findPmNamespacedCommand as It,resolvePmCommandOperation as ce}from"../sdk/cli-contracts/command-aliases.js";import{STATIC_INVENTORY_COMMAND_PATHS as Mt}from"../sdk/cli-contracts/flag-contracts.js";import{createPmCliProgram as Ve}from"../sdk/cli-program.js";import{runWithDiscoveredContextIntentContracts as Ht}from"../sdk/context-intent-runtime.js";import{createExtensionCommandError as Nt,describeUnknownError as D,isCommanderError as qe,normalizeThrownExitCode as Ke,readThrownExitCode as Je,wrapThrownErrorForSentry as Ye}from"../sdk/error-runtime.js";import{createExtensionCommandSdk as $t}from"../sdk/extension-command-context.js";import{isPmCliExpectedError as Gt,snapshotPmCliErrorContext as Ut}from"../sdk/errors.js";import{runExtensionMigrations as Lt}from"../sdk/extension/migrations.js";import{repairProjectionRecovery as Wt}from"./runtime/projection-retry.js";import{repairReadOutputMutationRecovery as jt}from"./runtime/read-output-mutation-retry.js";import{redactRefusalArgv as Bt}from"./runtime/refusal-credential-redaction.js";import{redactUrlCredentialsInText as Qe,runWithUrlCredentialInvocation as zt}from"../sdk/command-line.js";import{isTrackerRevisionGuarded as Vt}from"../sdk/lifecycle/item-revision.js";import{repairSchemaFieldRecovery as qt}from"./runtime/field-route-retry.js";import{isRegistrableFieldFlagSpelling as Kt}from"../sdk/schema/field-flag-spelling.js";import{ANNOTATION_OPTION_REFUSAL_CODE as Jt,repairAnnotationOptionRecovery as Yt}from"./runtime/annotation-option-retry.js";import{CLOSE_FIELDS_REFUSAL_CODE as Qt,repairCloseFieldsRecovery as Xt}from"./runtime/close-fields-retry.js";import{resolvePmCommandScopeArgs as Zt}from"../sdk/command-line.js";import{applyInvocationAuthorOverride as en}from"../sdk/invocation-author.js";import{attachOutputTokenAccounting as on}from"../sdk/output-token-accounting.js";import{annotationPositionalMutationOptions as tn,validateReadOutputOptions as nn}from"../sdk/read-output-contracts.js";import{runWithReproducibleProcessEnvironment as rn}from"../sdk/reproducibility/process.js";import{resolveTelemetrySourceAttribution as Xe,EXIT_CODE as h,PmCliError as G,activateExtensions as sn,clearActiveExtensionHooks as le,consumeAfterCommandAffectedItems as an,createCoreCommandHookContext as cn,createEmptyExtensionRegistrationRegistry as ln,createLazyModule as K,deriveTelemetryCommandResolution as mn,discoverExtensions as dn,emitTelemetryErrorEvent as un,ensureSentryInit as pn,ensureSentryCommandTracing as Ze,getActiveCommandResult as gn,getActiveExtensionRegistrations as fn,getSettingsPath as me,loadExtensions as hn,maybeRunFirstUseTelemetryPrompt as yn,pathExists as de,printError as y,printResult as eo,readSettings as I,readSettingsWithMetadata as oo,resetActiveExtensionRuntimeState as Cn,resolveGlobalPmRoot as _n,resolveItemTypeRegistry as vn,resolvePmCliVersion as wn,resolvePmPackageRootFromModule as En,resolvePmRoot as R,resolveRuntimeFieldRegistry as to,resolveTelemetryErrorCategory as Rn,runActiveCommandHandler as no,runActiveParserOverride as ue,runActivePreflightOverride as xn,runAfterCommandHooks as bn,runBeforeCommandHooks as Sn,runWithConfigurationOnlySettings as pe,runWithHarnessDetectionSignals as An,runWithWorkspaceHarnessSignalDescriptors as Pn,sentryCaptureCliError as ro,sentryDiscardCommandSpan as kn,sentryFinishCommandSpan as On,sentryFlush as U,sentryLogCliUsageError as Tn,sentrySetCommandContext as io,sentryStartCommandSpan as Fn,setActiveCommandContext as ge,setActiveCommandResult as L,setActiveExtensionCommands as Dn,setActiveExtensionHooks as In,setActiveExtensionParsers as Mn,setActiveExtensionPreflight as Hn,setActiveExtensionRegistrations as so,setActiveExtensionRenderers as Nn,setActiveExtensionServices as O,startTelemetryCommand as ao,writeStderr as fe}from"../sdk/runtime-primitives.js";import{PmClient as $n}from"../sdk/runtime.js";import{recordDeprecatedAliasUsage as Gn}from"../sdk/telemetry.js";import{finishActiveTelemetryCommand as Un,recordAfterCommandContextUsage as Ln}from"./after-command-context-usage.js";import{extractProvidedOptionFlags as co,normalizeLongOptionFlag as W,redactSensitiveCommandArgs as Wn,renderPmCommand as jn}from"./argv-utils.js";import{applyBootstrapPagerPolicy as Bn,findBootstrapCommandTokenIndex as he,normalizeBootstrapInvocation as lo,parseBootstrapCommandName as ye,parseBootstrapGlobalOptions as P,parseBootstrapHelpRequest as Ce,stripGlobalBootstrapTokens as mo}from"./bootstrap-args.js";import{installCommandNamespaces as uo}from"./command-namespaces.js";import{appendCommanderExtensionFailures as po,formatCommanderUsageJson as go,formatCommanderUsageMessage as fo,isKnownHelpCommandPath as _e,resolveCommanderUsageContext as ho,resolveUnknownCommanderToken as yo}from"./commander-usage.js";import{loadContextIntentSnapshotForInvocation as zn}from"./context-intent-invocation.js";import{classifyCommanderError as Co,classifyPmCliError as Vn,classifyUnknownError as qn,formatPmCliErrorForDisplay as Kn,formatPmCliErrorForJson as _o,formatUnknownErrorForJson as Jn,projectLeanErrorEnvelope as Yn}from"./error-guidance.js";import{applyDynamicExtensionArguments as Qn,applyDynamicExtensionFlagOptions as vo,buildCanonicalExtensionAliases as Xn,buildDynamicExtensionCommandMetadataHelp as Zn,buildExtensionInheritedFlagHelp as wo,isExtensionCreatedCommand as Eo,buildResidualDynamicExtensionFlagHelp as Ro,collectDynamicExtensionFlagHelpByCommand as er,collectExtensionCommandHelpDescriptors as or,collectSafeExtensionCommandPaths as tr,ensureCommandPath as nr,extensionFlagTakesValueForInvocation as xo,findCommandByPath as ve,normalizeExtensionCommandPath as k,reportExtensionCommandCollision as rr}from"./extension-command-help.js";import{collectLoosePositionalArgs as ir,stripLooseCommandOptionTokens as bo}from"../sdk/extension/command-options.js";import{loadExtensionRecoveryFailures as sr,loadUnknownCommandRecoveryFailures as ar}from"./extension-recovery.js";import{attachRichHelpText as cr,isFullHelpDiscovery as lr,setPmCommandHelpVisibilityTier as mr}from"./help-content.js";import{attachCreateUpdatePolicyHelpText as dr,maybeRenderBootstrapJsonHelp as ur}from"./help-json-payload.js";import{collectMandatoryMigrationBlockers as pr,enforceItemFormatWriteGateAndPreflightMigration as So,enforceMandatoryMigrationWriteGate as gr,enforceMutationGuardPreflight as Ao}from"./migration-gates.js";import{applyDefaultOutputFormat as fr,clearResolvedGlobalOptions as Po,collect as ko,formatHookWarnings as S,getCommandPath as M,getGlobalOptions as J,invalidateSearchCachesForMutation as hr,setResolvedGlobalOptions as yr,syncCommanderActionOptions as we}from"./registration-helpers.js";import{activationCommandMatchesProbe as Cr,buildBootstrapActivationProbe as j,buildRuntimeExtensionActivationScope as Oo,buildRuntimeExtensionFilterForProbe as To,collectActivationCommandCandidates as Ee,collectLeadingCommandArgs as _r,collectParsedActivationCommandArgs as Fo,commandPathNeedsSearchExtensions as vr,commandPathNeedsTemplateExtensions as wr,discoveryNeedsActivationForProbe as Y,extensionActivationCommands as Er,extensionCapabilities as Rr,extensionNeedsActivationForProbe as xr,extensionProvidesTemplatesRuntime as br,hasAnyCapability as Sr,hasGlobalExtensionContributions as Ar,matchesStaticExtensionCommand as Pr,probeUsesAnyFlag as kr,resolveStaticExtensionActivationDecision as Or}from"./runtime/activation.js";import{captureCommandOptionTokens as Tr,refuseConflictingCommandOptionSpellings as Fr,resolveExtensionCommandRefusalListing as Dr,collectExtensionFlagDefinitionsForCommand as Ir,collectExtensionFlagDefinitionsForInvocation as Q,copyReadOutputInvocationProvenance as Re,dynamicCommandArguments as Mr,extractCommandScopedOptions as B,forwardReadOutputIncludeModes as Do,isImporterOrExporterCommandPath as Io,recordCliReadOutputInvocationProvenance as Hr,refuseUndeclaredRootOnlyOptions as Nr,validateDynamicExtensionCommandArgs as $r,validateDynamicExtensionCommandInvocation as Mo}from"./runtime/invocation-options.js";import{LIST_QUERY_COMMAND_NAMES as Gr,enforceExplicitRetryForFlagTypos as Ho,invocationRequestsVersion as Ur,isStaticExtensionInventoryInvocation as xe,resolveStructuredMutationPreviewInvocation as Lr,resolveCoreCommandRegistrationSelection as No,shouldAttachRichHelpTextForInvocation as $o,shouldRegisterDynamicExtensionPaths as Go,shouldRegisterRuntimeSchemaFlags as Uo}from"./runtime/selection.js";import{recordInvocationPromotions as Wr}from"./runtime/invocation-rewrites.js";import{buildPostActionTelemetryOutcome as Lo,inferPostActionErrorCode as jr,inferPostActionFailureMessage as Br,normalizeTelemetryCommandResolution as zr,normalizeTelemetryErrorCategory as Vr,normalizeTelemetryResolutionStage as qr,readRecordBoolean as Kr,readRecordNumber as Jr,readRecordString as Yr}from"./runtime/telemetry-outcome.js";const be="PM_CLI_PACKAGE_ROOT",Wo=Symbol("pm.deprecatedAliasInvocation"),X=new Map;for(const e of Dt){const o=e.alias.split(" ")[0],t=X.get(o)??[];t.push(e),X.set(o,t)}for(const e of X.values())e.sort((o,t)=>t.alias.split(" ").length-o.alias.split(" ").length);function Qr(){return En(import.meta.url,["../.."])}(typeof process.env[be]!="string"||process.env[be]?.trim().length===0)&&(process.env[be]=Qr());let T=null,x=null,Z=null;function Xr(e){T=e}function Zr(e){v=e}let z=null,F=null,v=new Map;const Se=250,ei=new Set([h.USAGE,h.NOT_FOUND,h.CONFLICT]),oi=new Set(["1","true","yes","on"]),ti=K(()=>import("./register-setup.js")),ni=K(()=>import("./register-list-query.js")),ri=K(()=>import("./register-mutation.js")),ii=K(()=>import("./register-operations.js"));function ee(e){return jn(e)}function jo(e){const o=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!o||o.length===0)return;const t=[...new Set(o.map(n=>W(n)??n))];return t.length>0?t:void 0}function si(e,o,t,n){if(t?.suggested_retry||n===Qt||n===Jt||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;const r=co(o),s=new Set(r.map(d=>W(d)??d)),i=jo(e),c=o.find(d=>p.commands.some(m=>m.name()===d)),u=c?p.commands.find(d=>d.name()===c):void 0,l=new Set([...p.options,...u?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>W(m)).filter(m=>m!==void 0))),a=i?.filter(d=>{const m=W(d)??d;return s.has(m)?!1:l.has(m)||xo(o,c,m,v)!==void 0});return a&&a.length>0?a:void 0}function ai(e,o,t,n){if(n?.suggested_retry)return n.suggested_retry;const r=t?.[0],s=r?W(r):void 0,i=e.find(m=>p.commands.some(g=>g.name()===m)),c=i?p.commands.find(m=>m.name()===i):void 0,u=s?c?.options.find(m=>m.flags.split(/[ ,|]+/).includes(s)):void 0,l=xo(e,i,s,v),a=s?u?.isBoolean()===!0||l===!1?[s]:[s,"<value>"]:[],d=s?ee([...e,...a]):o;return d===o?void 0:d}function ci(e){if(!e)return{};const o=["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"],t={};for(const n of o){const r=e[n];r!==void 0&&(n==="allowed_values"||r!==null)&&(t[n]=r)}return t}function li(e){const o=e.existingRecovery;return{attempted_command:o?.attempted_command??e.attemptedCommand,normalized_args:o?.normalized_args??[...e.invocationArgv],provided_fields:o?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:o?.missing??e.inferredMissing,...ci(o),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Bo(e,o){return{...e,recovery:o}}function mi(e,o){if(o===void 0)return;const t=qt(e,o.code,o.field,Wt(e,o.code,o.recovery)),n=di(e),r=Yt(e,o.code,o.field,t,n),s=jt(e,o.code,r,n,()=>Vt(R(process.cwd(),P(e).path)));return Xt(e,o.code,s,n)}const zo=" ";function di(e){const o=e.map(r=>r===""?zo:/^--(?:pm-)?path=$/u.test(r)?`${r}${zo}`:r),t=P(o).path;if(t!==void 0&&t.trim()!=="")return[];const n=Zt({});return t!==void 0&&n.length>0?null:n}function Vo(e,o,t){const n=Wn(o),r=mo(n),s=he(r),[i,c]=s===void 0?[]:r.slice(s,s+2),u=n.includes("--explain");e=e===void 0?void 0:Ut(e);const l=mi(n,e),a=l&&(i==="history-redact"||i==="history"&&c==="redact")?{...l,...l.attempted_command?{attempted_command:ee(n)}:{},...l.normalized_args?{normalized_args:[...n]}:{},...l.suggested_retry?{suggested_retry:ee(n)}:{},...l.suggested_retry_args?{suggested_retry_args:[...n]}:{}}:l;if(a?.recovery_mode==="compact"&&!u)return Bo(e,a);const d=ee(n),m=co(n),g=si(t,n,a,e?.code),f=ai(n,d,g,a),E=li({invocationArgv:n,attemptedCommand:d,providedFields:m,inferredMissing:g,suggestedRetry:f,existingRecovery:a});return Bo(e,E)}async function V(e){const o=x;x=null,await Un(o,e);const t=T;if(T=null,!t){le();return}let n=[];const r=an();try{await Ln({pmRoot:t.pmRoot,author:t.globalOptions.author,itemIds:e.ok?r?.map(s=>s.id)??[]:[],intent:t.commandName})}catch{n.push("context_usage_feedback_write_failed")}try{n.push(...await bn(t.hooks,{command:t.commandName,args:t.commandArgs,options:{...t.commandOptions},global:{...t.globalOptions},pm_root:t.pmRoot,ok:e.ok,error:e.error,result:gn(),affected:r}))}catch(s){n=[`afterCommand hooks failed: ${s instanceof Error?s.message:String(s)}`]}finally{le()}!t.globalOptions.json&&n.length>0&&y(`[pm] warning: afterCommand hook_warnings=${S(n)}`),t.profileEnabled&&n.length>0&&y(`profile:extensions hook_warnings=${S(n)}`)}async function qo(e,o){await pn();const t=x,n=T,r=t?.command??n?.commandName??e,s=t??Xe(n?.globalOptions??o),i=v.get(k(r))?.source;io(r,n?.commandArgs??[],{...n?.commandOptions,...n?.globalOptions},{source_context:s.source_context,source_context_source:s.source_context_source,pm_version:t?.pm_version??N,extension:i})}function Ko(e){return oi.has((process.env[e]??"").trim().toLowerCase())}function Jo(e){return Ko("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!ei.has(Math.trunc(e))}async function oe(e,o){return Jo(e.exit_code)?(await qo(e.command,o),Tn({...e,source_context:e.source_context??Xe(o).source_context}),!0):!1}async function Yo(e){const o=Qe(D(e.error)),t=qn(o);e.bootstrapGlobal.json?y(JSON.stringify(Le(Jn(o,h.GENERIC_FAILURE)),null,2)):y(o),process.exitCode=h.GENERIC_FAILURE;let n="runtime",r="runtime_failed";try{await qo(e.attemptedCommand,e.bootstrapGlobal),ro(e.error);const s=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:t.code,errorMessage:t.detail,exitCode:h.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});n=s.errorCategory,r=s.commandResolution,await ie(!1,o,{error_code:t.code,error_category:n,exit_code:h.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(s){e.bootstrapGlobal.json||y(`Failed to report error: ${D(s)}`)}try{await V({ok:!1,error:o,exit_code:h.GENERIC_FAILURE,error_code:t.code,error_category:n,command_resolution:r,resolution_stage:"execute"})}catch(s){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${D(s)}`)}try{await U()}catch(s){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${D(s)}`)}}const ui={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"},Ae=new Map;function Pe(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Qo(e,o){return e.options.some(t=>t.long===o)}function Xo(e,o){return e.options.some(t=>t.short===o)}function ke(e,o,t,n){const r=o.trim();if(!r||!Kt(r))return;const s=t.length>0?t:`Runtime schema field (${o})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Xo(e,r))return;if(n){e.option(`${r} <value>`,`${s} (repeatable)`,ko);return}e.option(`${r} <value>`,s);return}const i=r.startsWith("--")?r:`--${r}`;if(!Qo(e,i)){if(n){e.option(`${i} <value>`,`${s} (repeatable)`,ko);return}e.option(`${i} <value>`,s)}}async function Zo(e,o){const t=ui[e];if(!t)return[];const n=`${o}:${t}`,r=Ae.get(n);if(r)return r;if(!await de(me(o)))return Ae.set(n,[]),[];const s=await I(o),c=(to(s.schema).command_to_fields.get(t)??[]).flatMap(u=>[u.cli_flag,...u.cli_aliases].map(a=>({long:`--${a}`,type:Pe(u.type),value_type:Pe(u.type)})));return Ae.set(n,c),c}async function et(e,o){const t=P(o),n=R(process.cwd(),t.path);if(!await de(me(n)))return;const r=F?.key===De(n)?F.snapshot:null,s=r===null?await I(n):r.settings,i=to(s.schema),c=[{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(const u of c){const l=ve(e,u.path.split(" "));if(l)for(const a of i.command_to_fields.get(u.command)??[]){const d=a.description??"";ke(l,a.cli_flag,d,a.repeatable);for(const m of a.cli_aliases)ke(l,m,`Alias for --${a.cli_flag}`,a.repeatable)}}}async function Oe(e,o,t,n,r){const s=ye(t);if(!(s!=="create"&&s!=="update"))try{const i=r??await I(o),c=vn(i,n);dr(e,c,t)}catch{}}function Te(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function ot(e,o="all"){return o==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${o}`}function Fe(e){return e.some(o=>o==="--profile")}function De(e){return`pm-root:${e}`}function Ie(e){for(const o of e)o.startsWith("settings_read_")&&Pt(o,`[pm] warning: ${o} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function tt(e,o){e.profile&&(y(`profile:extensions loaded=${o.loadedCount} failed=${o.loadFailedCount} warnings=${o.loadWarnings.length} activation_failed=${o.activationFailedCount} hook_counts=before:${o.hooks.beforeCommand.length}|after:${o.hooks.afterCommand.length}|write:${o.hooks.onWrite.length}|read:${o.hooks.onRead.length}|index:${o.hooks.onIndex.length} command_overrides=${o.commands.overrides.length} command_handlers=${o.commands.handlers.length} parser_overrides=${o.parsers.overrides.length} preflight_overrides=${o.preflight.overrides.length} service_overrides=${o.services.overrides.length} renderer_overrides=${o.renderers.overrides.length}`),o.activationWarnings.length>0&&y(`profile:extensions activation_warnings=${S(o.activationWarnings)}`))}function te(e,o,t){if(!e)return;const n=k(t.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${n} effective=${o.discovery.effective.length} warnings=${o.discovery.warnings.length} discovery_ms=${o.discoveryMs}`)}async function ne(e,o=oo){const t=De(e);if(F?.key===t)return F.snapshot;try{const n=Date.now(),{settings:r,warnings:s}=await o(e),i=await dn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),c={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-n,settingsReadWarnings:[...s]};return F={key:t,snapshot:c},c}catch{return F={key:t,snapshot:null},null}}async function H(e,o,t=I){const n=o?Oo(o):"all",r=ot(e,n);if(z?.key===r)return z.snapshot;try{const s=await t(e),i=await hn({pmRoot:e,settings:s,cwd:process.cwd(),noExtensions:!1,extensionFilter:o?To(o):void 0}),c=await sn({...i,loaded:i.loaded}),u=[...new Set(c.commands.handlers.map(g=>k(g.command)))].filter(g=>g.length>0).sort((g,f)=>g.localeCompare(f)),l=er(c.registrations.flags),a=Xn(c.commands.handlers,c.registrations.commands),d=or(u,c.registrations.commands,c.registrations.flags,a),m={hooks:c.hooks,commands:c.commands,parsers:c.parsers,preflight:c.preflight,services:c.services,renderers:c.renderers,registrations:c.registrations,pmRoot:e,settings:s,commandHandlers:u,commandFlagHelp:l,commandDescriptors:d,commandAliases:a,loadWarnings:[...i.warnings],activationWarnings:[...c.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:c.failed.length,contextIntentPackages:i.loaded.map(({name:g,module:f})=>({name:g,module:f}))};return z={key:r,snapshot:m},m}catch{return z={key:r,snapshot:null},null}}async function nt(e){const o=J(e);if(o.noExtensions){const i=R(process.cwd(),o.path);return await de(me(i))&&Ie((await oo(i)).warnings),null}const t=R(process.cwd(),o.path),n=await ne(t);if(!n)return null;Ie(n.settingsReadWarnings);const r={commandPath:M(e),commandArgs:Fo(e)};if(!Y(n.discovery,r))return te(o.profile,n,r),null;const s=await H(t,r);return s?(tt(o,s),{hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:t}):null}async function Me(e){const o=await H(e);return o?new Map(o.commandDescriptors):v}async function pi(e,o){return!e.requested||o.noExtensions||_e(p,e.commandPathTokens)?v:Me(R(process.cwd(),o.path))}async function rt(e,o){return(await Lt({pmRoot:o,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function it(e,o,t){const n=o.author;return $t(e,$n.forActiveExtensionHost({pmRoot:e,author:n}),n,k(t))}async function st(e,o,t,n=[]){const r=M(e);let s=bo(e.args.map(String),n),i={...o};delete i.author;let c={...t};const u=R(process.cwd(),t.path),l={args:[...s],path:t.path},a=await ue({command:r,args:s,options:i,global:c,pm_root:u});t.profile&&a.warnings.length>0&&y(`profile:extensions parser_warnings=${S(a.warnings)}`),s=a.context.args,i=a.context.options,c=a.context.global,je(l,{args:s,path:c.path},i),Mo(v.get(k(r)),s,i,n),L(void 0),ge({command:r,args:s,options:{...i},global:{...c},pm_root:u});const d=await no({command:r,args:s,options:i,global:c,pm_root:u,sdk:it(u,c,r)});if(c.profile&&d.warnings.length>0&&y(`profile:extensions command_handler_warnings=${S(d.warnings)}`),!d.handled)throw d.warnings.length>0?Nt(r,d):new G(`Command "${r}" is provided by extensions and is not currently available.`,h.NOT_FOUND);return d.exitCode!==void 0&&(process.exitCode=d.exitCode),L(d.result),d.result}const at=Symbol("pm.wrappedActionHandler");function gi(e,o){const t=e[e.length-1];return t instanceof ae?t:o}function ct(e,o,t){e&&t.length>0&&y(`profile:extensions ${o}=${S(t)}`)}function fi(e){const o=v.get(k(e.commandPath));if(!o||!Io(e.activeRegistrations,e.commandPath))return;const t=Mr(o).length===0?ir(e.commandArgs):bo(e.commandArgs,e.extensionFlagDefinitions);$r(o,t)}function hi(e,o,t){e.args=[...t],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),o.length>0&&Array.isArray(o[0])&&(o[0]=[...e.processedArgs])}function He(e,o,t){if(!Eo(e))return;const n=v.get(k(o))?.read_output_declared===!0;return Dr(t,n)}function lt(e){const o=t=>{const n=t;if(Tr(t),typeof n._actionHandler=="function"&&n[at]!==!0){const r=n._actionHandler;n._actionHandler=async function(...i){const c=gi(i,t),u=Date.now();Po(c);let l=J(c);const a=ce(M(c));if(Mt.has(a))return Ft(a,l.expectHash),await r.apply(this,i);const d=R(process.cwd(),l.path);let m=c.args.map(String);const g=fn(),f=g?Q(g,a,m):[],E=await Zo(a,d),C=He(c,a,f);let _=B(c,m,[...f,...E],C);Fr(c,f,a),v.has(k(a))&&delete _.author,C!==void 0&&Nr(_,f,a);const A={args:[...m],path:l.path},b=await ue({command:a,args:m,options:_,global:l,pm_root:d});ct(l.profile,"parser_warnings",b.warnings),m=b.context.args,_=b.context.options,Re(c,_),l=b.context.global,je(A,{args:m,path:l.path},_),fi({activeRegistrations:g,commandPath:a,commandArgs:m,extensionFlagDefinitions:f}),l=await fr(l),yr(c,l),hi(c,i,m),we(c,_),L(void 0),ge({command:a,args:m,options:{..._},global:{...l},pm_root:d});const w=await no({command:a,args:m,options:_,global:l,pm_root:d,sdk:it(d,l,a)});if(ct(l.profile,"command_handler_warnings",w.warnings),w.handled){L(w.result),eo(w.result,{...l,command:a,commandArgs:m,commandOptions:_,pmRoot:d}),l.profile&&y(`profile:command=${a} took_ms=${Date.now()-u}`);return}return await r.apply(this,i)},n[at]=!0}for(const r of t.commands)o(r)};o(e)}async function re(e){v=new Map,O({overrides:[]}),e&&await Oe(e.rootProgram,e.pmRoot,e.invocationArgv,ln(),e.settings)}function yi(e,o,t,n){if(o?.flags&&o.flags.length>0){vo(e,o.flags);const r=Ro(e,o.flags);r&&e.addHelpText("after",r)}else t&&e.addHelpText("after",t);o&&Eo(e)&&e.addHelpText("after",wo(o)),n&&e.addHelpText("after",n)}function Ci(e,o,t,n){o&&e.addHelpText("after",o),t&&e.addHelpText("after",wo(t)),n&&e.addHelpText("after",n)}function mt(e,o,t){const n={core:0,standard:1,full:2,internal:3},r=(s,i)=>{const c=i.join(" "),u=[...t.entries()].filter(([a])=>a===c||a.startsWith(`${c} `)).map(([,a])=>a),l=u.length===0?"standard":u.reduce((a,d)=>n[d.tier]<n[a]?d.tier:a,"internal");mr(s,l);for(const a of s.commands)r(a,[...i,a.name()])};for(const s of e.commands)o.has(s.name())||r(s,[s.name()])}async function dt(e,o){const t=P(o),n=R(process.cwd(),t.path);if(t.noExtensions){await re({rootProgram:e,pmRoot:n,invocationArgv:o});return}const r=await ne(n),s=j(o);if(!r){await re();return}if(!Y(r.discovery,s)){await re({rootProgram:e,pmRoot:n,invocationArgv:o,settings:r.settings}),te(Fe(o),r,s);return}const i=await H(n,s);if(!i){await re({rootProgram:e,pmRoot:n,invocationArgv:o,settings:r.settings});return}O(i.services),v=new Map(i.commandDescriptors),await Oe(e,n,o,i.registrations,i.settings);const c=tr(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,a=>rr(i.activationWarnings,y,a)),u=new Set(e.commands.map(a=>a.name())),l=a=>{const d=a.split(" ").filter(A=>A.length>0),m=i.commandDescriptors.get(a),g=ve(e,d),f=i.commandFlagHelp.get(a),E=m?Zn(m):null;if(g){yi(g,m,f,E);return}const C=nr(e,d);m?.description&&C.description(m.description);let _=f;m&&(Qn(C,m),m.flags.length>0&&(vo(C,m.flags),_=Ro(C,m.flags)??void 0)),Ci(C,_,m,E),C.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...A)=>{const b=A[A.length-1],w=b instanceof ae?b:C,q=J(w),At=Date.now(),se=Q(i.registrations,a,w.args.map(String)),Ge=B(w,w.args.map(String),se,He(w,a,se)),Ue=await st(w,Ge,q,se);await hr(q,Ue),eo(Ue,{...q,command:a,commandArgs:w.args.map(String),commandOptions:Ge,pmRoot:n}),q.profile&&y(`profile:command=${a} took_ms=${Date.now()-At}`)})};for(const a of c)l(a);mt(e,u,i.commandDescriptors)}const N=wn(import.meta.url,["../.."])??"0.0.0";let p=Ve(N);async function ut(e){if(!x)return;const o=Reflect.get(e,Wo);typeof o=="string"&&await Gn(o)}async function pt(e,o,t){const n=M(e);return["item mutate","item complete"].includes(n)&&e.optsWithGlobals().dryRun===!0?o:t()}async function gt(e,o,t){!x||!await Ze(!0)||(io(e,o,t,{source_context:x.source_context,source_context_source:x.source_context_source}),Fn(e),Z=x)}async function ie(e,o,t){const n=Z;if(!n)return;Z=null;let r=!1;try{const s=await I(n.global_pm_root);r=s.telemetry.enabled&&s.telemetry.installation_id===n.installation_id}catch{}await Ze(r)?On(e,o,t):kn()}async function _i(e){const o=await nt(e);return so(o?.registrations??null),o}function ft(e,o){o&&xe(o)||(e.hook("preAction",async(t,n)=>{T=null,x=null,Z=null,le(),Po(n);const r=n.optsWithGlobals(),s=J(n),i=ce(M(n));let c=n.args.map(String);const u={args:[...c],path:s.path};let l=B(n,c),a={...s};const d=R(process.cwd(),s.path),m=await _i(n);if(nn(i,{...l,...tn(i,n.processedArgs),outputInclude:r.outputInclude,outputLimit:r.outputLimit,outputBudget:r.outputBudget,outputFormat:r.outputFormat,outputSession:r.outputSession,outputCursor:r.outputCursor}),Do(n,i,a,l),await pt(n,void 0,()=>yn(i,a)),!m){T=cn({commandName:i,commandArgs:c,commandOptions:l,globalOptions:a,pmRoot:d}),x=await ao({command:i,pm_version:N,args:c,options:l,global:a,pm_root:d}),await ut(e),await gt(i,c,l),await So(i,l,d,Te()),await Ao(i,c,l,a,d),await Be({command:n,commandPath:i,commandArgs:c,commandOptions:l,expectHash:s.expectHash,pmRoot:d,globalOptions:a});return}In(m.hooks),Dn(m.commands),Mn(m.parsers),Hn(m.preflight),O(m.services),Nn(m.renderers),so(m.registrations);const g=Q(m.registrations,i,c);l=B(n,c,g,He(n,i,g)),Do(n,i,a,l);const f=await ue({command:i,args:c,options:l,global:a,pm_root:m.pmRoot});a.profile&&f.warnings.length>0&&y(`profile:extensions parser_warnings=${S(f.warnings)}`),c=f.context.args,l=f.context.options,Re(n,l),a=f.context.global;const E={args:[...c],path:a.path};we(n,l);const C=await xn({command:i,args:c,options:l,global:a,pm_root:m.pmRoot,decision:Te()});a.profile&&C.warnings.length>0&&y(`profile:extensions preflight_warnings=${S(C.warnings)}`),c=C.context.args,l=C.context.options,Re(n,l),a=C.context.global,we(n,l);const _=C.decision;await So(i,l,m.pmRoot,_),await Ao(i,c,l,a,m.pmRoot),await Be({command:n,commandPath:i,commandArgs:u.args,commandOptions:l,expectHash:s.expectHash,pmRoot:m.pmRoot,rewritten:Ot(u,[E,{args:c,path:a.path}]),globalOptions:{...a,path:s.path,noExtensions:s.noExtensions}});const A=_.run_extension_migrations?await pt(n,[],()=>rt(m.registrations.migrations,m.pmRoot)):[];a.profile&&A.length>0&&y(`profile:extensions migration_warnings=${S(A)}`);const b=pr(m.registrations.migrations);T={hooks:m.hooks,commandName:i,commandArgs:c,commandOptions:{...l},globalOptions:{...a},pmRoot:m.pmRoot,profileEnabled:!!a.profile,migrationBlockers:b},L(void 0),ge({command:i,args:c,options:{...l},global:{...a},pm_root:m.pmRoot}),x=await ao({command:i,pm_version:N,args:c,options:l,global:a,pm_root:m.pmRoot}),await ut(e),await gt(i,c,l);const w=await Sn(m.hooks,{command:i,args:c,options:{...l},global:{...a},pm_root:m.pmRoot});a.profile&&w.length>0&&y(`profile:extensions hook_warnings=${S(w)}`),_.enforce_mandatory_migration_gate&&gr(i,l,b)}),e.hook("postAction",async()=>{const t=Lo();await ie(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await V(t),await U()}))}ft(p);const ht=Symbol("pmCliIdempotentTopLevelRegistration");function yt(e){const o=e;if(o[ht])return;o[ht]=!0;const t=e.command.bind(e);e.command=((n,...r)=>{const s=n.split(/\s+/u)[0];return e.commands.some(i=>i.name()===s||i.aliases().includes(s))?new ae(s):t(n,...r)})}async function vi(e,o){if(yt(e),o.setup){const{registerSetupCommands:t}=await ti();t(e)}if(o.listQuery){const{registerListQueryCommands:t}=await ni(),n=typeof o.targetCommandName=="string"&&Gr.has(o.targetCommandName)?new Set([o.targetCommandName]):void 0;t(e,n?{commandFilter:n}:void 0)}if(o.mutation){const{registerMutationCommands:t}=await ri();t(e,{targetCommandName:o.targetCommandName})}if(o.operation){const{registerOperationCommands:t}=await ii();t(e)}}function $(e){return e.rawInvocationArgv??e.invocationArgv}function wi(e){return async o=>{const t=Rn(o.errorCode),n=mn({ok:!1,errorCode:o.errorCode,errorCategory:t});return await un({command:o.command,args:e.invocationArgv,options:o.options,global:e.bootstrapGlobal,pm_version:N,pm_root:e.bootstrapPmRoot,error_code:o.errorCode,error_message:o.errorMessage,exit_code:o.exitCode,error_category:t,command_resolution:n,resolution_stage:o.resolutionStage}),{errorCategory:t,commandResolution:n}}}async function Ct(e){if(e.bootstrapGlobal.noExtensions||xe(e.invocationArgv))return;const o=j(e.invocationArgv),t=await ne(e.bootstrapPmRoot);if(t&&Y(t.discovery,o)){const n=await H(e.bootstrapPmRoot,o);_t(n);return}t&&te(Fe(e.invocationArgv),t,o),O({overrides:[]})}function _t(e){if(!e){O({overrides:[]});return}O(e.services)}async function Ne(e){await ie(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await V({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 vt(){await ie(!0,void 0,{exit_code:h.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await V({ok:!0,exit_code:h.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=h.SUCCESS}async function wt(e,o){const t=typeof o=="number"&&Number.isFinite(o);if(!(e.error instanceof G)&&(qe(e.error)||!t))return!1;const n=Qe(D(e.error)),r=e.error instanceof G?e.error.exitCode:Ke(o),s=e.error instanceof G||Gt(e.error)?e.error.context:void 0,i=Vo(s,e.invocationArgv,n),c=Vn(n,i),u=Le(e.bootstrapGlobal.lean?Yn(_o(n,r,i)):_o(n,r,i)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?on(u,g=>`${JSON.stringify(g,null,2)}
2
+ `):u,null,2):Kn(n,i,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?fe(`${l}
3
+ `):y(l);const{errorCategory:a,commandResolution:d}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:c.code,errorMessage:c.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),m=await oe({command:e.attemptedCommand,error_code:c.code,error_category:a,exit_code:r,error_message:c.detail,command_resolution:d,resolution_stage:"execute",source_context:x?.source_context},e.bootstrapGlobal);return await Ne({errorMessage:n,exitCode:r,classificationCode:c.code,errorCategory:a,commandResolution:d,resolutionStage:"execute"}),m&&(ro(Ye(e.error,n)),await U(Se)),process.exitCode=r,!0}async function Et(e,o){const t=Ce(e.invocationArgv).commandPathTokens.join(" ")||yo(e.invocationArgv),n=ce(t),r=`unknown command '${t}'`,s=R(process.cwd(),e.bootstrapGlobal.path),i=e.bootstrapGlobal.noExtensions?v:await Me(s),c=j(e.invocationArgv),u=e.bootstrapGlobal.noExtensions?[]:await sr(s,{},Ee(c)),l=await ho({message:r},p,i,{failedExtensions:u},$(e)),a=Co(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:u}),{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:a.code,errorMessage:a.detail,exitCode:h.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:o??"commander.helpDisplayed"},resolutionStage:"parse"}),g=await oe({command:n,error_code:a.code,error_category:d,exit_code:h.USAGE,error_message:a.detail,command_resolution:m,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await go({message:r},p,i,e.bootstrapGlobal.lean===!0,{failedExtensions:u},$(e)):await fo({message:r},p,i,{failedExtensions:u},$(e)),E=po(f,e.jsonErrors,u);await Ne({errorMessage:r,exitCode:h.USAGE,classificationCode:a.code,errorCategory:d,commandResolution:m,resolutionStage:"parse"}),e.jsonErrors?fe(`${We(E)}
4
+ `):y(E),g&&await U(Se),process.exitCode=h.USAGE}async function Rt(e,o,t){if(!(o==="commander.helpDisplayed"||o==="commander.help"||o==="commander.helpCommand")&&!t.includes("(outputHelp)"))return!1;const r=Ce(e.invocationArgv);return r.requested&&!_e(p,r.commandPathTokens)?(await Et(e,o),!0):(await vt(),!0)}async function xt(e,o){const t=await ho(e.error,p,v,{},$(e)),n=Co(t.message,t.commandName,t.allowedTypes,{unknownCommandExamples:t.unknownCommandExamples,unknownCommandNextSteps:t.unknownCommandNextSteps,attemptedCommand:t.attemptedCommand,normalizedInvocationArgs:t.normalizedInvocationArgs,providedOptionFlags:t.providedOptionFlags,unknownOptionSuggestions:t.unknownOptionSuggestions,suggestedRetryCommand:t.suggestedRetryCommand}),{errorCategory:r,commandResolution:s}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:h.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:o},resolutionStage:"parse"}),i=await oe({command:e.attemptedCommand,error_code:n.code,error_category:r,exit_code:h.USAGE,error_message:n.detail,command_resolution:s,resolution_stage:"parse",source_context:x?.source_context},e.bootstrapGlobal),c=e.jsonErrors?await go(e.error,p,v,e.bootstrapGlobal.lean===!0,{},$(e)):await fo(e.error,p,v,{},$(e)),u=await ar(n.code,e.bootstrapPmRoot,{},Ee(j(e.invocationArgv))),l=po(c,e.jsonErrors,u);await Ne({errorMessage:t.message,exitCode:h.USAGE,classificationCode:n.code,errorCategory:r,commandResolution:s,resolutionStage:"parse"}),e.jsonErrors?fe(`${We(l)}
5
+ `):y(l),i&&await U(Se),process.exitCode=h.USAGE}function bt(e){if(typeof e!="object"||e===null||!("code"in e))return!1;const o=e.code;return typeof o=="string"&&(o==="commander.version"||o.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function St(e){const o=e.error.code,t=String(e.error.message??"");if(!await Rt(e,o,t)){if(o==="commander.version"){await vt();return}await xt(e,o)}}async function $e(e){const o=P(e.invocationArgv),t=R(process.cwd(),o.path),n=Bt(e.invocationArgv),r={error:e.error,invocationArgv:n,rawInvocationArgv:e.invocationArgv,bootstrapGlobal:o,jsonErrors:o.json,bootstrapPmRoot:t,attemptedCommand:ye(n)??"<unknown>",emitTelemetryCommandError:wi({invocationArgv:n,bootstrapGlobal:o,bootstrapPmRoot:t})};if(await Ct({invocationArgv:e.invocationArgv,bootstrapGlobal:o,bootstrapPmRoot:t}),!await wt(r,Je(e.error))){if(bt(e.error)){await St(r);return}await Yo({error:e.error,attemptedCommand:r.attemptedCommand,bootstrapGlobal:o,emitTelemetryCommandError:r.emitTelemetryCommandError})}}function Ei(e,o,t){const n=t.requested?t.commandPathTokens:mo(o),r=It(n);if(r&&!ve(e,[...r.canonical_argv]))throw new ze(h.USAGE,"commander.unknownCommand",`unknown command '${r.alias}'`)}function Ri(e,o){let t=he(o);if(t===void 0)return;if(["pm","pm-cli"].includes(o[t]?.trim().toLowerCase())){const i=he(o.slice(t+1));if(i===void 0)return;t+=i+1}const n=X.get(o[t]),r=o.slice(t).filter(i=>!["--global","--project","--local"].includes(i)),s=n?.find(i=>i.alias.split(" ").every((c,u)=>r[u]===c));s?.lifecycle==="deprecated"&&Reflect.set(e,Wo,s.alias)}function xi(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function bi(e,o){p=Ve(N),p.hook("preAction",(s,i)=>{o.configurationOnly=["item mutate","item complete"].includes(M(i))&&i.optsWithGlobals().dryRun===!0}),ft(p,e),z=null,F=null,v=new Map,Cn();let t=[...e],n,r;try{const s=lo(e);t=s.argv,Wr(s.trace),Ri(p,e);const i=xi(t),c=t.length===0,u=P(t);if(u.authorMissingValue)throw new G("--author requires a non-empty value.",h.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});n=en(u.author),Ho(s),r=Bn(t);const l=No(t);await vi(p,l),uo(p,!0),Go(p,t)?await dt(p,t):(v=new Map,O({overrides:[]})),Uo(t)&&await et(p,t),uo(p);const d=Ce(t);Ei(p,t,d),$o(t)&&cr(p,t),lt(p);const m=await pi(d,u);if(await ur(p,t,m,e))return;if(d.requested&&!_e(p,d.commandPathTokens))throw new ze(h.USAGE,"commander.helpDisplayed","(outputHelp)");if(c||lr(t)&&ye(t)===void 0){p.outputHelp();return}if(xe(t)){await p.parseAsync(i);return}const f=R(process.cwd(),u.path),E=await I(f),C=await zn(t,f,u.noExtensions,H);await Tt(_=>Ht({pmRoot:f,packages:C?.contextIntentPackages},()=>An({env:{...process.env,PM_PATH:f},argv:i,cwd:process.cwd()},()=>Pn(E.agent_identity.harness_signals,()=>_(()=>p.parseAsync(i)),{probesEnabled:E.agent_identity?.probes_enabled}))))}catch(s){await $e({error:s,invocationArgv:t})}finally{r?.(),n?.()}}async function vs(e=process.argv.slice(2)){let o=e;try{o=lo(e).argv}catch{}await zt([...e,...o],()=>Si(e,o))}async function Si(e,o){const t=Lr(o),n={configurationOnly:t!==void 0},r=()=>n.configurationOnly,s=()=>kt(P(o).json,async()=>{try{await rn(process.env,()=>bi(e,n))}catch(i){await $e({error:i,invocationArgv:[...e]})}});if(t!==void 0){const i=R(process.cwd(),P(o).path),c=R(process.cwd(),t.path),u=_n(process.cwd());await pe(i,()=>pe(c,()=>pe(u,s,r),r),r)}else await s()}const ws={activationCommandMatchesProbe:Cr,applyDynamicExtensionRootHelpVisibility:mt,bootstrapProfileEnabled:Fe,buildBootstrapActivationProbe:j,buildPostActionTelemetryOutcome:Lo,buildPmCliRecoveryContext:Vo,buildRuntimeExtensionDiscoverySnapshotCacheKey:De,buildRuntimeExtensionActivationScope:Oo,buildRuntimeExtensionSnapshotCacheKey:ot,buildRuntimeExtensionFilterForProbe:To,addRuntimeFieldOption:ke,collectActivationCommandCandidates:Ee,collectExtensionFlagDefinitionsForCommand:Ir,collectExtensionFlagDefinitionsForInvocation:Q,collectLeadingCommandArgs:_r,collectParsedActivationCommandArgs:Fo,collectRuntimeFieldLooseFlagDefinitionsForCommand:Zo,commandHasLongOption:Qo,commandHasShortOption:Xo,commandPathNeedsSearchExtensions:vr,commandPathNeedsTemplateExtensions:wr,describeUnknownError:D,defaultPreflightDecision:Te,discoveryNeedsActivationForProbe:Y,emitExtensionProfile:tt,emitExtensionSkippedProfile:te,emitSettingsReadWarnings:Ie,ensureIdempotentTopLevelCommandRegistration:yt,enforceExplicitRetryForFlagTypos:Ho,envFlagEnabled:Ko,executeRegisteredRuntimeMigrations:rt,extractCommandScopedOptions:B,extensionActivationCommands:Er,extensionCapabilities:Rr,extensionNeedsActivationForProbe:xr,extensionProvidesTemplatesRuntime:br,hasAnyCapability:Sr,hasGlobalExtensionContributions:Ar,handleGenericRunPmCliError:Yo,handleRunPmCliCommanderError:St,handleRunPmCliError:$e,handleRunPmCliHelpDisplayError:Rt,handleRunPmCliKnownError:wt,handleRunPmCliCommanderUsageError:xt,handleUnknownHelpCommandError:Et,inferMissingFieldsFromErrorMessage:jo,inferPostActionErrorCode:jr,inferPostActionFailureMessage:Br,invocationRequestsVersion:Ur,isCommanderError:qe,loadRuntimeExtensionCommandDescriptorsForRecovery:Me,loadRuntimeExtensionDiscoverySnapshot:ne,loadRuntimeExtensionSnapshot:H,maybeLoadRuntimeExtensions:nt,maybeAttachCreateUpdatePolicyHelpText:Oe,maybeLogHandledCliErrorToSentry:oe,matchesStaticExtensionCommand:Pr,normalizeTelemetryCommandResolution:zr,normalizeTelemetryErrorCategory:Vr,normalizeTelemetryResolutionStage:qr,normalizeThrownExitCode:Ke,probeUsesAnyFlag:kr,prepareExtensionServicesForRunPmCliError:Ct,readRecordBoolean:Kr,readRecordNumber:Jr,readRecordString:Yr,recordCliReadOutputInvocationProvenance:Hr,registerDynamicExtensionCommandPaths:dt,registerRuntimeSchemaFieldFlags:et,resolveCoreCommandRegistrationSelection:No,resolveStaticExtensionActivationDecision:Or,resolveUnknownHelpToken:yo,readThrownExitCode:Je,runAndClearAfterCommandHooks:V,runRequiredExtensionCommand:st,shouldAttachRichHelpTextForInvocation:$o,shouldLogHandledErrorToSentry:Jo,shouldRegisterDynamicExtensionPaths:Go,shouldRegisterRuntimeSchemaFlags:Uo,shouldHandleRunPmCliCommanderError:bt,setActiveExtensionHookContextForTest:Xr,setActiveRuntimeExtensionCommandDescriptorsForTest:Zr,setRecoveredExtensionServices:_t,toLooseFieldDefinitionType:Pe,isImporterOrExporterCommandPath:Io,validateDynamicExtensionCommandInvocation:Mo,wrapProgramActionsForExtensionHandlers:lt,wrapThrownErrorForSentry:Ye};export{ws as _testOnly,vs as runPmCli};
6
6
  //# sourceMappingURL=main.js.map
@@ -1,11 +1,11 @@
1
- import{EXIT_CODE as p,PmCliError as f,readSettings as R,renderRowsAsCsv as q,renderRowsAsTable as L,resolvePmRoot as $}from"../sdk/runtime-primitives.js";import{renderPmCommandAliasMigrationHint as G,resolvePmCommandAlias as M}from"../sdk/cli-contracts.js";import{EVAL_QUERY_SET_SCHEMA_ID as B}from"../sdk/eval.js";import{applyContextIntentProjection as F}from"../sdk/context-intent-contracts.js";import{renderPmClosedDomainHelp as b}from"../sdk/agent/closed-domain-contracts.js";import{serializeNdjsonRows as A,serializeNdjsonStream as I}from"../sdk/output.js";import{listMutationEvents as N,subscribeMutationEventBatches as T,subscribeMutationEvents as U}from"../sdk/mutation-events.js";import{registerHistoryActivityCommand as C}from"./register-history-activity.js";import{registerHistoryMaintenanceCommands as P}from"./register-history-maintenance.js";import{runAggregate as z}from"./commands/query/aggregate.js";import{renderContextMarkdown as H,runContext as J,resolveContextOutputFormat as Q}from"./commands/query/context.js";import{runEval as V}from"./commands/query/eval.js";import{runGet as K}from"./commands/query/get.js";import{runGraph as W}from"./commands/query/graph.js";import{runHistory as X}from"./commands/history/history.js";import{runList as Y}from"./commands/query/list.js";import{LIST_COMMAND_DEFAULT_PROJECTIONS as Z}from"../sdk/query/list.js";import{renderNextMarkdown as ee,runNext as te,resolveNextOutputFormat as ne}from"./commands/query/next.js";import{runSearch as oe}from"./commands/query/search.js";import{addHiddenOption as s,collect as l,getGlobalOptions as h,normalizeAggregateOptions as ie,normalizeContextOptions as ae,normalizeListOptions as re,normalizeNextOptions as se,normalizeSearchKeywordsInput as le,normalizeSearchOptions as de,printError as m,printListJsonStream as ue,printResult as y,setActiveCommandResult as S,writeStdout as v}from"./registration-helpers.js";function ce(e,o){return!o||o.size===0?!0:e==="context"?o.has("context")||o.has("ctx"):o.has(e)}function j(e){if(e===void 0)return;if(typeof e!="string")throw new f("List --format must be one of csv|table|json|ndjson|toon",p.USAGE);const o=e.trim().toLowerCase();if(o==="csv"||o==="table"||o==="json"||o==="ndjson"||o==="toon")return o;throw new f("List --format must be one of csv|table|json|ndjson|toon",p.USAGE)}function k(e,o,i,t=!1){if(o===void 0)return i;if(typeof o!="string")throw new f(`${e} --format must be one of ${t?"json|ndjson|toon":"json|toon"}`,p.USAGE);const a=o.trim().toLowerCase();if(a!=="json"&&(a!=="ndjson"||!t)&&a!=="toon")throw new f(`${e} --format must be one of ${t?"json|ndjson|toon":"json|toon"}`,p.USAGE);if(i.json===!0&&a==="toon")throw new f(`${e} cannot combine --json with --format toon`,p.USAGE);return{...i,json:a==="json"||a==="ndjson"}}function pe(e,o){Z[o]==="brief"&&e.includeBody!==!0&&e.compact!==!0&&e.brief!==!0&&e.full!==!0&&e.fields===void 0&&(e.brief=!0)}function O(e){e.option("--has-notes","Show only items that have notes").option("--has-learnings","Show only items that have learnings").option("--has-files","Show only items that have linked files").option("--has-docs","Show only items that have linked docs").option("--has-tests","Show only items that have linked tests").option("--has-comments","Show only items that have comments").option("--has-deps","Show only items that have dependencies").option("--has-body","Show only items that have a non-empty body").option("--has-linked-command","Show only items whose linked tests carry a runnable command").option("--no-notes","Show only items that have no notes").option("--no-learnings","Show only items that have no learnings").option("--no-files","Show only items that have no linked files").option("--filter-files-missing","Alias for --no-files").option("--no-docs","Show only items that have no linked docs").option("--filter-docs-missing","Alias for --no-docs").option("--no-tests","Show only items that have no linked tests").option("--no-comments","Show only items that have no comments").option("--no-deps","Show only items that have no dependencies").option("--empty-body","Show only items with an empty body").option("--no-linked-command","Show only items whose linked tests carry no runnable command").option("--filter-reviewer-missing","Show only items missing reviewer").option("--filter-risk-missing","Show only items missing risk").option("--filter-confidence-missing","Show only items missing confidence").option("--filter-sprint-missing","Show only items missing sprint").option("--filter-release-missing","Show only items missing release")}const me={draft:{name:"list-draft",dependencyBlocked:!1},open:{name:"list-open",dependencyBlocked:!1},in_progress:{name:"list-in-progress",dependencyBlocked:!1},blocked:{name:"list-blocked",dependencyBlocked:!0},closed:{name:"list-closed",dependencyBlocked:!1},canceled:{name:"list-canceled",dependencyBlocked:!1}};function fe(e,o){const i=e.stream===!0,t=j(e.format),a=t==="csv"||t==="table",n=t==="json"||t==="ndjson"||t==="toon"?k("List",e.format,o,!0):o;if(i&&!n.json)throw new f("--stream requires --json output mode.",p.USAGE);if((a||t==="ndjson")&&i)throw new f("--format csv|table|ndjson cannot be combined with --stream.",p.USAGE);return{streamMode:i,listFormat:t,effectiveGlobal:n}}function he(e,o,i){if(i.listFormat==="csv"||i.listFormat==="table"){S(o);const t=o.items,a=i.listFormat==="csv"?q(t):L(t);!i.effectiveGlobal.quiet&&a.length>0&&v(`${a}
2
- `)}else if(i.listFormat==="ndjson"){S(o);const t=A(o.items);!i.effectiveGlobal.quiet&&t.length>0&&v(`${t}
3
- `)}else i.streamMode?ue(e,o,i.effectiveGlobal):y(o,i.effectiveGlobal)}function _(e,o,i,t=[]){if(i.outputBudget===void 0)return F(e,o,t);const{outputBudget:a,...n}=F(e,{...o,outputBudget:i.outputBudget},t);return n}async function ye(e){const o=h(e.actionCommand),i=e.aliasContract?{...o,command:e.aliasContract.canonical}:o,t=Date.now();e.aliasContract?.lifecycle==="deprecated"&&await R($(process.cwd(),i.path)).then(D=>D.ux.deprecation_hints)&&m(G(e.aliasContract));const a=_("list",e.options,i),n=re(a),r=ve(e,n),{effectiveName:d,effectiveStatus:u,effectiveDependencyBlocked:c,effectiveExcludeTerminal:w}=r;pe(n,e.name),Object.assign(n,{projectionCommand:d}),w&&(n.excludeTerminal=!0),n.dependencyBlocked=c;const x=fe(a,i),E=await Y(c?void 0:u,n,i);he("list",E,x),i.profile&&m(`profile:command=list took_ms=${Date.now()-t}`)}function ve(e,o){let i=e.name,t=e.status,a=e.dependencyBlocked===!0,n=e.excludeTerminal===!0;const r=o.status?.trim().toLowerCase(),d=e.name==="list"&&r!==void 0?me[r]:void 0;return e.name==="list"&&(e.options.all===!0||r==="all"?(i="list-all",n=!1,o.status=void 0):r!==void 0&&d!==void 0&&(i=d.name,t=r,a=d.dependencyBlocked,n=!1,o.status=void 0)),(i==="list-open"||i==="list-in-progress")&&(o.lifecycleBucket=i==="list-open"?"open":"in_progress",t=void 0),{effectiveName:i,effectiveStatus:t,effectiveDependencyBlocked:a,effectiveExcludeTerminal:n}}function ge(e,o){const{name:i,description:t,status:a,excludeTerminal:n,allowStatusFilter:r,dependencyBlocked:d,aliasContract:u}=o,c=e.command(i,{hidden:u?.hidden===!0}).description(t);r&&c.option("--status <value>","Filter by status (repeatable or comma-separated; matches any; all selects every status)",l),i==="list"&&c.option("--all","Include every lifecycle status"),c.option("--for <intent>",`Apply a declared context intent projection. ${b("list","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--type <value>","Filter by item type (repeatable or comma-separated; matches any)",l).option("--tag <value>","Filter by tag (repeatable or comma-separated; matches any)",l).option("--priority <value>","Filter by priority (repeatable or comma-separated; matches any)",l).option("--deadline-before <value>","Filter by deadline upper bound (ISO/date string or relative)").option("--deadline-after <value>","Filter by deadline lower bound (ISO/date string or relative)").option("--today","Filter to items updated since local midnight today").option("--recent","Filter to items updated in the last 7 days").option("--updated-after <value>","Updated since ISO timestamp or signed relative (-2h/-7d for past); use last-window ISO").option("--updated-before <value>","Filter by updated_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-after <value>","Filter by created_at lower bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-before <value>","Filter by created_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--ids <value>","Filter by explicit item IDs (comma-separated or repeatable)").option("--assignee <value>","Filter by assignee",l).option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--parent <value>","Filter by parent item ID").option("--sprint <value>","Filter by sprint",l).option("--release <value>","Filter by release",l).option("--filter-ac-missing","Show only items missing acceptance_criteria").option("--filter-estimates-missing","Show only items missing estimated_minutes").option("--filter-resolution-missing","Show only terminal items missing resolution").option("--filter-metadata-missing","Show only items missing any tracked metadata (AC, estimate, or resolution)").option("--limit <n>","Alias for --output-limit; --output-budget may cap rows").option("--offset <n>","Skip the first n matching rows before limit is applied").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor").option("--no-truncate","Disable default token cap; explicit --limit and --output-budget apply").option("--include-body","Include item body in each returned list row").option("--strict-read","Fail closed if any item document or item directory cannot be read").option("--compact","Render compact list projection fields (mutually exclusive with --brief/--full/--fields)").option("--brief","Brief rows: id, status, type, title and leading sort field (priority by default; excludes --compact/--full/--fields)").option("--full","Render full list projection fields (mutually exclusive with --compact/--brief/--fields)").option("--fields <value>",`Render custom comma-separated list fields (mutually exclusive with --compact/--brief/--full). ${b(i,"--fields")}`).option("--sort <value>","Sort field: priority|deadline|updated_at|created_at|title|parent (aliases: updated, created)").option("--order <value>","Sort order: asc|desc (requires --sort)").option("--tree","Render rows in parent/child tree order").option("--tree-depth <n>","Maximum recursion depth with --tree (0 keeps root rows only)").option("--format <value>","Output render mode: csv|table (human export) or json|ndjson|toon (machine output override)").option("--stream","Emit line-delimited JSON rows (requires --json)"),O(c),c.action(async(w,x)=>{await ye({name:i,status:a,excludeTerminal:n,dependencyBlocked:d,options:w,actionCommand:x,aliasContract:u})}),s(c,"--tags <value>","Alias for --tag"),s(c,"--assignee_filter <value>","Alias for --assignee-filter"),s(c,"--tree_depth <n>","Alias for --tree-depth"),s(c,"--token_budget <n>","Alias for --token-budget"),s(c,"--filter-estimate-missing","Alias for --filter-estimates-missing")}async function be(e,o){const i=h(o),t=Date.now(),a=await z(ie(e),i);y(a,i),i.profile&&m(`profile:command=aggregate took_ms=${Date.now()-t}`)}async function we(e,o){const i=h(o),t=Date.now(),a=ae(_("context",e,i)),n=await J(a,i),r=Q(a,i);if(r==="markdown")i.quiet||v(`${H(n)}
4
- `);else if(r==="ndjson"){S(n);const d=A([...n.high_level,...n.low_level,...n.blocked_fallback]);!i.quiet&&d.length>0&&v(`${d}
5
- `);const u=n.activity_history_read;u!==void 0&&m(`[pm] warning: activity_history_read reason=${u.reason} streams_read=${u.streams_read}/${u.streams_total}`)}else y(n,{...i,json:r==="json"});i.profile&&m(`profile:command=context took_ms=${Date.now()-t}`)}async function xe(e,o){const i=h(o),t=Date.now(),a=se(_("next",e,i)),n=await te(a,i),r=ne(a,i);r==="markdown"?i.quiet||v(`${ee(n)}
6
- `):y(n,{...i,json:r==="json"}),i.profile&&m(`profile:command=next took_ms=${Date.now()-t}`)}async function ke(e,o,i){const t=h(i),a=Date.now(),n=le(e),r=_("search",o,t,[n]),d=de(r),u=await oe(n,d,t),c=typeof r.format=="string"?r.format.trim().toLowerCase():void 0,w=k("Search",r.format,t,!0);if(c==="ndjson"){S(u);const x=A(u.items);!w.quiet&&x.length>0&&v(`${x}
7
- `)}else y(u,w);t.profile&&m(`profile:command=search took_ms=${Date.now()-a}`)}async function Se(e,o){const i=h(o),t=Date.now(),a=await V({mode:typeof e.mode=="string"?e.mode:void 0,k:typeof e.k=="string"?e.k:void 0,failUnder:typeof e.failUnder=="string"?e.failUnder:void 0,queries:typeof e.queries=="string"?e.queries:void 0,format:typeof e.format=="string"?e.format:void 0},i);if(y(a,k("Eval",e.format,i)),i.profile&&m(`profile:command=eval took_ms=${Date.now()-t}`),!a.passed)throw new f("Eval gate failed: one or more aggregate or per-query thresholds were not met; inspect the metric report",p.GENERIC_FAILURE)}async function _e(e,o,i){const t=h(i),a=Date.now(),n=_("get",o,t,[e]),r=await K(e,t,{depth:typeof n.depth=="string"?n.depth:void 0,fields:typeof n.fields=="string"?n.fields:void 0,full:!!n.full,tree:n.tree===!0,treeDepth:typeof n.treeDepth=="string"?n.treeDepth:typeof n.tree_depth=="string"?n.tree_depth:void 0,at:typeof n.at=="string"?n.at:void 0});y(r,k("Get",n.format,t)),t.profile&&m(`profile:command=get took_ms=${Date.now()-a}`)}async function Ae(e,o,i){const t=h(i),a=Date.now();if([o.compact,o.raw,o.full,o.provenance].filter(u=>u===!0).length>1)throw new f("History projection options are mutually exclusive. Use --compact, --provenance, or --full.",p.USAGE);const n=typeof o.field=="string"?o.field:void 0,r=!!o.strictExit||!!o.failOnWarn;if(r&&!o.verify)throw new f("--strict-exit requires --verify (it gates on the verification result).",p.USAGE);const d=await X(e,{limit:typeof o.limit=="string"?o.limit:void 0,order:o.order,compact:!(o.full===!0||o.provenance===!0),provenance:o.provenance===!0,provenanceSummary:o.provenanceSummary===!0,harness:g(o,"harness"),agentInstance:g(o,"agentInstance"),provenanceFilter:g(o,"provenanceFilter"),diff:!!o.diff||n!==void 0,field:n,verify:!!o.verify},t);y(d,k("History",o.format,t)),r&&d.verification&&!d.verification.ok&&(process.exitCode=p.GENERIC_FAILURE),t.profile&&m(`profile:command=history took_ms=${Date.now()-a}`)}function g(e,o){const i=e[o];return Array.isArray(i)?i:void 0}function Fe(e,o){const i=g(e,"harness"),t=g(e,"agentInstance"),a=g(e,"provenanceFilter"),n=typeof e.cursorMode=="string"?e.cursorMode:void 0;if(n!==void 0&&n!=="batch"&&n!=="row")throw new f("Events --cursor-mode must be batch or row.",p.USAGE,{code:"invalid_event_cursor_mode"});const r=n;return{pmRoot:o,since:typeof e.since=="string"?e.since:void 0,type:g(e,"type"),author:g(e,"author"),item:g(e,"item"),limit:typeof e.limit=="string"?Number(e.limit):void 0,full:e.full===!0,...e.verify===!0?{verify:!0}:{},...e.provenance===!0?{provenance:!0}:{},...e.provenanceSummary===!0?{provenanceSummary:!0}:{},...i===void 0?{}:{harness:i},...t===void 0?{}:{agentInstance:t},...a===void 0?{}:{provenanceFilter:a},cursorMode:r}}async function Ie(e,o,i){if(o.provenanceSummary===!0)throw new f("Events --provenance-summary is bounded to one page and cannot be combined with --follow.",p.USAGE);const t=typeof o.intervalMs=="string"?Number(o.intervalMs):void 0;if(e.cursorMode==="row"){for await(const a of U({...e,intervalMs:t}))i||v(`${JSON.stringify(a)}
8
- `);return}for await(const a of T({...e,intervalMs:t}))i||v(`${I(a.events,{count:a.count,has_more:a.has_more,next_cursor:a.next_cursor??null,source:a.source,integrity:a.integrity,...a.verified_streams===void 0?{}:{verified_streams:a.verified_streams},heartbeat:a.count===0})}
9
- `)}function Ce(e){return e.cursor_mode==="row"?A(e.events):I(e.events,{count:e.count,has_more:e.has_more,next_cursor:e.next_cursor??null,source:e.source,integrity:e.integrity,...e.verified_streams===void 0?{}:{verified_streams:e.verified_streams},...e.provenance_summary===void 0?{}:{provenance_summary:e.provenance_summary}})}async function je(e,o){const i=h(o),t=Date.now(),a=Fe(e,i.path);if(e.follow===!0){await Ie(a,e,i.quiet===!0);return}const n=await N(a);if(S(n),i.json){y(n,i),i.profile&&m(`profile:command=events took_ms=${Date.now()-t}`);return}const r=Ce(n);!i.quiet&&r.length>0&&v(`${r}
10
- `),i.profile&&m(`profile:command=events took_ms=${Date.now()-t}`)}async function Oe(e,o,i,t,a){const n=h(a),r=Date.now(),d=await W(e,o,i,{...Array.isArray(t.kind)?{kind:t.kind}:{},maxDepth:typeof t.maxDepth=="string"?t.maxDepth:void 0,limit:typeof t.limit=="string"?t.limit:void 0,after:typeof t.after=="string"?t.after:void 0,direction:typeof t.direction=="string"?t.direction:void 0,maxPaths:typeof t.maxPaths=="string"?t.maxPaths:void 0,sample:typeof t.sample=="string"?t.sample:void 0,...Array.isArray(t.exemptIsolate)?{exemptIsolate:t.exemptIsolate}:{},...Array.isArray(t.exemptIsolateType)?{exemptIsolateType:t.exemptIsolateType}:{},saveBaseline:t.saveBaseline===!0,rebuild:t.rebuild===!0,clear:t.clear===!0,summary:t.summary===!0,full:t.full===!0},n);y(d,n),n.profile&&m(`profile:command=graph took_ms=${Date.now()-r}`)}function Ye(e,o){const i=o?.commandFilter,t=n=>ce(n,i),a=[{name:"list",description:"List active items with optional lifecycle-status and project filters.",excludeTerminal:!0,allowStatusFilter:!0},{name:"list-all",description:"List all items with optional filters.",excludeTerminal:!1,allowStatusFilter:!0},{name:"list-draft",description:"List draft items with optional filters.",status:"draft"},{name:"list-open",description:"List open items with optional filters.",status:"open",excludeTerminal:!1,allowStatusFilter:!1},{name:"list-in-progress",description:"List in-progress items with optional filters.",status:"in_progress",excludeTerminal:!1,allowStatusFilter:!1},{name:"list-blocked",description:"List blocked items (blocked status or open blocked_by dependencies, matching pm next) with optional filters.",dependencyBlocked:!0,excludeTerminal:!1,allowStatusFilter:!1},{name:"list-closed",description:"List closed items with optional filters.",status:"closed"},{name:"list-canceled",description:"List canceled items with optional filters.",status:"canceled"}];for(const n of a)if(t(n.name)){const r=M(n.name);ge(e,{...n,...r?.registration==="commander"?{aliasContract:r}:{}})}if(t("aggregate")){const n=e.command("aggregate").description("Group item counts and numeric measures.").option("--set-mode <value>","Set grouping: element (default)|tuple").option("--limit <value>","Group page size (default: 50)").option("--after <value>","Continue with next_after cursor").option("--group-by <value>","Fields: parent,type,priority,status,assignee,tags,sprint,release (comma-separated)").option("--count","Counts (default)").option("--completion","Status counts and completion_pct").option("--sum <field>","Group numeric sum").option("--avg <field>","Group numeric average").option("--include-unparented","Keep unparented group").option("--status <value>","Item status").option("--type <value>","Item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--deadline-before <value>","Latest deadline (ISO/date or relative)").option("--deadline-after <value>","Earliest deadline (ISO/date or relative)").option("--assignee <value>","Filter by assignee").option("--assignee-filter <value>","Assignee presence: assigned|unassigned").option("--parent <value>","Parent ID").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release");s(n,"--include_unparented","Alias for --include-unparented"),s(n,"--assignee_filter <value>","Alias for --assignee-filter"),n.action(be)}if(t("context")){const n=e.command("context").alias("ctx").description("Show a token-efficient project context snapshot for next-work decisions.").option("--for <intent>",`Apply a declared context intent projection. ${b("context","--for")}`).option("--date <value>","Anchor date/time for agenda window calculations (ISO/date string or relative)").option("--from <value>","Agenda lower bound (ISO/date string or relative)").option("--to <value>","Agenda upper bound (ISO/date string or relative)").option("--past","Include past agenda entries in bounded windows").option("--type <value>","Filter by item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--assignee <value>","Filter by assignee").option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release").option("--parent <id>","Scope the snapshot to one item's subtree (the item plus all descendants)").option("--limit <n>","Limit focus and agenda rows per section").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor").option("--format <value>","Context output format override: markdown|toon|json|ndjson").option("--depth <value>","Context depth: brief|standard|deep|full (full = every section, no per-section cap)").option("--section <value...>","Include specific sections (repeatable; overrides --depth)").option("--fields <value>","Project focus rows to a comma-separated field subset (e.g. id,title,priority)").option("--activity-limit <n>","Limit recent activity entries (default: settings or 10)").option("--stale-threshold <value>","Staleness cutoff in days (e.g. 7 or 7d; default: settings or 7)").option("--explain-ranking","Include the scorer model, per-signal contributions, and ranked candidate ids").option("--token-budget <n>","Complete JSON/TOON response token ceiling").option("--no-extension-health","Omit the installed extension health summary").option("--no-tags","Omit tag arrays from context focus rows");s(n,"--assignee_filter <value>","Alias for --assignee-filter"),s(n,"--max-items <n>","Alias for --limit"),s(n,"--explain_ranking","Alias for --explain-ranking"),s(n,"--token_budget <n>","Alias for --token-budget"),n.action(we)}if(t("next")){const n=e.command("next").description("Recommend the next actionable (unblocked, ready) work item with rationale + blocked companion.").option("--for <intent>",`Apply a declared context intent projection. ${b("next","--for")}`).option("--type <value>","Filter candidate items by type").option("--tag <value>","Filter candidate items by tag").option("--priority <value>","Filter candidate items by priority").option("--assignee <value>","Filter candidate items by assignee").option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--sprint <value>","Filter candidate items by sprint").option("--release <value>","Filter candidate items by release").option("--parent <id>","Scope to one item's subtree (the item plus all descendants)").option("--limit <n>","Limit ready rows (default: 5; non-positive falls back to default)").option("--blocked-limit <n>","Limit blocked rows (default: same as --limit)").option("--ready-only","Omit the blocked companion list").option("--include-decisions","Include human-gated Decision items in the claimable ready queue").option("--include-gates","Include outcome gates in the ready queue").option("--include-containers","Include containers with unfinished descendants in the ready queue").option("--format <value>","Next output format override: markdown|toon|json").option("--explain-ranking","Include the scorer model, per-signal contributions, and ranked ready ids").option("--token-budget <n>","Maximum estimated tokens spent on the ranked ready queue");s(n,"--assignee_filter <value>","Alias for --assignee-filter"),s(n,"--blocked_limit <n>","Alias for --blocked-limit"),s(n,"--ready_only","Alias for --ready-only"),s(n,"--explain_ranking","Alias for --explain-ranking"),s(n,"--token_budget <n>","Alias for --token-budget"),n.action(xe)}if(t("search")){const n=e.command("search").argument("<keywords...>","Keyword query tokens").description("Search items with keyword, semantic, or hybrid retrieval. Inline field:value tokens (tag:/status:/type:/priority:) in the query are parsed as filters, e.g. 'auth tag:area:search status:open'.").option("--for <intent>",`Apply a declared context intent projection. ${b("search","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--mode <value>","Search mode: keyword|semantic|hybrid (default: auto)").option("--semantic","Shorthand for --mode semantic").option("--hybrid","Shorthand for --mode hybrid").option("--match-mode <value>","Token match mode: and|or|exact (default: or with all-terms ranking bonus; and = hard-require every token; exact = exact phrase)").option("--min-score <value>","Per-query minimum score threshold (finite number >= 0); overrides settings search.score_threshold for this query only").option("--count","Return only the count of matching items (post-filter/threshold, pre-limit); skips hit rows").option("--semantic-weight <value>","Override hybrid semantic weight for this query (0..1); invalid values fall back to settings").option("--include-linked","Include linked files, docs, and tests in the searchable corpus").option("--title-exact","Require exact normalized title match for the full query string").option("--phrase-exact","Require exact normalized phrase match in searchable text").option("--highlight","Emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit; off by default").option("--status <value>","Filter by status before query (all, open/closed/canceled aliases, or configured status id; CSV)").option("--type <value>","Filter by item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--deadline-before <value>","Filter by deadline upper bound (ISO/date string or relative)").option("--deadline-after <value>","Filter by deadline lower bound (ISO/date string or relative)").option("--updated-after <value>",'Filter by updated_at lower bound: ISO timestamp or signed relative (e.g. "-2h"/"-7d" for the past)').option("--updated-before <value>","Filter by updated_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-after <value>","Filter by created_at lower bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-before <value>","Filter by created_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--assignee <value>","Filter by assignee").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release").option("--parent <value>","Filter by parent item ID").option("--compact","Render compact search hits (default; mutually exclusive with --full/--fields)").option("--full","Render full search hits with nested item payloads (mutually exclusive with --compact/--fields)").option("--fields <value>",`Render custom comma-separated search hit fields (mutually exclusive with --compact/--full). ${b("search","--fields")}`).option("--format <value>","Search output format override: json|ndjson|toon").option("--limit <n>","Limit returned item count").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor");O(n),n.action(ke),s(n,"--tags <value>","Alias for --tag"),s(n,"--token_budget <n>","Alias for --token-budget")}if(t("eval")&&e.command("eval").description("Evaluate search relevance against a curated golden-query set: reports nDCG@k, MRR@k, precision@k, and recall@k per query plus the macro average. Use --fail-under as a CI gate.").option("--mode <value>","Default retrieval mode for queries without their own: keyword|semantic|hybrid (default: keyword)").option("--k <n>","Metric cutoff @k (positive integer; default: 10)").option("--fail-under <value>","Exit non-zero when aggregate nDCG@k falls below this threshold (0..1); CI gate").option("--queries <path>",`Query JSON (${B}); default: search/eval-queries.json; errors show an example`).option("--format <value>","Eval output format override: json|toon").action(Se),t("get")){const n=e.command("get").argument("<id>","Item id").option("--for <intent>",`Apply a declared context intent projection. ${b("get","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--depth <value>","brief|standard|deep|full (default: standard)").option("--full","Full details and children for any type; excludes --depth/--fields").option("--fields <value>",`Render custom comma-separated item metadata fields. ${b("get","--fields")}`).option("--tree","Include descendants rooted at the requested item").option("--tree-depth <n>","Maximum subtree depth for --tree descendants").option("--at <version-or-timestamp>","Reconstruct a verified historical item state without mutating it").option("--format <value>","Get output format override: json|toon").description("Show item details by ID.").action(_e);s(n,"--tree_depth <n>","Alias for --tree-depth"),s(n,"--token_budget <n>","Alias for --token-budget")}if(t("history")){const n=e.command("history").enablePositionalOptions().argument("<id>","Item id").option("--limit <n>","Latest N; keeps order").option("--order <value>","oldest_first|newest_first").option("--compact","Summary (default newest_first)").option("--full","Patches (default oldest_first)").option("--provenance","Authors (default newest_first)").option("--provenance-summary","Count provenance completeness").option("--harness <value>","Harness (repeatable)",l).option("--agent-instance <value>","Instance (repeatable)",l).option("--provenance-filter <dimension=value>","Provenance (repeatable)",l).option("--diff","Before/after field diffs").option("--field <name>","Filter changed field; implies --diff").option("--verify","Verify full chain and replay").option("--strict-exit","With --verify, fail on integrity errors").option("--fail-on-warn","Alias for --strict-exit").option("--format <value>","Output: json|toon").description("Read history.").action(Ae);P(n,!0),C(n.command("activity"))}t("events")&&e.command("events").option("--since <cursor-or-timestamp>","Resume strictly after a durable cursor, or include events from an ISO timestamp").option("--type <value>","Filter by mutation operation (repeatable or comma-separated)",l).option("--author <value>","Filter by mutation author (repeatable or comma-separated)",l).option("--item <value>","Filter by item or workspace stream id (repeatable or comma-separated)",l).option("--limit <n>","Return at most 1,000 events (default: 100)").option("--cursor-mode <mode>","Cursors: batch trailer (default) or per-row").option("--full","Include each complete authoritative history entry").option("--verify","Verify selected authoritative history chains").option("--provenance","Include patch-free author, harness, instance, and extensible provenance").option("--provenance-summary","Include bounded provenance completeness counts").option("--harness <value>","Filter by recorded or vocabulary-resolved harness (repeatable)",l).option("--agent-instance <value>","Filter by privacy-safe agent instance (repeatable)",l).option("--provenance-filter <dimension=value>","Filter by an exact declared provenance value (repeatable)",l).option("--follow","Follow committed events as NDJSON").option("--interval-ms <n>","Empty-read delay while following (minimum: 10ms; default: 250ms)").description("Read mutation events as NDJSON with resumable cursors.").action(je),t("activity")&&C(e.command("activity",{hidden:!0})),t("graph")&&e.command("graph").argument("<subcommand>","Graph query (ancestors, descendants, predecessors, successors, paths, impact, analyze, audit, communities, redundancy, dominators, slack, centrality, articulation, plan, index)").argument("[id]","Root item id (traversals, paths, impact, and dominators)").argument("[target]","Target item id (paths only)").option("--kind <value>","Restrict traversal to registered relationship kinds (repeatable or comma-separated)",l).option("--max-depth <value>","Maximum traversal depth (non-negative integer)").option("--limit <value>","Maximum returned rows per bounded collection").option("--after <value>","Resume a traversal after this previously returned node id").option("--direction <value>","Edge orientation for paths/impact (outgoing, incoming, or both)").option("--max-paths <value>","Maximum enumerated paths (paths only)").option("--sample <value>","Maximum evidence sample entries per audit finding (audit only)").option("--exempt-isolate <value>","Item ids treated as explicitly valid isolates by the audit (repeatable or comma-separated)",l).option("--exempt-isolate-type <value>","Item types whose active isolates are policy-valid for the audit (repeatable or comma-separated)",l).option("--save-baseline","Persist the audit census as the change-since-baseline comparison point (audit only)").option("--rebuild","Rebuild and warm the durable graph index (index only)").option("--clear","Delete the durable graph index (index only)").option("--summary","Return counts-first envelopes without row collections").option("--full","Return the complete graph row projection").description("Bounded workspace relationship-graph queries, analytics, and governance audit.").action(Oe)}const Ze={resolveReadCommandOutputFormat:k,parseListFormat:j};export{Ze as _testOnlyRegisterListQuery,Ye as registerListQueryCommands};
1
+ import{EXIT_CODE as m,PmCliError as f,readSettings as q,renderRowsAsCsv as L,renderRowsAsTable as $,resolvePmRoot as G}from"../sdk/runtime-primitives.js";import{renderPmCommandAliasMigrationHint as B,resolvePmCommandAlias as M}from"../sdk/cli-contracts.js";import{EVAL_QUERY_SET_SCHEMA_ID as N}from"../sdk/eval.js";import{applyContextIntentProjection as F}from"../sdk/context-intent-contracts.js";import{renderPmClosedDomainHelp as b}from"../sdk/agent/closed-domain-contracts.js";import{serializeNdjsonRows as A,serializeNdjsonStream as I}from"../sdk/output.js";import{listMutationEvents as T,subscribeMutationEventBatches as U,subscribeMutationEvents as P}from"../sdk/mutation-events.js";import{registerHistoryActivityCommand as C}from"./register-history-activity.js";import{registerHistoryMaintenanceCommands as z}from"./register-history-maintenance.js";import{runAggregate as H}from"./commands/query/aggregate.js";import{renderContextMarkdown as J,runContext as Q,resolveContextOutputFormat as V}from"./commands/query/context.js";import{runEval as K}from"./commands/query/eval.js";import{runGet as W}from"./commands/query/get.js";import{runGraph as X}from"./commands/query/graph.js";import{runHistory as Y}from"./commands/history/history.js";import{runList as Z}from"./commands/query/list.js";import{LIST_COMMAND_DEFAULT_PROJECTIONS as ee}from"../sdk/query/list.js";import{renderNextMarkdown as te,runNext as ne,resolveNextOutputFormat as oe}from"./commands/query/next.js";import{runSearch as ie}from"./commands/query/search.js";import{addHiddenOption as s,collect as l,getGlobalOptions as h,normalizeAggregateOptions as ae,normalizeContextOptions as re,normalizeListOptions as se,normalizeNextOptions as le,normalizeSearchKeywordsInput as de,normalizeSearchOptions as ue,printError as p,printListJsonStream as ce,printResult as y,setActiveCommandResult as S,writeStdout as v}from"./registration-helpers.js";function pe(e,i){return!i||i.size===0?!0:e==="context"?i.has("context")||i.has("ctx"):i.has(e)}function O(e){return new f(`List --format must be one of ${e?"json":"csv|table|json|ndjson|toon"}`,m.USAGE,{field:"format"})}function j(e,i=!1){if(e===void 0)return;if(typeof e!="string")throw O(i);const t=e.trim().toLowerCase();if(t==="csv"||t==="table"||t==="json"||t==="ndjson"||t==="toon")return t;throw O(i)}function k(e,i,t,n=!1){if(i===void 0)return t;if(typeof i!="string")throw new f(`${e} --format must be one of ${n?"json|ndjson|toon":"json|toon"}`,m.USAGE);const a=i.trim().toLowerCase();if(a!=="json"&&(a!=="ndjson"||!n)&&a!=="toon")throw new f(`${e} --format must be one of ${n?"json|ndjson|toon":"json|toon"}`,m.USAGE);if(t.json===!0&&a==="toon")throw new f(`${e} cannot combine --json with --format toon`,m.USAGE);return{...t,json:a==="json"||a==="ndjson"}}function me(e,i){ee[i]==="brief"&&e.includeBody!==!0&&e.compact!==!0&&e.brief!==!0&&e.full!==!0&&e.fields===void 0&&(e.brief=!0)}function E(e){e.option("--has-notes","Show only items that have notes").option("--has-learnings","Show only items that have learnings").option("--has-files","Show only items that have linked files").option("--has-docs","Show only items that have linked docs").option("--has-tests","Show only items that have linked tests").option("--has-comments","Show only items that have comments").option("--has-deps","Show only items that have dependencies").option("--has-body","Show only items that have a non-empty body").option("--has-linked-command","Show only items whose linked tests carry a runnable command").option("--no-notes","Show only items that have no notes").option("--no-learnings","Show only items that have no learnings").option("--no-files","Show only items that have no linked files").option("--filter-files-missing","Alias for --no-files").option("--no-docs","Show only items that have no linked docs").option("--filter-docs-missing","Alias for --no-docs").option("--no-tests","Show only items that have no linked tests").option("--no-comments","Show only items that have no comments").option("--no-deps","Show only items that have no dependencies").option("--empty-body","Show only items with an empty body").option("--no-linked-command","Show only items whose linked tests carry no runnable command").option("--filter-reviewer-missing","Show only items missing reviewer").option("--filter-risk-missing","Show only items missing risk").option("--filter-confidence-missing","Show only items missing confidence").option("--filter-sprint-missing","Show only items missing sprint").option("--filter-release-missing","Show only items missing release")}const fe={draft:{name:"list-draft",dependencyBlocked:!1},open:{name:"list-open",dependencyBlocked:!1},in_progress:{name:"list-in-progress",dependencyBlocked:!1},blocked:{name:"list-blocked",dependencyBlocked:!0},closed:{name:"list-closed",dependencyBlocked:!1},canceled:{name:"list-canceled",dependencyBlocked:!1}};function he(e,i){const t=e.stream===!0,n=j(e.format,t),a=n==="csv"||n==="table",o=n==="json"||n==="ndjson"||n==="toon"?k("List",e.format,i,!0):i;if(t&&!o.json)throw new f("--stream requires --json output mode.",m.USAGE);if((a||n==="ndjson")&&t)throw new f("--format csv|table|ndjson cannot be combined with --stream.",m.USAGE);return{streamMode:t,listFormat:n,effectiveGlobal:o}}function ye(e,i,t){if(t.listFormat==="csv"||t.listFormat==="table"){S(i);const n=i.items,a=t.listFormat==="csv"?L(n):$(n);!t.effectiveGlobal.quiet&&a.length>0&&v(`${a}
2
+ `)}else if(t.listFormat==="ndjson"){S(i);const n=A(i.items);!t.effectiveGlobal.quiet&&n.length>0&&v(`${n}
3
+ `)}else t.streamMode?ce(e,i,t.effectiveGlobal):y(i,t.effectiveGlobal)}function _(e,i,t,n=[]){if(t.outputBudget===void 0)return F(e,i,n);const{outputBudget:a,...o}=F(e,{...i,outputBudget:t.outputBudget},n);return o}async function ve(e){const i=h(e.actionCommand),t=e.aliasContract?{...i,command:e.aliasContract.canonical}:i,n=Date.now();e.aliasContract?.lifecycle==="deprecated"&&await q(G(process.cwd(),t.path)).then(D=>D.ux.deprecation_hints)&&p(B(e.aliasContract));const a=_("list",e.options,t),o=se(a),r=ge(e,o),{effectiveName:d,effectiveStatus:u,effectiveDependencyBlocked:c,effectiveExcludeTerminal:w}=r;me(o,e.name),Object.assign(o,{projectionCommand:d}),w&&(o.excludeTerminal=!0),o.dependencyBlocked=c;const x=he(a,t),R=await Z(c?void 0:u,o,t);ye("list",R,x),t.profile&&p(`profile:command=list took_ms=${Date.now()-n}`)}function ge(e,i){let t=e.name,n=e.status,a=e.dependencyBlocked===!0,o=e.excludeTerminal===!0;const r=i.status?.trim().toLowerCase(),d=e.name==="list"&&r!==void 0?fe[r]:void 0;return e.name==="list"&&(e.options.all===!0||r==="all"?(t="list-all",o=!1,i.status=void 0):r!==void 0&&d!==void 0&&(t=d.name,n=r,a=d.dependencyBlocked,o=!1,i.status=void 0)),(t==="list-open"||t==="list-in-progress")&&(i.lifecycleBucket=t==="list-open"?"open":"in_progress",n=void 0),{effectiveName:t,effectiveStatus:n,effectiveDependencyBlocked:a,effectiveExcludeTerminal:o}}function be(e,i){const{name:t,description:n,status:a,excludeTerminal:o,allowStatusFilter:r,dependencyBlocked:d,aliasContract:u}=i,c=e.command(t,{hidden:u?.hidden===!0}).description(n);r&&c.option("--status <value>","Filter by status (repeatable or comma-separated; matches any; all selects every status)",l),t==="list"&&c.option("--all","Include every lifecycle status"),c.option("--for <intent>",`Apply a declared context intent projection. ${b("list","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--type <value>","Filter by item type (repeatable or comma-separated; matches any)",l).option("--tag <value>","Filter by tag (repeatable or comma-separated; matches any)",l).option("--priority <value>","Filter by priority (repeatable or comma-separated; matches any)",l).option("--deadline-before <value>","Filter by deadline upper bound (ISO/date string or relative)").option("--deadline-after <value>","Filter by deadline lower bound (ISO/date string or relative)").option("--today","Filter to items updated since local midnight today").option("--recent","Filter to items updated in the last 7 days").option("--updated-after <value>","Updated since ISO timestamp or signed relative (-2h/-7d for past); use last-window ISO").option("--updated-before <value>","Filter by updated_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-after <value>","Filter by created_at lower bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-before <value>","Filter by created_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--ids <value>","Filter by explicit item IDs (comma-separated or repeatable)").option("--assignee <value>","Filter by assignee",l).option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--parent <value>","Filter by parent item ID").option("--sprint <value>","Filter by sprint",l).option("--release <value>","Filter by release",l).option("--filter-ac-missing","Show only items missing acceptance_criteria").option("--filter-estimates-missing","Show only items missing estimated_minutes").option("--filter-resolution-missing","Show only terminal items missing resolution").option("--filter-metadata-missing","Show only items missing any tracked metadata (AC, estimate, or resolution)").option("--limit <n>","Alias for --output-limit; --output-budget may cap rows").option("--offset <n>","Skip the first n matching rows before limit is applied").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor").option("--no-truncate","Disable default token cap; explicit --limit and --output-budget apply").option("--include-body","Include item body in each returned list row").option("--strict-read","Fail closed if any item document or item directory cannot be read").option("--compact","Render compact list projection fields (mutually exclusive with --brief/--full/--fields)").option("--brief","Brief rows: id, status, type, title and leading sort field (priority by default; excludes --compact/--full/--fields)").option("--full","Render full list projection fields (mutually exclusive with --compact/--brief/--fields)").option("--fields <value>",`Render custom comma-separated list fields (mutually exclusive with --compact/--brief/--full). ${b(t,"--fields")}`).option("--sort <value>","Sort field: priority|deadline|updated_at|created_at|title|parent (aliases: updated, created)").option("--order <value>","Sort order: asc|desc (requires --sort)").option("--tree","Render rows in parent/child tree order").option("--tree-depth <n>","Maximum recursion depth with --tree (0 keeps root rows only)").option("--format <value>","Output render mode: csv|table (human export) or json|ndjson|toon (machine output override)").option("--stream","Emit line-delimited JSON rows (requires --json)"),E(c),c.action(async(w,x)=>{await ve({name:t,status:a,excludeTerminal:o,dependencyBlocked:d,options:w,actionCommand:x,aliasContract:u})}),s(c,"--tags <value>","Alias for --tag"),s(c,"--assignee_filter <value>","Alias for --assignee-filter"),s(c,"--tree_depth <n>","Alias for --tree-depth"),s(c,"--token_budget <n>","Alias for --token-budget"),s(c,"--filter-estimate-missing","Alias for --filter-estimates-missing")}async function we(e,i){const t=h(i),n=Date.now(),a=await H(ae(e),t);y(a,t),t.profile&&p(`profile:command=aggregate took_ms=${Date.now()-n}`)}async function xe(e,i){const t=h(i),n=Date.now(),a=re(_("context",e,t)),o=await Q(a,t),r=V(a,t);if(r==="markdown")t.quiet||v(`${J(o)}
4
+ `);else if(r==="ndjson"){S(o);const d=A([...o.high_level,...o.low_level,...o.blocked_fallback]);!t.quiet&&d.length>0&&v(`${d}
5
+ `);const u=o.activity_history_read;u!==void 0&&p(`[pm] warning: activity_history_read reason=${u.reason} streams_read=${u.streams_read}/${u.streams_total}`)}else y(o,{...t,json:r==="json"});t.profile&&p(`profile:command=context took_ms=${Date.now()-n}`)}async function ke(e,i){const t=h(i),n=Date.now(),a=le(_("next",e,t)),o=await ne(a,t),r=oe(a,t);r==="markdown"?t.quiet||v(`${te(o)}
6
+ `):y(o,{...t,json:r==="json"}),t.profile&&p(`profile:command=next took_ms=${Date.now()-n}`)}async function Se(e,i,t){const n=h(t),a=Date.now(),o=de(e),r=_("search",i,n,[o]),d=ue(r),u=await ie(o,d,n),c=typeof r.format=="string"?r.format.trim().toLowerCase():void 0,w=k("Search",r.format,n,!0);if(c==="ndjson"){S(u);const x=A(u.items);!w.quiet&&x.length>0&&v(`${x}
7
+ `)}else y(u,w);n.profile&&p(`profile:command=search took_ms=${Date.now()-a}`)}async function _e(e,i){const t=h(i),n=Date.now(),a=await K({mode:typeof e.mode=="string"?e.mode:void 0,k:typeof e.k=="string"?e.k:void 0,failUnder:typeof e.failUnder=="string"?e.failUnder:void 0,queries:typeof e.queries=="string"?e.queries:void 0,format:typeof e.format=="string"?e.format:void 0},t);if(y(a,k("Eval",e.format,t)),t.profile&&p(`profile:command=eval took_ms=${Date.now()-n}`),!a.passed)throw new f("Eval gate failed: one or more aggregate or per-query thresholds were not met; inspect the metric report",m.GENERIC_FAILURE)}async function Ae(e,i,t){const n=h(t),a=Date.now(),o=_("get",i,n,[e]),r=await W(e,n,{depth:typeof o.depth=="string"?o.depth:void 0,fields:typeof o.fields=="string"?o.fields:void 0,full:!!o.full,tree:o.tree===!0,treeDepth:typeof o.treeDepth=="string"?o.treeDepth:typeof o.tree_depth=="string"?o.tree_depth:void 0,at:typeof o.at=="string"?o.at:void 0});y(r,k("Get",o.format,n)),n.profile&&p(`profile:command=get took_ms=${Date.now()-a}`)}async function Fe(e,i,t){const n=h(t),a=Date.now();if([i.compact,i.raw,i.full,i.provenance].filter(u=>u===!0).length>1)throw new f("History projection options are mutually exclusive. Use --compact, --provenance, or --full.",m.USAGE);const o=typeof i.field=="string"?i.field:void 0,r=!!i.strictExit||!!i.failOnWarn;if(r&&!i.verify)throw new f("--strict-exit requires --verify (it gates on the verification result).",m.USAGE);const d=await Y(e,{limit:typeof i.limit=="string"?i.limit:void 0,order:i.order,compact:!(i.full===!0||i.provenance===!0),provenance:i.provenance===!0,provenanceSummary:i.provenanceSummary===!0,harness:g(i,"harness"),agentInstance:g(i,"agentInstance"),provenanceFilter:g(i,"provenanceFilter"),diff:!!i.diff||o!==void 0,field:o,verify:!!i.verify},n);y(d,k("History",i.format,n)),r&&d.verification&&!d.verification.ok&&(process.exitCode=m.GENERIC_FAILURE),n.profile&&p(`profile:command=history took_ms=${Date.now()-a}`)}function g(e,i){const t=e[i];return Array.isArray(t)?t:void 0}function Ie(e,i){const t=g(e,"harness"),n=g(e,"agentInstance"),a=g(e,"provenanceFilter"),o=typeof e.cursorMode=="string"?e.cursorMode:void 0;if(o!==void 0&&o!=="batch"&&o!=="row")throw new f("Events --cursor-mode must be batch or row.",m.USAGE,{code:"invalid_event_cursor_mode"});const r=o;return{pmRoot:i,since:typeof e.since=="string"?e.since:void 0,type:g(e,"type"),author:g(e,"author"),item:g(e,"item"),limit:typeof e.limit=="string"?Number(e.limit):void 0,full:e.full===!0,...e.verify===!0?{verify:!0}:{},...e.provenance===!0?{provenance:!0}:{},...e.provenanceSummary===!0?{provenanceSummary:!0}:{},...t===void 0?{}:{harness:t},...n===void 0?{}:{agentInstance:n},...a===void 0?{}:{provenanceFilter:a},cursorMode:r}}async function Ce(e,i,t){if(i.provenanceSummary===!0)throw new f("Events --provenance-summary is bounded to one page and cannot be combined with --follow.",m.USAGE);const n=typeof i.intervalMs=="string"?Number(i.intervalMs):void 0;if(e.cursorMode==="row"){for await(const a of P({...e,intervalMs:n}))t||v(`${JSON.stringify(a)}
8
+ `);return}for await(const a of U({...e,intervalMs:n}))t||v(`${I(a.events,{count:a.count,has_more:a.has_more,next_cursor:a.next_cursor??null,source:a.source,integrity:a.integrity,...a.verified_streams===void 0?{}:{verified_streams:a.verified_streams},heartbeat:a.count===0})}
9
+ `)}function Oe(e){return e.cursor_mode==="row"?A(e.events):I(e.events,{count:e.count,has_more:e.has_more,next_cursor:e.next_cursor??null,source:e.source,integrity:e.integrity,...e.verified_streams===void 0?{}:{verified_streams:e.verified_streams},...e.provenance_summary===void 0?{}:{provenance_summary:e.provenance_summary}})}async function je(e,i){const t=h(i),n=Date.now(),a=Ie(e,t.path);if(e.follow===!0){await Ce(a,e,t.quiet===!0);return}const o=await T(a);if(S(o),t.json){y(o,t),t.profile&&p(`profile:command=events took_ms=${Date.now()-n}`);return}const r=Oe(o);!t.quiet&&r.length>0&&v(`${r}
10
+ `),t.profile&&p(`profile:command=events took_ms=${Date.now()-n}`)}async function Ee(e,i,t,n,a){const o=h(a),r=Date.now(),d=await X(e,i,t,{...Array.isArray(n.kind)?{kind:n.kind}:{},maxDepth:typeof n.maxDepth=="string"?n.maxDepth:void 0,limit:typeof n.limit=="string"?n.limit:void 0,after:typeof n.after=="string"?n.after:void 0,direction:typeof n.direction=="string"?n.direction:void 0,maxPaths:typeof n.maxPaths=="string"?n.maxPaths:void 0,sample:typeof n.sample=="string"?n.sample:void 0,...Array.isArray(n.exemptIsolate)?{exemptIsolate:n.exemptIsolate}:{},...Array.isArray(n.exemptIsolateType)?{exemptIsolateType:n.exemptIsolateType}:{},saveBaseline:n.saveBaseline===!0,rebuild:n.rebuild===!0,clear:n.clear===!0,summary:n.summary===!0,full:n.full===!0},o);y(d,o),o.profile&&p(`profile:command=graph took_ms=${Date.now()-r}`)}function Ze(e,i){const t=i?.commandFilter,n=o=>pe(o,t),a=[{name:"list",description:"List active items with optional lifecycle-status and project filters.",excludeTerminal:!0,allowStatusFilter:!0},{name:"list-all",description:"List all items with optional filters.",excludeTerminal:!1,allowStatusFilter:!0},{name:"list-draft",description:"List draft items with optional filters.",status:"draft"},{name:"list-open",description:"List open items with optional filters.",status:"open",excludeTerminal:!1,allowStatusFilter:!1},{name:"list-in-progress",description:"List in-progress items with optional filters.",status:"in_progress",excludeTerminal:!1,allowStatusFilter:!1},{name:"list-blocked",description:"List blocked items (blocked status or open blocked_by dependencies, matching pm next) with optional filters.",dependencyBlocked:!0,excludeTerminal:!1,allowStatusFilter:!1},{name:"list-closed",description:"List closed items with optional filters.",status:"closed"},{name:"list-canceled",description:"List canceled items with optional filters.",status:"canceled"}];for(const o of a)if(n(o.name)){const r=M(o.name);be(e,{...o,...r?.registration==="commander"?{aliasContract:r}:{}})}if(n("aggregate")){const o=e.command("aggregate").description("Group item counts and numeric measures.").option("--set-mode <value>","Set grouping: element (default)|tuple").option("--limit <value>","Group page size (default: 50)").option("--after <value>","Continue with next_after cursor").option("--group-by <value>","Fields: parent,type,priority,status,assignee,tags,sprint,release (comma-separated)").option("--count","Counts (default)").option("--completion","Status counts and completion_pct").option("--sum <field>","Group numeric sum").option("--avg <field>","Group numeric average").option("--include-unparented","Keep unparented group").option("--status <value>","Item status").option("--type <value>","Item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--deadline-before <value>","Latest deadline (ISO/date or relative)").option("--deadline-after <value>","Earliest deadline (ISO/date or relative)").option("--assignee <value>","Filter by assignee").option("--assignee-filter <value>","Assignee presence: assigned|unassigned").option("--parent <value>","Parent ID").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release");s(o,"--include_unparented","Alias for --include-unparented"),s(o,"--assignee_filter <value>","Alias for --assignee-filter"),o.action(we)}if(n("context")){const o=e.command("context").alias("ctx").description("Show a token-efficient project context snapshot for next-work decisions.").option("--for <intent>",`Apply a declared context intent projection. ${b("context","--for")}`).option("--date <value>","Anchor date/time for agenda window calculations (ISO/date string or relative)").option("--from <value>","Agenda lower bound (ISO/date string or relative)").option("--to <value>","Agenda upper bound (ISO/date string or relative)").option("--past","Include past agenda entries in bounded windows").option("--type <value>","Filter by item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--assignee <value>","Filter by assignee").option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release").option("--parent <id>","Scope the snapshot to one item's subtree (the item plus all descendants)").option("--limit <n>","Limit focus and agenda rows per section").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor").option("--format <value>","Context output format override: markdown|toon|json|ndjson").option("--depth <value>","Context depth: brief|standard|deep|full (full = every section, no per-section cap)").option("--section <value...>","Include specific sections (repeatable; overrides --depth)").option("--fields <value>","Project focus rows to a comma-separated field subset (e.g. id,title,priority)").option("--activity-limit <n>","Limit recent activity entries (default: settings or 10)").option("--stale-threshold <value>","Staleness cutoff in days (e.g. 7 or 7d; default: settings or 7)").option("--explain-ranking","Include the scorer model, per-signal contributions, and ranked candidate ids").option("--token-budget <n>","Complete JSON/TOON response token ceiling").option("--no-extension-health","Omit the installed extension health summary").option("--no-tags","Omit tag arrays from context focus rows");s(o,"--assignee_filter <value>","Alias for --assignee-filter"),s(o,"--max-items <n>","Alias for --limit"),s(o,"--explain_ranking","Alias for --explain-ranking"),s(o,"--token_budget <n>","Alias for --token-budget"),o.action(xe)}if(n("next")){const o=e.command("next").description("Recommend the next actionable (unblocked, ready) work item with rationale + blocked companion.").option("--for <intent>",`Apply a declared context intent projection. ${b("next","--for")}`).option("--type <value>","Filter candidate items by type").option("--tag <value>","Filter candidate items by tag").option("--priority <value>","Filter candidate items by priority").option("--assignee <value>","Filter candidate items by assignee").option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--sprint <value>","Filter candidate items by sprint").option("--release <value>","Filter candidate items by release").option("--parent <id>","Scope to one item's subtree (the item plus all descendants)").option("--limit <n>","Limit ready rows (default: 5; non-positive falls back to default)").option("--blocked-limit <n>","Limit blocked rows (default: same as --limit)").option("--ready-only","Omit the blocked companion list").option("--include-decisions","Include human-gated Decision items in the claimable ready queue").option("--include-gates","Include outcome gates in the ready queue").option("--include-containers","Include containers with unfinished descendants in the ready queue").option("--format <value>","Next output format override: markdown|toon|json").option("--explain-ranking","Include the scorer model, per-signal contributions, and ranked ready ids").option("--token-budget <n>","Maximum estimated tokens spent on the ranked ready queue");s(o,"--assignee_filter <value>","Alias for --assignee-filter"),s(o,"--blocked_limit <n>","Alias for --blocked-limit"),s(o,"--ready_only","Alias for --ready-only"),s(o,"--explain_ranking","Alias for --explain-ranking"),s(o,"--token_budget <n>","Alias for --token-budget"),o.action(ke)}if(n("search")){const o=e.command("search").argument("<keywords...>","Keyword query tokens").description("Search items with keyword, semantic, or hybrid retrieval. Inline field:value tokens (tag:/status:/type:/priority:) in the query are parsed as filters, e.g. 'auth tag:area:search status:open'.").option("--for <intent>",`Apply a declared context intent projection. ${b("search","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--mode <value>","Search mode: keyword|semantic|hybrid (default: auto)").option("--semantic","Shorthand for --mode semantic").option("--hybrid","Shorthand for --mode hybrid").option("--match-mode <value>","Token match mode: and|or|exact (default: or with all-terms ranking bonus; and = hard-require every token; exact = exact phrase)").option("--min-score <value>","Per-query minimum score threshold (finite number >= 0); overrides settings search.score_threshold for this query only").option("--count","Return only the count of matching items (post-filter/threshold, pre-limit); skips hit rows").option("--semantic-weight <value>","Override hybrid semantic weight for this query (0..1); invalid values fall back to settings").option("--include-linked","Include linked files, docs, and tests in the searchable corpus").option("--title-exact","Require exact normalized title match for the full query string").option("--phrase-exact","Require exact normalized phrase match in searchable text").option("--highlight","Emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit; off by default").option("--status <value>","Filter by status before query (all, open/closed/canceled aliases, or configured status id; CSV)").option("--type <value>","Filter by item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--deadline-before <value>","Filter by deadline upper bound (ISO/date string or relative)").option("--deadline-after <value>","Filter by deadline lower bound (ISO/date string or relative)").option("--updated-after <value>",'Filter by updated_at lower bound: ISO timestamp or signed relative (e.g. "-2h"/"-7d" for the past)').option("--updated-before <value>","Filter by updated_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-after <value>","Filter by created_at lower bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-before <value>","Filter by created_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--assignee <value>","Filter by assignee").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release").option("--parent <value>","Filter by parent item ID").option("--compact","Render compact search hits (default; mutually exclusive with --full/--fields)").option("--full","Render full search hits with nested item payloads (mutually exclusive with --compact/--fields)").option("--fields <value>",`Render custom comma-separated search hit fields (mutually exclusive with --compact/--full). ${b("search","--fields")}`).option("--format <value>","Search output format override: json|ndjson|toon").option("--limit <n>","Limit returned item count").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor");E(o),o.action(Se),s(o,"--tags <value>","Alias for --tag"),s(o,"--token_budget <n>","Alias for --token-budget")}if(n("eval")&&e.command("eval").description("Evaluate search relevance against a curated golden-query set: reports nDCG@k, MRR@k, precision@k, and recall@k per query plus the macro average. Use --fail-under as a CI gate.").option("--mode <value>","Default retrieval mode for queries without their own: keyword|semantic|hybrid (default: keyword)").option("--k <n>","Metric cutoff @k (positive integer; default: 10)").option("--fail-under <value>","Exit non-zero when aggregate nDCG@k falls below this threshold (0..1); CI gate").option("--queries <path>",`Query JSON (${N}); default: search/eval-queries.json; errors show an example`).option("--format <value>","Eval output format override: json|toon").action(_e),n("get")){const o=e.command("get").argument("<id>","Item id").option("--for <intent>",`Apply a declared context intent projection. ${b("get","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--depth <value>","brief|standard|deep|full (default: standard)").option("--full","Full details and children for any type; excludes --depth/--fields").option("--fields <value>",`Render custom comma-separated item metadata fields. ${b("get","--fields")}`).option("--tree","Include descendants rooted at the requested item").option("--tree-depth <n>","Maximum subtree depth for --tree descendants").option("--at <version-or-timestamp>","Reconstruct a verified historical item state without mutating it").option("--format <value>","Get output format override: json|toon").description("Show item details by ID.").action(Ae);s(o,"--tree_depth <n>","Alias for --tree-depth"),s(o,"--token_budget <n>","Alias for --token-budget")}if(n("history")){const o=e.command("history").enablePositionalOptions().argument("<id>","Item id").option("--limit <n>","Latest N; keeps order").option("--order <value>","oldest_first|newest_first").option("--compact","Summary (default newest_first)").option("--full","Patches (default oldest_first)").option("--provenance","Authors (default newest_first)").option("--provenance-summary","Count provenance completeness").option("--harness <value>","Harness (repeatable)",l).option("--agent-instance <value>","Instance (repeatable)",l).option("--provenance-filter <dimension=value>","Provenance (repeatable)",l).option("--diff","Before/after field diffs").option("--field <name>","Filter changed field; implies --diff").option("--verify","Verify full chain and replay").option("--strict-exit","With --verify, fail on integrity errors").option("--fail-on-warn","Alias for --strict-exit").option("--format <value>","Output: json|toon").description("Read history.").action(Fe);z(o,!0),C(o.command("activity"))}n("events")&&e.command("events").option("--since <cursor-or-timestamp>","Resume strictly after a durable cursor, or include events from an ISO timestamp").option("--type <value>","Filter by mutation operation (repeatable or comma-separated)",l).option("--author <value>","Filter by mutation author (repeatable or comma-separated)",l).option("--item <value>","Filter by item or workspace stream id (repeatable or comma-separated)",l).option("--limit <n>","Return at most 1,000 events (default: 100)").option("--cursor-mode <mode>","Cursors: batch trailer (default) or per-row").option("--full","Include each complete authoritative history entry").option("--verify","Verify selected authoritative history chains").option("--provenance","Include patch-free author, harness, instance, and extensible provenance").option("--provenance-summary","Include bounded provenance completeness counts").option("--harness <value>","Filter by recorded or vocabulary-resolved harness (repeatable)",l).option("--agent-instance <value>","Filter by privacy-safe agent instance (repeatable)",l).option("--provenance-filter <dimension=value>","Filter by an exact declared provenance value (repeatable)",l).option("--follow","Follow committed events as NDJSON").option("--interval-ms <n>","Empty-read delay while following (minimum: 10ms; default: 250ms)").description("Read mutation events as NDJSON with resumable cursors.").action(je),n("activity")&&C(e.command("activity",{hidden:!0})),n("graph")&&e.command("graph").argument("<subcommand>","Graph query (ancestors, descendants, predecessors, successors, paths, impact, analyze, audit, communities, redundancy, dominators, slack, centrality, articulation, plan, index)").argument("[id]","Root item id (traversals, paths, impact, and dominators)").argument("[target]","Target item id (paths only)").option("--kind <value>","Restrict traversal to registered relationship kinds (repeatable or comma-separated)",l).option("--max-depth <value>","Maximum traversal depth (non-negative integer)").option("--limit <value>","Maximum returned rows per bounded collection").option("--after <value>","Resume a traversal after this previously returned node id").option("--direction <value>","Edge orientation for paths/impact (outgoing, incoming, or both)").option("--max-paths <value>","Maximum enumerated paths (paths only)").option("--sample <value>","Maximum evidence sample entries per audit finding (audit only)").option("--exempt-isolate <value>","Item ids treated as explicitly valid isolates by the audit (repeatable or comma-separated)",l).option("--exempt-isolate-type <value>","Item types whose active isolates are policy-valid for the audit (repeatable or comma-separated)",l).option("--save-baseline","Persist the audit census as the change-since-baseline comparison point (audit only)").option("--rebuild","Rebuild and warm the durable graph index (index only)").option("--clear","Delete the durable graph index (index only)").option("--summary","Return counts-first envelopes without row collections").option("--full","Return the complete graph row projection").description("Bounded workspace relationship-graph queries, analytics, and governance audit.").action(Ee)}const et={resolveReadCommandOutputFormat:k,parseListFormat:j};export{et as _testOnlyRegisterListQuery,Ze as registerListQueryCommands};
11
11
  //# sourceMappingURL=register-list-query.js.map