@unbrained/pm-cli 2026.9.25 → 2026.9.27

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 (161) hide show
  1. package/.agents/skills/README.md +1 -0
  2. package/.agents/skills/pm-developer/SKILL.md +3 -0
  3. package/.agents/skills/pm-test-audit/LICENSE.txt +21 -0
  4. package/.agents/skills/pm-test-audit/SKILL.md +103 -0
  5. package/.agents/skills/pm-test-audit/references/AUDIT.md +54 -0
  6. package/.agents/skills/pm-test-audit/references/CAMPAIGN.md +47 -0
  7. package/.claude-plugin/marketplace.json +2 -2
  8. package/CHANGELOG.md +28 -1
  9. package/dist/cli/commander-usage.js +2 -2
  10. package/dist/cli/error-guidance.js +1 -1
  11. package/dist/cli/main.js +2 -2
  12. package/dist/cli/register-list-query.js +2 -2
  13. package/dist/cli/register-setup.js +1 -1
  14. package/dist/cli/runtime/selection.d.ts +3 -1
  15. package/dist/cli/runtime/selection.js +1 -1
  16. package/dist/cli/schema/registration.js +2 -2
  17. package/dist/cli-bundle/bundle-manifest.json +155 -147
  18. package/dist/cli-bundle/chunks/chunk-3BTJ66CB.js +238 -0
  19. package/dist/cli-bundle/chunks/{chunk-5AP67ZXH.js → chunk-4SLLCDFL.js} +39 -39
  20. package/dist/cli-bundle/chunks/{chunk-GAU55CWI.js → chunk-4UPZLUT2.js} +7 -7
  21. package/dist/cli-bundle/chunks/{chunk-25KTCTBL.js → chunk-6OJVQ7SW.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-445ARBKY.js → chunk-7TAGYNFP.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-GOWZEBTH.js → chunk-AUS6USO4.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-YDIGMRLZ.js → chunk-IEP3VAT5.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-3IB4THWX.js → chunk-JX6WCCHL.js} +6 -6
  26. package/dist/cli-bundle/chunks/chunk-LC6WEA5U.js +2 -0
  27. package/dist/cli-bundle/chunks/{chunk-CZ3VJJEA.js → chunk-LKGQUZ5M.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-P7ZSJOWH.js → chunk-OKVDVERQ.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-COFQCKF4.js → chunk-TSF2LPIH.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-YABJDOOX.js → chunk-V5UGBYHN.js} +3 -3
  31. package/dist/cli-bundle/chunks/{register-list-query-IZ7ZVTDE.js → register-list-query-6PAJ4PBU.js} +4 -4
  32. package/dist/cli-bundle/chunks/{register-mutation-IPAZTFDZ.js → register-mutation-RZCXZXYS.js} +4 -4
  33. package/dist/cli-bundle/chunks/{register-operations-APN33LNI.js → register-operations-GK6VU2H2.js} +2 -2
  34. package/dist/cli-bundle/chunks/register-setup-ASEMNMBF.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-KRIHJH5U.js → chunk-6J2YCGSN.js} +5 -5
  36. package/dist/cli-bundle/focused-chunks/{chunk-XKH2FC5D.js → chunk-6UNKK3UH.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-NRHTXBTI.js → chunk-DQ3MB7BO.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-PMPFLA6X.js → chunk-E7LYK7V5.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-GZD4ZYIB.js +20 -0
  40. package/dist/cli-bundle/focused-chunks/chunk-KMPKKSA6.js +2 -0
  41. package/dist/cli-bundle/focused-chunks/{chunk-TLF6N56J.js → chunk-LBDWUHQD.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-UIFVIE5F.js → chunk-MILJCOFJ.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-MK5AKKHK.js → chunk-NETVXIH5.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-Q355NPLH.js → chunk-NWRVNHAD.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-IXNNMP2R.js → chunk-NZAG7OKB.js} +12 -12
  46. package/dist/cli-bundle/focused-chunks/{chunk-OY3VHCTX.js → chunk-OJKJFDIG.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-OJRX6G22.js +2 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-NVVB2HJC.js → chunk-PDVL7QYU.js} +16 -16
  49. package/dist/cli-bundle/focused-chunks/{chunk-O7MIBEMK.js → chunk-QO4MTAEA.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-ABA3KRPY.js → chunk-SMADBUPL.js} +2 -2
  51. package/dist/cli-bundle/main.js +21 -21
  52. package/dist/cli-bundle/sdk-authoring.js +1 -1
  53. package/dist/cli-bundle/sdk-contracts.js +1 -1
  54. package/dist/cli-bundle/sdk-core.js +20 -20
  55. package/dist/cli-bundle/sdk-governance.js +1 -1
  56. package/dist/cli-bundle/sdk-graph.js +1 -1
  57. package/dist/cli-bundle/sdk-merge.js +46 -46
  58. package/dist/cli-bundle/sdk-query.js +1 -1
  59. package/dist/cli-bundle/sdk-runtime.js +1 -1
  60. package/dist/cli-bundle/sdk-testing.js +1 -1
  61. package/dist/cli-bundle/sdk.js +8 -8
  62. package/dist/core/search/embedding-batches.d.ts +47 -15
  63. package/dist/core/search/embedding-batches.js +1 -1
  64. package/dist/core/search/eval-thresholds.d.ts +14 -0
  65. package/dist/core/search/eval-thresholds.js +2 -0
  66. package/dist/core/search/eval.d.ts +4 -1
  67. package/dist/core/search/eval.js +1 -1
  68. package/dist/core/search/http-client.d.ts +7 -0
  69. package/dist/core/search/http-client.js +1 -1
  70. package/dist/sdk/agent-capability-contracts.js +1 -1
  71. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  72. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  73. package/dist/sdk/completion/shared.d.ts +1 -1
  74. package/dist/sdk/completion/shared.js +1 -1
  75. package/dist/sdk/eval.d.ts +19 -17
  76. package/dist/sdk/eval.js +1 -1
  77. package/dist/sdk/extension/static-inventory.d.ts +54 -0
  78. package/dist/sdk/extension/static-inventory.js +2 -0
  79. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  80. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  81. package/dist/sdk/governance/reindex.d.ts +4 -1
  82. package/dist/sdk/governance/reindex.js +2 -2
  83. package/dist/sdk/guide-topics.js +1 -1
  84. package/dist/sdk/index.d.ts +1 -0
  85. package/dist/sdk/index.js +1 -1
  86. package/dist/sdk/public-surface.json +1 -1
  87. package/dist/sdk/query/complete-list.js +1 -1
  88. package/dist/sdk/query.d.ts +3 -0
  89. package/dist/sdk/query.js +1 -1
  90. package/dist/sdk/read-output/provenance.d.ts +20 -0
  91. package/dist/sdk/read-output/provenance.js +2 -0
  92. package/dist/sdk/read-output-contracts.js +1 -1
  93. package/dist/sdk/runtime/schema-preview.d.ts +2 -0
  94. package/dist/sdk/runtime/schema-preview.js +2 -0
  95. package/dist/sdk/runtime/schema.js +1 -1
  96. package/dist/sdk/runtime-input.js +1 -1
  97. package/dist/sdk/runtime-primitives.d.ts +2 -1
  98. package/dist/sdk/runtime-primitives.js +1 -1
  99. package/docs/CLI_GRAMMAR.md +31 -0
  100. package/docs/CODEX_PLUGIN.md +8 -0
  101. package/docs/EXTENSION_LIFECYCLE.md +18 -0
  102. package/docs/README.md +1 -0
  103. package/docs/RELEASING.md +51 -2
  104. package/docs/SEARCH_QUALITY.md +116 -0
  105. package/docs/agent-task-token-baseline.json +4 -4
  106. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
  107. package/docs/generated/AGENT_COMMAND_SURFACE.md +5 -1
  108. package/docs/generated/FLAG_LEXICON_BUDGETS.md +4 -0
  109. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +14 -7
  110. package/marketplace.json +2 -2
  111. package/package.json +2 -2
  112. package/packages/pm-beads/package.json +1 -1
  113. package/packages/pm-calendar/package.json +1 -1
  114. package/packages/pm-command-kit/package.json +1 -1
  115. package/packages/pm-digital-twin/package.json +1 -1
  116. package/packages/pm-governance-audit/package.json +1 -1
  117. package/packages/pm-guide-shell/package.json +1 -1
  118. package/packages/pm-kanban/package.json +1 -1
  119. package/packages/pm-lifecycle-hooks/package.json +1 -1
  120. package/packages/pm-linked-test-adapters/package.json +1 -1
  121. package/packages/pm-search-advanced/package.json +1 -1
  122. package/packages/pm-templates/package.json +1 -1
  123. package/packages/pm-todos/package.json +1 -1
  124. package/packages/pm-vcs/package.json +1 -1
  125. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  126. package/plugins/pm-claude/README.md +5 -1
  127. package/plugins/pm-claude/package.json +2 -2
  128. package/plugins/pm-claude/skills/pm-audit/SKILL.md +14 -103
  129. package/plugins/pm-claude/skills/pm-audit/agents/openai.yaml +4 -0
  130. package/plugins/pm-claude/skills/pm-developer/SKILL.md +20 -143
  131. package/plugins/pm-claude/skills/pm-developer/agents/openai.yaml +4 -0
  132. package/plugins/pm-claude/skills/pm-planner/SKILL.md +16 -167
  133. package/plugins/pm-claude/skills/pm-planner/agents/openai.yaml +4 -0
  134. package/plugins/pm-claude/skills/pm-release/SKILL.md +18 -102
  135. package/plugins/pm-claude/skills/pm-release/agents/openai.yaml +4 -0
  136. package/plugins/pm-claude/skills/pm-workflow/SKILL.md +25 -156
  137. package/plugins/pm-claude/skills/pm-workflow/agents/openai.yaml +4 -0
  138. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  139. package/plugins/pm-codex/README.md +10 -2
  140. package/plugins/pm-codex/mcp.json +11 -0
  141. package/plugins/pm-codex/package.json +2 -2
  142. package/plugins/pm-codex/plugin.json +45 -0
  143. package/plugins/pm-codex/skills/pm-audit/SKILL.md +21 -0
  144. package/plugins/pm-codex/skills/pm-audit/agents/openai.yaml +4 -0
  145. package/plugins/pm-codex/skills/pm-auditor/SKILL.md +5 -40
  146. package/plugins/pm-codex/skills/pm-auditor/agents/openai.yaml +3 -5
  147. package/plugins/pm-codex/skills/pm-developer/SKILL.md +26 -0
  148. package/plugins/pm-codex/skills/pm-developer/agents/openai.yaml +4 -0
  149. package/plugins/pm-codex/skills/pm-native/SKILL.md +7 -87
  150. package/plugins/pm-codex/skills/pm-native/agents/openai.yaml +3 -5
  151. package/plugins/pm-codex/skills/pm-planner/SKILL.md +22 -0
  152. package/plugins/pm-codex/skills/pm-planner/agents/openai.yaml +4 -0
  153. package/plugins/pm-codex/skills/pm-release/SKILL.md +17 -38
  154. package/plugins/pm-codex/skills/pm-release/agents/openai.yaml +2 -4
  155. package/plugins/pm-codex/skills/pm-workflow/SKILL.md +39 -0
  156. package/plugins/pm-codex/skills/pm-workflow/agents/openai.yaml +4 -0
  157. package/dist/cli-bundle/chunks/chunk-JDHWZYZU.js +0 -238
  158. package/dist/cli-bundle/chunks/register-setup-HPHIKG5U.js +0 -2
  159. package/dist/cli-bundle/focused-chunks/chunk-HQPTDJLF.js +0 -2
  160. package/dist/cli-bundle/focused-chunks/chunk-V2X37U6J.js +0 -2
  161. package/dist/cli-bundle/focused-chunks/chunk-Y2M4QLAA.js +0 -20
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d13df07a-5c72-56b8-84d9-b1464f7dbe0e")}catch(e2){}})();import{resolveRecoveryCommandName}from"../sdk/agent/command-recovery.js";import{projectPmDiagnosticOutput,projectPmDiagnosticText}from"../sdk/cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./argv-utils.js";import{discoverNearbyPmRoot}from"../sdk/tracker-root-discovery.js";import{stripGlobalBootstrapTokens}from"../sdk/cli-bootstrap.js";import{resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";function projectLeanErrorEnvelope(envelope){const{why:_why,title:_title,...actionable}=envelope;return actionable}const STRUCTURED_WHY_SUPPRESSION_CODES=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function includeWhyInStructuredGuidance(message){if(!message.why){return false}if(message.recovery?.recovery_mode==="compact"){return false}return!STRUCTURED_WHY_SUPPRESSION_CODES.has(message.code)}function errorType(code){return`urn:pm-cli:error:${code}`}function makeGuidanceMessage(params){return{...params,type:errorType(params.code)}}const GUIDE_SHELL_HINT={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"};const CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"};const SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"};const GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"};const KNOWN_PACKAGE_COMMAND_HINTS={guide:GUIDE_SHELL_HINT,shell:GUIDE_SHELL_HINT,completion:GUIDE_SHELL_HINT,"completion-statuses":GUIDE_SHELL_HINT,"completion-tags":GUIDE_SHELL_HINT,"completion-types":GUIDE_SHELL_HINT,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:CALENDAR_HINT,cal:CALENDAR_HINT,reindex:SEARCH_ADVANCED_HINT,"search-advanced":SEARCH_ADVANCED_HINT,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":GOVERNANCE_AUDIT_HINT,"dedupe-audit":GOVERNANCE_AUDIT_HINT,"dedupe-merge":GOVERNANCE_AUDIT_HINT,normalize:GOVERNANCE_AUDIT_HINT};function resolveKnownPackageCommandHint(commandToken){const primary=commandToken.trim().split(/\s+/)[0]?.toLowerCase();if(!primary){return void 0}return KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){if(entries.length===0){return[]}return[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values)){return void 0}const normalized=values.filter(entry=>typeof entry==="string").map(entry=>entry.trim()).filter(entry=>entry.length>0);return normalized.length>0?normalized:void 0}function normalizeRecoveryCandidates(candidates){if(!Array.isArray(candidates)){return void 0}const normalized=candidates.map(entry=>({source:typeof entry?.source==="string"?entry.source.trim():"",command:typeof entry?.command==="string"?entry.command.trim():"",reason:typeof entry?.reason==="string"?entry.reason.trim():""})).filter(entry=>entry.source.length>0&&entry.command.length>0&&entry.reason.length>0);return normalized.length>0?normalized:void 0}function assignRecoveryString(normalized,key,value){if(typeof value==="string"&&value.trim().length>0){normalized[key]=value.trim()}}function assignRecoveryCollection(normalized,key,value){if(key==="parsed_positionals"){if(!Array.isArray(value))return;const parsedPositionals=value.map(entry=>({role:typeof entry?.role==="string"?entry.role.trim():"",value:typeof entry?.value==="string"?entry.value.trim():""})).filter(entry=>entry.role.length>0&&entry.value.length>0);if(parsedPositionals.length>0){normalized.parsed_positionals=parsedPositionals}return}const values=normalizeStringArray(value);if(values){normalized[key]=values}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!=="object"){return void 0}const normalized={};if(payload.recovery_mode==="compact"){normalized.recovery_mode="compact"}assignRecoveryString(normalized,"attempted_command",payload.attempted_command);assignRecoveryCollection(normalized,"normalized_args",payload.normalized_args);assignRecoveryCollection(normalized,"parsed_positionals",payload.parsed_positionals);assignRecoveryCollection(normalized,"provided_fields",payload.provided_fields);assignRecoveryCollection(normalized,"missing",payload.missing);assignRecoveryCollection(normalized,"missing_required_fields",payload.missing_required_fields);assignRecoveryCollection(normalized,"suggested_flags",payload.suggested_flags);assignRecoveryCollection(normalized,"allowed_values",payload.allowed_values);assignRecoveryCollection(normalized,"candidate_commands",payload.candidate_commands);if(typeof payload.candidate_commands_total==="number"&&Number.isSafeInteger(payload.candidate_commands_total)&&payload.candidate_commands_total>=0){normalized.candidate_commands_total=payload.candidate_commands_total}if(payload.candidate_commands_truncated===true){normalized.candidate_commands_truncated=true}if(payload.option_scope==="declared_on_path"||payload.option_scope==="declared_elsewhere"||payload.option_scope==="declared_nowhere"){normalized.option_scope=payload.option_scope}assignRecoveryString(normalized,"suggested_retry",payload.suggested_retry);assignRecoveryCollection(normalized,"suggested_retry_args",payload.suggested_retry_args);if(typeof payload.retry_after_ms==="number"&&Number.isSafeInteger(payload.retry_after_ms)&&payload.retry_after_ms>=0){normalized.retry_after_ms=payload.retry_after_ms}const fallbackCandidates=normalizeRecoveryCandidates(payload.fallback_candidates);if(fallbackCandidates){normalized.fallback_candidates=fallbackCandidates}assignRecoveryString(normalized,"next_best_command",payload.next_best_command);return Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){if(value){lines.push(` ${label}: ${value}`)}}function appendRecoveryListLine(lines,label,values,separator){if(values&&values.length>0){lines.push(` ${label}: ${values.join(separator)}`)}}function renderRecoveryBundle(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized){return[]}const lines=["Recovery bundle:"];appendRecoveryTextLine(lines,"suggested_retry",normalized.suggested_retry);appendRecoveryTextLine(lines,"attempted_command",normalized.attempted_command);appendRecoveryListLine(lines,"normalized_args",normalized.attempted_command?void 0:normalized.normalized_args," ");if(normalized.parsed_positionals&&normalized.parsed_positionals.length>0){lines.push(" parsed_positionals:");for(const positional of normalized.parsed_positionals){lines.push(` - ${positional.role}: ${positional.value}`)}}appendRecoveryListLine(lines,"provided_fields",normalized.provided_fields,", ");appendRecoveryListLine(lines,"missing",normalized.missing,", ");appendRecoveryListLine(lines,"missing_required_fields",normalized.missing_required_fields,", ");appendRecoveryListLine(lines,"suggested_flags",normalized.suggested_flags,", ");appendRecoveryListLine(lines,"allowed_values",normalized.allowed_values,", ");appendRecoveryListLine(lines,"candidate_commands",normalized.candidate_commands,", ");if(typeof normalized.candidate_commands_total==="number"){lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`)}if(normalized.candidate_commands_truncated===true){lines.push(" candidate_commands_truncated: true")}if(normalized.option_scope!==void 0){lines.push(` option_scope: ${normalized.option_scope}`)}if(typeof normalized.retry_after_ms==="number"){lines.push(` retry_after_ms: ${normalized.retry_after_ms}`)}appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command);if(normalized.fallback_candidates&&normalized.fallback_candidates.length>0){lines.push(" fallback_candidates:");for(const candidate of normalized.fallback_candidates){lines.push(` - ${candidate.source}: ${candidate.command} (${candidate.reason})`)}}return lines}function renderGuidanceMessage(message){const lines=[`Error: ${message.title}`,"","What is required:",` ${message.required}`];if(message.nextSteps&&message.nextSteps.length>0){lines.push("");lines.push(...renderList("Next steps:",message.nextSteps))}lines.push("","What happened:",` ${message.happened}`);if(message.why){lines.push("","Why:");lines.push(` ${message.why}`)}if(message.examples&&message.examples.length>0){lines.push("");lines.push(...renderList("Examples:",message.examples))}if(message.verificationErrors&&message.verificationErrors.length>0){lines.push("");lines.push(...renderList("Verification errors:",message.verificationErrors))}const recoveryLines=renderRecoveryBundle(message.recovery);if(recoveryLines.length>0){lines.push("");lines.push(...recoveryLines)}return lines.join("\n")}function attachStructuredGuidanceDetails(payload,message){if(message.tombstone!==void 0){payload.tombstone=message.tombstone;payload.item_id=message.itemId}if(includeWhyInStructuredGuidance(message)){payload.why=message.why}if(message.examples&&message.examples.length>0){payload.examples=message.examples}if(message.nextSteps&&message.nextSteps.length>0){payload.next_steps=message.nextSteps}if(message.verificationErrors&&message.verificationErrors.length>0){payload.verification_errors=message.verificationErrors}if(message.flag!==void 0)payload.flag=message.flag;if(message.value!==void 0)payload.value=message.value;if(message.unmatchedSelectors!==void 0)payload.unmatched_selectors=message.unmatchedSelectors;if(message.availableDependencies!==void 0)payload.available_dependencies=message.availableDependencies;if(message.recovery){payload.recovery=message.recovery}return payload}function resolveRefusalCandidateFlag(message,normalizedArgs){if(message.flag)return message.flag;const isAdmissibleCandidate=flag=>{const canonicalFlag=flag.split("=",1)[0];return stripGlobalBootstrapTokens([canonicalFlag]).length>0&&!["--help","--no-changed-fields","--version"].includes(canonicalFlag)&&normalizedArgs.some(argument=>argument===canonicalFlag||argument.startsWith(`${canonicalFlag}=`))};const mentionedFlag=[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag));if(mentionedFlag)return mentionedFlag;return message.recovery?.provided_fields?.map(field=>field.split("=",1)[0]).find(field=>isAdmissibleCandidate(field))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(candidateFlag){const candidateArgument=normalizedArgs.find(argument=>argument===candidateFlag||argument.startsWith(`${candidateFlag}=`));if(candidateArgument?.startsWith(`${candidateFlag}=`)){return candidateArgument.slice(candidateFlag.length+1)}const candidateIndex=normalizedArgs.indexOf(candidateFlag);return candidateIndex>=0?normalizedArgs[candidateIndex+1]:void 0}const allowedValues=message.recovery?.allowed_values;if(!allowedValues?.length)return void 0;return normalizedArgs.find((argument,index)=>index>0&&!argument.startsWith("-")&&!allowedValues.includes(argument))}function buildRefusalEnvelope(message,exitCode){if(message.policyViolations?.length){return{surface:`policy:${message.policyViolations.map(policy=>policy.policy_id).join(",")}`,policies:message.policyViolations,policy_violation_count:message.policyViolationCount,missing_fields:[...new Set(message.policyViolations.flatMap(policy=>policy.missing_fields))],exit_code:exitCode}}const normalizedArgs=message.recovery?.normalized_args??[];const candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs);const rejectedValue=resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag);return{surface:candidateFlag??message.recovery?.missing?.[0]??inferCommandNameFromRecovery(message.recovery)??"command",...rejectedValue!==void 0?{rejected_value:rejectedValue}:{},...message.recovery?.allowed_values?.length?{legal_domain:message.recovery.allowed_values}:{},exit_code:exitCode}}function guidanceToJsonEnvelope(message,exitCode){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,exit_code:exitCode,refusal:buildRefusalEnvelope(message,exitCode)},message)}function projectJsonErrorGuidance(guidance,exitCode){const recovery=guidance.recovery;const hasActionableRecovery=Boolean(recovery?.suggested_retry)||Boolean(recovery?.suggested_retry_args?.length)||Boolean(recovery?.allowed_values?.length)||Boolean(recovery?.candidate_commands?.length)||Boolean(guidance.nextSteps?.length);return projectPmDiagnosticOutput(guidanceToJsonEnvelope(guidance,exitCode),{diagnosticClass:hasActionableRecovery?"recovery_bundle":"error"})}function guidanceToClassification(message){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required},message)}function normalizeMessage(message){return message.replace(/\(outputHelp\)/g,"").trim()}function isModuleResolutionErrorMessage(message){const normalized=message.toLowerCase();return normalized.includes("cannot find module")||normalized.includes("cannot find package")||normalized.includes("err_module_not_found")||normalized.includes("module_not_found")}function normalizeContextList(values){if(!Array.isArray(values)){return void 0}const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function dedupeStrings(values){const seen=new Set;const result=[];for(const value of values){if(seen.has(value)){continue}seen.add(value);result.push(value)}return result}function inferCommandNameFromRecovery(recovery){return resolveRecoveryCommandName(recovery?.normalized_args)}function inferAllowedValuesFromMessage(message){const match=message.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);if(!match){return[]}return match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry))}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args;const fields=recovery?.provided_fields;const replacement=allowedValues[0];if(!Array.isArray(args)||!Array.isArray(fields)||!replacement){return void 0}for(const field of fields){const index=args.findIndex(arg=>arg===field);if(index>=0&&index<args.length-1&&!args[index+1]?.startsWith("-")){const nextArgs=[...args];nextArgs[index+1]=replacement;return renderPmCommand(nextArgs)}}return void 0}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length===0){return void 0}if(firstLine.length<=120){return firstLine}return`${firstLine.slice(0,117)}...`}function normalizeContextValue(value,fallback){return typeof value==="string"&&value.trim().length>0?value.trim():fallback}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context){return guidance}const normalizedRawMessage=normalizeMessage(rawMessage);const code=normalizeContextValue(context.code,guidance.code);const type=normalizeContextValue(context.type,errorType(code));const examples=normalizeContextList(context.examples)??guidance.examples;const nextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps;const verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors;const fallbackTitle=guidance.code==="command_failed"&&context.code?buildFallbackTitleFromMessage(normalizedRawMessage):void 0;const contextRecovery=normalizeRecoveryPayload(context.recovery);const recovery=contextRecovery&&guidance.recovery?normalizeRecoveryPayload({...guidance.recovery,...contextRecovery}):contextRecovery??guidance.recovery;return{...guidance,code,type,title:fallbackTitle??guidance.title,happened:normalizedRawMessage.length>0?normalizedRawMessage:guidance.happened,required:normalizeContextValue(context.required,guidance.required),why:normalizeContextValue(context.why,guidance.why),examples,nextSteps,verificationErrors,policyViolations:context.policy_violations,policyViolationCount:context.policy_violation_count,flag:context.flag,value:context.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,tombstone:context.tombstone,availableDependencies:context.available_dependencies,recovery}}function buildTrackerNotInitializedGuidance(rawMessage,message,context){const trackerNotInitialized=message.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!trackerNotInitialized){return null}const attemptedRoot=trackerNotInitialized[1];const nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);if(nearbyRoot){return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${attemptedRoot}, but found a tracker at ${nearbyRoot}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${nearbyRoot} <command>`,`PM_PATH=${nearbyRoot} pm <command>`],nextSteps:[`Re-run with "--pm-path ${nearbyRoot}" or export PM_PATH=${nearbyRoot}.`]}),rawMessage,context)}return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${trackerNotInitialized[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),rawMessage,context)}function buildItemNotFoundGuidance(rawMessage,message,context){const itemNotFound=message.match(/^Item ([^ ]+) not found$/);if(!itemNotFound){return null}const badId=itemNotFound[1];const isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId);const happened=isPlaceholder?`The item ID "${badId}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${badId}" exists in the active tracker scope.`;const nextSteps=isPlaceholder?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",happened,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){if(!message.includes("is assigned to")||!message.includes("Use --force to override")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"ownership_conflict",title:"Ownership conflict",happened:message,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),rawMessage,context)}function buildLockConflictGuidance(rawMessage,message,context){if(!message.includes("is locked")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),rawMessage,context)}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /);const missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions){return null}const plural=Boolean(missingRequiredOptions);const missingOptionFlag=!plural?message.replace(/^Missing required option\s+/,"").trim():null;const missingOptionLabel=missingOptionFlag??"";const missingOptionRequired=missingOptionFlag?`Pass ${missingOptionFlag} with a valid value before running the command.`:"Provide the required option for this command invocation.";return applyPmCliErrorContext(makeGuidanceMessage({code:"missing_required_option",title:plural?"Missing required options":`Missing required option ${missingOptionLabel}`,happened:message,required:plural?"Provide every required option for this command invocation.":missingOptionRequired,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),rawMessage,context)}function buildNoUpdateFieldsGuidance(rawMessage,message,context){if(!message.startsWith("No update flags provided")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),rawMessage,context)}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!message.startsWith("Invalid ")&&!message.includes(" must be ")&&!message.includes(" requires ")){return null}const recovery=normalizeRecoveryPayload(context?.recovery);const commandName=inferCommandNameFromRecovery(recovery);const helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help";const allowedValues=inferAllowedValuesFromMessage(message);const enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues});const retryExample=buildAllowedValueRetryCommand(recovery,allowedValues);const examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"];const nextSteps=allowedValues.length>0?[`Allowed values: ${allowedValues.join("|")}`,`Run "${helpExample}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return applyPmCliErrorContext(makeGuidanceMessage({code:"invalid_argument_value",title:"Invalid argument value",happened:message,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples,nextSteps,recovery:enrichedRecovery}),rawMessage,context)}function buildPmCliErrorGuidance(rawMessage,context){const message=normalizeMessage(rawMessage);const guidance=buildTrackerNotInitializedGuidance(rawMessage,message,context)??buildItemNotFoundGuidance(rawMessage,message,context)??buildOwnershipConflictGuidance(rawMessage,message,context)??buildLockConflictGuidance(rawMessage,message,context)??buildPmMissingRequiredOptionGuidance(rawMessage,message,context)??buildNoUpdateFieldsGuidance(rawMessage,message,context)??buildInvalidArgumentGuidance(rawMessage,message,context);if(guidance){return guidance}return applyPmCliErrorContext(makeGuidanceMessage({code:"command_failed",title:"Command failed",happened:message,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),rawMessage,context)}function commandExampleForRequiredOption(commandName,optionFlag,allowedTypes){if(commandName==="create"&&optionFlag.startsWith("--type")){const firstAllowed=allowedTypes.split("|")[0]||"Task";return[`pm create --title "Example title" --description "Example description" --type ${firstAllowed} --status open --priority 1 --message "Create item" --create-mode progressive`]}if(commandName==="update"){return['pm update pm-a1b2 --status in_progress --message "Start implementation"']}return[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();const firstLongFlag=normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0];return firstLongFlag??normalized}function renderPmCommandFromArgs(argv){if(!Array.isArray(argv)||argv.length===0){return void 0}return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values)){return void 0}const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function buildCommanderRecoveryPayload(context,overrides={}){const providedFields=normalizeOptionFlags(context?.providedOptionFlags);const normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0;const attemptedCommand=typeof context?.attemptedCommand==="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs);const retryCommand=typeof context?.suggestedRetryCommand==="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,...overrides})}function appendIfMissing(entries,value){if(!value||entries.includes(value)){return entries}return[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]);const LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(!Array.isArray(argv)){return void 0}for(const token of argv){if(!token.startsWith("--")){continue}const equalsIndex=token.indexOf("=");const flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag)){return flag}}return void 0}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv)){return void 0}const commandIndex=argv.indexOf("test");if(commandIndex<0){return void 0}const idToken=argv[commandIndex+1];if(typeof idToken!=="string"||idToken.startsWith("-")){return void 0}for(let index=commandIndex+2;index<argv.length;index+=1){const token=argv[index];if(token!=="--add"&&token!=="--remove"){continue}const key=argv[index+1];if(typeof key!=="string"||!LINKED_TEST_RETRY_KEYS.has(key)){return void 0}const valueTokens=[];for(let cursor=index+2;cursor<argv.length;cursor+=1){const candidate=argv[cursor];if(candidate.startsWith("--")&&candidate.length>2){break}valueTokens.push(candidate)}if(valueTokens.length<2){return void 0}const merged=`${key}=${valueTokens.join(" ")}`;const rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}return void 0}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption){return null}const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]);const isType=optionFlag.startsWith("--type");const retryCommand=context?.suggestedRetryCommand;const providedFlags=normalizeOptionFlags(context?.providedOptionFlags);const missing=[optionFlag];const examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes);const examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples;const nextStepsBase=isType?[`Allowed type values: ${allowedTypes}`,`Run "pm ${commandName??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${commandName??"<command>"} --help" for required option guidance.`];const nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase;const nextSteps=providedFlags&&providedFlags.length>0?appendIfMissing(nextStepsWithRetry,`Already provided options: ${providedFlags.join(", ")}`):nextStepsWithRetry;return makeGuidanceMessage({code:"missing_required_option",title:`Missing required option ${optionFlag}`,happened:`Commander rejected the command because ${optionFlag} was not provided.`,required:`Pass ${optionFlag} with a valid value before running the command.`,why:isType?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:examplesWithRetry,nextSteps,recovery:buildCommanderRecoveryPayload(context,{missing})})}function buildMissingRequiredArgumentGuidance(message,commandName,context){const missingArgument=message.match(/missing required argument '([^']+)'/);if(!missingArgument){return null}const argumentName=missingArgument[1];return makeGuidanceMessage({code:"missing_required_argument",title:`Missing required argument ${argumentName}`,happened:`Command invocation omitted positional argument ${argumentName}.`,required:`Provide ${argumentName} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context,{missing:[argumentName]})})}function buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions){return makeGuidanceMessage({code:"unsupported_update_option",title:`Unsupported option ${optionName} for update`,happened:`pm update does not accept ${optionName} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions})})}const UNKNOWN_OPTION_REQUIRED_BY_SCOPE={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function resolveUnknownOptionCandidateContext(context){const otherCommands=normalizeContextList(context.unknownOptionOtherCommands)??[];return{otherCommands,optionScope:context.unknownOptionScope??(otherCommands.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:context.unknownOptionOtherCommandsTotal??otherCommands.length}}function buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand){const proseCommands=candidateContext.otherCommands.slice(0,3);const proseRemainder=candidateContext.candidateTotal-proseCommands.length;const proseRemainderText=proseRemainder>0?` and ${String(proseRemainder)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",suggestions.length?`Nearest supported options: ${suggestions.join(", ")}`:void 0,proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,candidateContext.optionScope==="declared_nowhere"?`${optionName} is not declared on any command path. Use a nearest supported option on ${commandName??"the attempted command"}, or inspect that command's help.`:void 0,retryCommand?`Replay with suggested correction: ${retryCommand}`:void 0].filter(entry=>typeof entry==="string")}function resolveUnknownOptionRetry(context,optionName){if(context.suggestedRetryCommand!==void 0){return{retryCommand:context.suggestedRetryCommand}}const normalizedArgs=context.normalizedInvocationArgs;if(normalizedArgs===void 0)return{};if(normalizedArgs.filter(argument=>argument===optionName||argument.startsWith(`${optionName}=`)).length!==1){return{}}const optionIndex=normalizedArgs.findIndex(argument=>argument===optionName||argument.startsWith(`${optionName}=`));if(optionIndex<0||normalizedArgs.includes("--")||!normalizedArgs[optionIndex]?.includes("=")&&optionIndex!==normalizedArgs.length-1&&normalizedArgs[optionIndex+1]?.startsWith("-")!==true){return{}}const suggestedRetryArgs=stripGlobalBootstrapTokens(normalizedArgs.filter((_,index)=>index!==optionIndex));return{retryCommand:renderPmCommand(suggestedRetryArgs),suggestedRetryArgs}}function buildUnknownOptionGuidance(message,commandName,context){const unknownOption=message.match(/unknown option '([^']+)'/);if(!unknownOption){return null}const guidanceContext=context??{};const optionName=unknownOption[1];const suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[];const{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc")){return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions)}const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext);const nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);const examples=[retryCommand,`pm ${commandName?resolvePmCommandAlias(commandName)?.canonical??commandName:"<command>"} --help`].filter(entry=>typeof entry==="string");return makeGuidanceMessage({code:"unknown_option",title:`Unknown option ${optionName}`,happened:`Commander does not recognize option ${optionName} for this command path.`,required:UNKNOWN_OPTION_REQUIRED_BY_SCOPE[candidateContext.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:optionName,value:optionName,examples,nextSteps,recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions.length>0?suggestions:void 0,suggested_retry:retryCommand,suggested_retry_args:suggestedRetryArgs,candidate_commands:candidateContext.otherCommands,candidate_commands_total:candidateContext.candidateTotal||void 0,candidate_commands_truncated:guidanceContext.unknownOptionOtherCommandsTruncated,option_scope:candidateContext.optionScope})})}function buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context){const installStep=`"${commandToken}" is provided by the ${packageHint.packageName} package. Install it with: ${packageHint.installCommand}`;const nextSteps=baseNextSteps.filter(step=>!step.endsWith(`: ${packageHint.installCommand}`));return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration. It is shipped by the optional ${packageHint.packageName} package.`,required:`Install the ${packageHint.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:dedupeStrings([packageHint.installCommand,...baseExamples]),nextSteps:dedupeStrings([installStep,...nextSteps]),recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownCommandGuidance(message,context){const unknownCommand=message.match(/unknown command '([^']+)'/);if(!unknownCommand){return null}const commandToken=unknownCommand[1];const runtimeExamples=normalizeContextList(context?.unknownCommandExamples);const runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps);const packageHint=resolveKnownPackageCommandHint(commandToken);const baseExamples=runtimeExamples??["pm --help"];const baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."];const failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase()));const hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();if(packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))){return buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context)}return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:baseExamples,nextSteps:baseNextSteps,recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownSubcommandGuidance(context){const commandPath=context?.unknownSubcommandPath?.trim();const token=context?.unknownSubcommandToken?.trim();const allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed){return null}const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,happened:`The positional token sequence "${token}" is not a declared ${commandPath} subcommand.`,required:`Use one of: ${allowed.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...retryCommand?[retryCommand]:[],`pm ${commandPath} --help`],nextSteps:retryCommand?[`Retry with the declared hyphenated action: ${retryCommand}`]:["Choose one value from recovery.allowed_values."],recovery:buildCommanderRecoveryPayload(context,{allowed_values:allowed,suggested_retry:retryCommand})})}function buildLinkedTestValueNotQuotedGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||commandName!=="test"){return null}const argv=context?.normalizedInvocationArgs;const mutationFlag=findLinkedTestMutationFlag(argv);if(!mutationFlag){return null}const retryCommand=buildLinkedTestQuotedRetryCommand(argv);return makeGuidanceMessage({code:"linked_test_value_not_quoted",title:`Linked-test ${mutationFlag} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${mutationFlag} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${mutationFlag} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...retryCommand?[retryCommand]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...retryCommand?[`Replay with the value re-joined into one argument: ${retryCommand}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:buildCommanderRecoveryPayload(context,retryCommand?{suggested_retry:retryCommand}:{})})}const TRANSPOSED_COLLECTION_COMMANDS=new Set(["comments","docs","files","learnings","notes","test"]);function buildTransposedCollectionActionGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!TRANSPOSED_COLLECTION_COMMANDS.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>token===commandName);const action=argv[commandIndex+1];const parsedItemId=argv[commandIndex+2];const itemId=context?.verifiedCollectionItemId?.trim();if(action?.toLowerCase()!=="add"||!parsedItemId||parsedItemId.startsWith("-")||!itemId||itemId.toLowerCase()!==parsedItemId.toLowerCase()){return null}const suggestedRetry=`pm ${commandName} ${itemId} --add <value>`;return makeGuidanceMessage({code:"collection_transposed_subcommand",title:`Transposed ${commandName} add syntax`,happened:`The positional token "add" occupied the item-id role and "${itemId}" occupied the next positional role. pm ${commandName} does not use an add subcommand.`,required:`Place the item id immediately after ${commandName}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[suggestedRetry,`pm ${commandName} --help`],recovery:buildCommanderRecoveryPayload(context,{parsed_positionals:[{role:"transposed_subcommand",value:action},{role:"item_id",value:itemId}],suggested_retry:suggestedRetry})})}const CONTEXT_GUIDANCE_VALUE_FLAGS=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]);const CONTEXT_GUIDANCE_COMMAND_NAMES=new Set(["context","ctx"]);function buildContextItemArgumentGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!CONTEXT_GUIDANCE_COMMAND_NAMES.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token));const searchIndex=commandIndex===-1?1:commandIndex+1;const match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=false;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=false;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(token.startsWith("-")){continue}positional=token;break}}if(!positional){return null}const getCommand=`pm get ${positional}`;return makeGuidanceMessage({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${positional}".`,required:`Use ${getCommand} for one item's full details, or pm context --parent ${positional} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[getCommand,`pm context --parent ${positional}`],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:getCommand})})}function buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context){const message=normalizeMessage(rawMessage);const guidance=buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context)??buildMissingRequiredArgumentGuidance(message,commandName,context)??buildUnknownOptionGuidance(message,commandName,context)??buildUnknownCommandGuidance(message,context)??buildUnknownSubcommandGuidance(context)??buildTransposedCollectionActionGuidance(message,commandName,context)??buildLinkedTestValueNotQuotedGuidance(message,commandName,context)??buildContextItemArgumentGuidance(message,commandName,context);if(guidance){return guidance}return makeGuidanceMessage({code:"invalid_command_usage",title:"Invalid command usage",happened:message,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context)})}function formatPmCliErrorForDisplay(rawMessage,context){const guidance=buildPmCliErrorGuidance(rawMessage,context);if((context?.code==="tracker_root_missing"||context?.code==="tracker_not_initialized")&&guidance.title==="Tracker is not initialized"&&guidance.recovery?.suggested_retry_args){return[`Error: ${guidance.title}`,`Run: ${renderPmCommand(guidance.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join("\n")}return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyPmCliError(rawMessage,context){return guidanceToClassification(buildPmCliErrorGuidance(rawMessage,context))}function formatPmCliErrorForJson(rawMessage,exitCode,context){return projectJsonErrorGuidance(buildPmCliErrorGuidance(rawMessage,context),exitCode)}function formatCommanderErrorForDisplay(rawMessage,commandName,allowedTypes,context){const guidance=buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context);return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyCommanderError(rawMessage,commandName,allowedTypes,context){return guidanceToClassification(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context))}function formatCommanderErrorForJson(rawMessage,commandName,allowedTypes,exitCode,context){return projectJsonErrorGuidance(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context),exitCode)}function formatUnknownErrorForJson(rawMessage,exitCode){const guidance=buildUnknownErrorGuidance(rawMessage);return projectJsonErrorGuidance(guidance,exitCode)}function buildUnknownErrorGuidance(rawMessage){const message=normalizeMessage(rawMessage);if(isModuleResolutionErrorMessage(message)){return makeGuidanceMessage({code:"module_import_failed",title:"Module import failed",happened:message,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]})}return makeGuidanceMessage({code:"unknown_error",title:"Unhandled error",happened:message,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function classifyUnknownError(rawMessage){return guidanceToClassification(buildUnknownErrorGuidance(rawMessage))}const _testOnly={applyPmCliErrorContext,appendIfMissing,buildCommanderRecoveryPayload,buildFallbackTitleFromMessage,commandExampleForRequiredOption,dedupeStrings,guidanceToClassification,guidanceToJsonEnvelope,normalizeRecoveryPayload,renderList,resolveKnownPackageCommandHint};export{_testOnly,buildLinkedTestQuotedRetryCommand,classifyCommanderError,classifyPmCliError,classifyUnknownError,formatCommanderErrorForDisplay,formatCommanderErrorForJson,formatPmCliErrorForDisplay,formatPmCliErrorForJson,formatUnknownErrorForJson,projectLeanErrorEnvelope,renderGuidanceMessage};
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="10506b96-211c-5174-aeb0-0e5301e21e34")}catch(e2){}})();import{resolveRecoveryCommandName}from"../sdk/agent/command-recovery.js";import{projectPmDiagnosticOutput,projectPmDiagnosticText}from"../sdk/cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./argv-utils.js";import{discoverNearbyPmRoot}from"../sdk/tracker-root-discovery.js";import{stripGlobalBootstrapTokens}from"../sdk/cli-bootstrap.js";import{findPmNamespacedCommand,resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";function projectLeanErrorEnvelope(envelope){const{why:_why,title:_title,...actionable}=envelope;return actionable}const STRUCTURED_WHY_SUPPRESSION_CODES=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function includeWhyInStructuredGuidance(message){if(!message.why){return false}if(message.recovery?.recovery_mode==="compact"){return false}return!STRUCTURED_WHY_SUPPRESSION_CODES.has(message.code)}function errorType(code){return`urn:pm-cli:error:${code}`}function makeGuidanceMessage(params){return{...params,type:errorType(params.code)}}const GUIDE_SHELL_HINT={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"};const CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"};const SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"};const GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"};const KNOWN_PACKAGE_COMMAND_HINTS={guide:GUIDE_SHELL_HINT,shell:GUIDE_SHELL_HINT,completion:GUIDE_SHELL_HINT,"completion-statuses":GUIDE_SHELL_HINT,"completion-tags":GUIDE_SHELL_HINT,"completion-types":GUIDE_SHELL_HINT,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:CALENDAR_HINT,cal:CALENDAR_HINT,reindex:SEARCH_ADVANCED_HINT,"search-advanced":SEARCH_ADVANCED_HINT,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":GOVERNANCE_AUDIT_HINT,"dedupe-audit":GOVERNANCE_AUDIT_HINT,"dedupe-merge":GOVERNANCE_AUDIT_HINT,normalize:GOVERNANCE_AUDIT_HINT};function resolveKnownPackageCommandHint(commandToken){const primary=commandToken.trim().split(/\s+/)[0]?.toLowerCase();if(!primary){return void 0}return KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){if(entries.length===0){return[]}return[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values)){return void 0}const normalized=values.filter(entry=>typeof entry==="string").map(entry=>entry.trim()).filter(entry=>entry.length>0);return normalized.length>0?normalized:void 0}function normalizeRecoveryCandidates(candidates){if(!Array.isArray(candidates)){return void 0}const normalized=candidates.map(entry=>({source:typeof entry?.source==="string"?entry.source.trim():"",command:typeof entry?.command==="string"?entry.command.trim():"",reason:typeof entry?.reason==="string"?entry.reason.trim():""})).filter(entry=>entry.source.length>0&&entry.command.length>0&&entry.reason.length>0);return normalized.length>0?normalized:void 0}function assignRecoveryString(normalized,key,value){if(typeof value==="string"&&value.trim().length>0){normalized[key]=value.trim()}}function assignRecoveryCollection(normalized,key,value){if(key==="parsed_positionals"){if(!Array.isArray(value))return;const parsedPositionals=value.map(entry=>({role:typeof entry?.role==="string"?entry.role.trim():"",value:typeof entry?.value==="string"?entry.value.trim():""})).filter(entry=>entry.role.length>0&&entry.value.length>0);if(parsedPositionals.length>0){normalized.parsed_positionals=parsedPositionals}return}const values=normalizeStringArray(value);if(values){normalized[key]=values}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!=="object"){return void 0}const normalized={};if(payload.recovery_mode==="compact"){normalized.recovery_mode="compact"}assignRecoveryString(normalized,"attempted_command",payload.attempted_command);assignRecoveryCollection(normalized,"normalized_args",payload.normalized_args);assignRecoveryCollection(normalized,"parsed_positionals",payload.parsed_positionals);assignRecoveryCollection(normalized,"provided_fields",payload.provided_fields);assignRecoveryCollection(normalized,"missing",payload.missing);assignRecoveryCollection(normalized,"missing_required_fields",payload.missing_required_fields);assignRecoveryCollection(normalized,"suggested_flags",payload.suggested_flags);assignRecoveryCollection(normalized,"allowed_values",payload.allowed_values);assignRecoveryCollection(normalized,"candidate_commands",payload.candidate_commands);if(typeof payload.candidate_commands_total==="number"&&Number.isSafeInteger(payload.candidate_commands_total)&&payload.candidate_commands_total>=0){normalized.candidate_commands_total=payload.candidate_commands_total}if(payload.candidate_commands_truncated===true){normalized.candidate_commands_truncated=true}if(payload.option_scope==="declared_on_path"||payload.option_scope==="declared_elsewhere"||payload.option_scope==="declared_nowhere"){normalized.option_scope=payload.option_scope}assignRecoveryString(normalized,"suggested_retry",payload.suggested_retry);assignRecoveryCollection(normalized,"suggested_retry_args",payload.suggested_retry_args);if(typeof payload.retry_after_ms==="number"&&Number.isSafeInteger(payload.retry_after_ms)&&payload.retry_after_ms>=0){normalized.retry_after_ms=payload.retry_after_ms}const fallbackCandidates=normalizeRecoveryCandidates(payload.fallback_candidates);if(fallbackCandidates){normalized.fallback_candidates=fallbackCandidates}assignRecoveryString(normalized,"next_best_command",payload.next_best_command);return Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){if(value){lines.push(` ${label}: ${value}`)}}function appendRecoveryListLine(lines,label,values,separator){if(values&&values.length>0){lines.push(` ${label}: ${values.join(separator)}`)}}function renderRecoveryBundle(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized){return[]}const lines=["Recovery bundle:"];appendRecoveryTextLine(lines,"suggested_retry",normalized.suggested_retry);appendRecoveryTextLine(lines,"attempted_command",normalized.attempted_command);appendRecoveryListLine(lines,"normalized_args",normalized.attempted_command?void 0:normalized.normalized_args," ");if(normalized.parsed_positionals&&normalized.parsed_positionals.length>0){lines.push(" parsed_positionals:");for(const positional of normalized.parsed_positionals){lines.push(` - ${positional.role}: ${positional.value}`)}}appendRecoveryListLine(lines,"provided_fields",normalized.provided_fields,", ");appendRecoveryListLine(lines,"missing",normalized.missing,", ");appendRecoveryListLine(lines,"missing_required_fields",normalized.missing_required_fields,", ");appendRecoveryListLine(lines,"suggested_flags",normalized.suggested_flags,", ");appendRecoveryListLine(lines,"allowed_values",normalized.allowed_values,", ");appendRecoveryListLine(lines,"candidate_commands",normalized.candidate_commands,", ");if(typeof normalized.candidate_commands_total==="number"){lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`)}if(normalized.candidate_commands_truncated===true){lines.push(" candidate_commands_truncated: true")}if(normalized.option_scope!==void 0){lines.push(` option_scope: ${normalized.option_scope}`)}if(typeof normalized.retry_after_ms==="number"){lines.push(` retry_after_ms: ${normalized.retry_after_ms}`)}appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command);if(normalized.fallback_candidates&&normalized.fallback_candidates.length>0){lines.push(" fallback_candidates:");for(const candidate of normalized.fallback_candidates){lines.push(` - ${candidate.source}: ${candidate.command} (${candidate.reason})`)}}return lines}function renderGuidanceMessage(message){const lines=[`Error: ${message.title}`,"","What is required:",` ${message.required}`];if(message.nextSteps&&message.nextSteps.length>0){lines.push("");lines.push(...renderList("Next steps:",message.nextSteps))}lines.push("","What happened:",` ${message.happened}`);if(message.why){lines.push("","Why:");lines.push(` ${message.why}`)}if(message.examples&&message.examples.length>0){lines.push("");lines.push(...renderList("Examples:",message.examples))}if(message.verificationErrors&&message.verificationErrors.length>0){lines.push("");lines.push(...renderList("Verification errors:",message.verificationErrors))}const recoveryLines=renderRecoveryBundle(message.recovery);if(recoveryLines.length>0){lines.push("");lines.push(...recoveryLines)}return lines.join("\n")}function attachStructuredGuidanceDetails(payload,message){if(message.tombstone!==void 0){payload.tombstone=message.tombstone;payload.item_id=message.itemId}if(includeWhyInStructuredGuidance(message)){payload.why=message.why}if(message.examples&&message.examples.length>0){payload.examples=message.examples}if(message.nextSteps&&message.nextSteps.length>0){payload.next_steps=message.nextSteps}if(message.verificationErrors&&message.verificationErrors.length>0){payload.verification_errors=message.verificationErrors}if(message.flag!==void 0)payload.flag=message.flag;if(message.value!==void 0)payload.value=message.value;if(message.unmatchedSelectors!==void 0)payload.unmatched_selectors=message.unmatchedSelectors;if(message.availableDependencies!==void 0)payload.available_dependencies=message.availableDependencies;if(message.recovery){payload.recovery=message.recovery}return payload}function resolveRefusalCandidateFlag(message,normalizedArgs){if(message.flag)return message.flag;const isAdmissibleCandidate=flag=>{const canonicalFlag=flag.split("=",1)[0];return stripGlobalBootstrapTokens([canonicalFlag]).length>0&&!["--help","--no-changed-fields","--version"].includes(canonicalFlag)&&normalizedArgs.some(argument=>argument===canonicalFlag||argument.startsWith(`${canonicalFlag}=`))};const mentionedFlag=[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag));if(mentionedFlag)return mentionedFlag;return message.recovery?.provided_fields?.map(field=>field.split("=",1)[0]).find(field=>isAdmissibleCandidate(field))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(candidateFlag){const candidateArgument=normalizedArgs.find(argument=>argument===candidateFlag||argument.startsWith(`${candidateFlag}=`));if(candidateArgument?.startsWith(`${candidateFlag}=`)){return candidateArgument.slice(candidateFlag.length+1)}const candidateIndex=normalizedArgs.indexOf(candidateFlag);return candidateIndex>=0?normalizedArgs[candidateIndex+1]:void 0}const allowedValues=message.recovery?.allowed_values;if(!allowedValues?.length)return void 0;return normalizedArgs.find((argument,index)=>index>0&&!argument.startsWith("-")&&!allowedValues.includes(argument))}function buildRefusalEnvelope(message,exitCode){if(message.policyViolations?.length){return{surface:`policy:${message.policyViolations.map(policy=>policy.policy_id).join(",")}`,policies:message.policyViolations,policy_violation_count:message.policyViolationCount,missing_fields:[...new Set(message.policyViolations.flatMap(policy=>policy.missing_fields))],exit_code:exitCode}}const invocationArgs=stripGlobalBootstrapTokens(message.recovery?.normalized_args??[]);const namespaced=findPmNamespacedCommand(invocationArgs);const normalizedArgs=namespaced?[namespaced.alias,...invocationArgs.slice(namespaced.canonical_argv.length)]:invocationArgs;const candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs);const rejectedValue=resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag);return{surface:candidateFlag??message.recovery?.missing?.[0]??resolveRecoveryCommandName(normalizedArgs)??"command",...rejectedValue!==void 0?{rejected_value:rejectedValue}:{},...message.recovery?.allowed_values?.length?{legal_domain:message.recovery.allowed_values}:{},exit_code:exitCode}}function guidanceToJsonEnvelope(message,exitCode){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,exit_code:exitCode,refusal:buildRefusalEnvelope(message,exitCode)},message)}function projectJsonErrorGuidance(guidance,exitCode){const recovery=guidance.recovery;const hasActionableRecovery=Boolean(recovery?.suggested_retry)||Boolean(recovery?.suggested_retry_args?.length)||Boolean(recovery?.allowed_values?.length)||Boolean(recovery?.candidate_commands?.length)||Boolean(guidance.nextSteps?.length);return projectPmDiagnosticOutput(guidanceToJsonEnvelope(guidance,exitCode),{diagnosticClass:hasActionableRecovery?"recovery_bundle":"error"})}function guidanceToClassification(message){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required},message)}function normalizeMessage(message){return message.replace(/\(outputHelp\)/g,"").trim()}function isModuleResolutionErrorMessage(message){const normalized=message.toLowerCase();return normalized.includes("cannot find module")||normalized.includes("cannot find package")||normalized.includes("err_module_not_found")||normalized.includes("module_not_found")}function normalizeContextList(values){if(!Array.isArray(values)){return void 0}const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function dedupeStrings(values){const seen=new Set;const result=[];for(const value of values){if(seen.has(value)){continue}seen.add(value);result.push(value)}return result}function inferCommandNameFromRecovery(recovery){return resolveRecoveryCommandName(recovery?.normalized_args)}function inferAllowedValuesFromMessage(message){const match=message.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);if(!match){return[]}return match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry))}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args;const fields=recovery?.provided_fields;const replacement=allowedValues[0];if(!Array.isArray(args)||!Array.isArray(fields)||!replacement){return void 0}for(const field of fields){const index=args.findIndex(arg=>arg===field);if(index>=0&&index<args.length-1&&!args[index+1]?.startsWith("-")){const nextArgs=[...args];nextArgs[index+1]=replacement;return renderPmCommand(nextArgs)}}return void 0}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length===0){return void 0}if(firstLine.length<=120){return firstLine}return`${firstLine.slice(0,117)}...`}function normalizeContextValue(value,fallback){return typeof value==="string"&&value.trim().length>0?value.trim():fallback}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context){return guidance}const normalizedRawMessage=normalizeMessage(rawMessage);const code=normalizeContextValue(context.code,guidance.code);const type=normalizeContextValue(context.type,errorType(code));const examples=normalizeContextList(context.examples)??guidance.examples;const nextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps;const verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors;const fallbackTitle=guidance.code==="command_failed"&&context.code?buildFallbackTitleFromMessage(normalizedRawMessage):void 0;const contextRecovery=normalizeRecoveryPayload(context.recovery);const recovery=contextRecovery&&guidance.recovery?normalizeRecoveryPayload({...guidance.recovery,...contextRecovery}):contextRecovery??guidance.recovery;return{...guidance,code,type,title:fallbackTitle??guidance.title,happened:normalizedRawMessage.length>0?normalizedRawMessage:guidance.happened,required:normalizeContextValue(context.required,guidance.required),why:normalizeContextValue(context.why,guidance.why),examples,nextSteps,verificationErrors,policyViolations:context.policy_violations,policyViolationCount:context.policy_violation_count,flag:context.flag,value:context.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,tombstone:context.tombstone,availableDependencies:context.available_dependencies,recovery}}function buildTrackerNotInitializedGuidance(rawMessage,message,context){const trackerNotInitialized=message.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!trackerNotInitialized){return null}const attemptedRoot=trackerNotInitialized[1];const nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);if(nearbyRoot){return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${attemptedRoot}, but found a tracker at ${nearbyRoot}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${nearbyRoot} <command>`,`PM_PATH=${nearbyRoot} pm <command>`],nextSteps:[`Re-run with "--pm-path ${nearbyRoot}" or export PM_PATH=${nearbyRoot}.`]}),rawMessage,context)}return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${trackerNotInitialized[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),rawMessage,context)}function buildItemNotFoundGuidance(rawMessage,message,context){const itemNotFound=message.match(/^Item ([^ ]+) not found$/);if(!itemNotFound){return null}const badId=itemNotFound[1];const isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId);const happened=isPlaceholder?`The item ID "${badId}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${badId}" exists in the active tracker scope.`;const nextSteps=isPlaceholder?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",happened,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){if(!message.includes("is assigned to")||!message.includes("Use --force to override")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"ownership_conflict",title:"Ownership conflict",happened:message,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),rawMessage,context)}function buildLockConflictGuidance(rawMessage,message,context){if(!message.includes("is locked")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),rawMessage,context)}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /);const missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions){return null}const plural=Boolean(missingRequiredOptions);const missingOptionFlag=!plural?message.replace(/^Missing required option\s+/,"").trim():null;const missingOptionLabel=missingOptionFlag??"";const missingOptionRequired=missingOptionFlag?`Pass ${missingOptionFlag} with a valid value before running the command.`:"Provide the required option for this command invocation.";return applyPmCliErrorContext(makeGuidanceMessage({code:"missing_required_option",title:plural?"Missing required options":`Missing required option ${missingOptionLabel}`,happened:message,required:plural?"Provide every required option for this command invocation.":missingOptionRequired,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),rawMessage,context)}function buildNoUpdateFieldsGuidance(rawMessage,message,context){if(!message.startsWith("No update flags provided")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),rawMessage,context)}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!message.startsWith("Invalid ")&&!message.includes(" must be ")&&!message.includes(" requires ")){return null}const recovery=normalizeRecoveryPayload(context?.recovery);const commandName=inferCommandNameFromRecovery(recovery);const helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help";const allowedValues=inferAllowedValuesFromMessage(message);const enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues});const retryExample=buildAllowedValueRetryCommand(recovery,allowedValues);const examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"];const nextSteps=allowedValues.length>0?[`Allowed values: ${allowedValues.join("|")}`,`Run "${helpExample}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return applyPmCliErrorContext(makeGuidanceMessage({code:"invalid_argument_value",title:"Invalid argument value",happened:message,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples,nextSteps,recovery:enrichedRecovery}),rawMessage,context)}function buildPmCliErrorGuidance(rawMessage,context){const message=normalizeMessage(rawMessage);const guidance=buildTrackerNotInitializedGuidance(rawMessage,message,context)??buildItemNotFoundGuidance(rawMessage,message,context)??buildOwnershipConflictGuidance(rawMessage,message,context)??buildLockConflictGuidance(rawMessage,message,context)??buildPmMissingRequiredOptionGuidance(rawMessage,message,context)??buildNoUpdateFieldsGuidance(rawMessage,message,context)??buildInvalidArgumentGuidance(rawMessage,message,context);if(guidance){return guidance}return applyPmCliErrorContext(makeGuidanceMessage({code:"command_failed",title:"Command failed",happened:message,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),rawMessage,context)}function commandExampleForRequiredOption(commandName,optionFlag,allowedTypes){if(commandName==="create"&&optionFlag.startsWith("--type")){const firstAllowed=allowedTypes.split("|")[0]||"Task";return[`pm create --title "Example title" --description "Example description" --type ${firstAllowed} --status open --priority 1 --message "Create item" --create-mode progressive`]}if(commandName==="update"){return['pm update pm-a1b2 --status in_progress --message "Start implementation"']}return[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();const firstLongFlag=normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0];return firstLongFlag??normalized}function renderPmCommandFromArgs(argv){if(!Array.isArray(argv)||argv.length===0){return void 0}return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values)){return void 0}const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function buildCommanderRecoveryPayload(context,overrides={}){const providedFields=normalizeOptionFlags(context?.providedOptionFlags);const normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0;const attemptedCommand=typeof context?.attemptedCommand==="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs);const retryCommand=typeof context?.suggestedRetryCommand==="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,...overrides})}function appendIfMissing(entries,value){if(!value||entries.includes(value)){return entries}return[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]);const LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(!Array.isArray(argv)){return void 0}for(const token of argv){if(!token.startsWith("--")){continue}const equalsIndex=token.indexOf("=");const flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag)){return flag}}return void 0}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv)){return void 0}const commandIndex=argv.indexOf("test");if(commandIndex<0){return void 0}const idToken=argv[commandIndex+1];if(typeof idToken!=="string"||idToken.startsWith("-")){return void 0}for(let index=commandIndex+2;index<argv.length;index+=1){const token=argv[index];if(token!=="--add"&&token!=="--remove"){continue}const key=argv[index+1];if(typeof key!=="string"||!LINKED_TEST_RETRY_KEYS.has(key)){return void 0}const valueTokens=[];for(let cursor=index+2;cursor<argv.length;cursor+=1){const candidate=argv[cursor];if(candidate.startsWith("--")&&candidate.length>2){break}valueTokens.push(candidate)}if(valueTokens.length<2){return void 0}const merged=`${key}=${valueTokens.join(" ")}`;const rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}return void 0}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption){return null}const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]);const isType=optionFlag.startsWith("--type");const retryCommand=context?.suggestedRetryCommand;const providedFlags=normalizeOptionFlags(context?.providedOptionFlags);const missing=[optionFlag];const examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes);const examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples;const nextStepsBase=isType?[`Allowed type values: ${allowedTypes}`,`Run "pm ${commandName??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${commandName??"<command>"} --help" for required option guidance.`];const nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase;const nextSteps=providedFlags&&providedFlags.length>0?appendIfMissing(nextStepsWithRetry,`Already provided options: ${providedFlags.join(", ")}`):nextStepsWithRetry;return makeGuidanceMessage({code:"missing_required_option",title:`Missing required option ${optionFlag}`,happened:`Commander rejected the command because ${optionFlag} was not provided.`,required:`Pass ${optionFlag} with a valid value before running the command.`,why:isType?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:examplesWithRetry,nextSteps,recovery:buildCommanderRecoveryPayload(context,{missing})})}function buildMissingRequiredArgumentGuidance(message,commandName,context){const missingArgument=message.match(/missing required argument '([^']+)'/);if(!missingArgument){return null}const argumentName=missingArgument[1];return makeGuidanceMessage({code:"missing_required_argument",title:`Missing required argument ${argumentName}`,happened:`Command invocation omitted positional argument ${argumentName}.`,required:`Provide ${argumentName} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context,{missing:[argumentName]})})}function buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions){return makeGuidanceMessage({code:"unsupported_update_option",title:`Unsupported option ${optionName} for update`,happened:`pm update does not accept ${optionName} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions})})}const UNKNOWN_OPTION_REQUIRED_BY_SCOPE={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function resolveUnknownOptionCandidateContext(context){const otherCommands=normalizeContextList(context.unknownOptionOtherCommands)??[];return{otherCommands,optionScope:context.unknownOptionScope??(otherCommands.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:context.unknownOptionOtherCommandsTotal??otherCommands.length}}function buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand){const proseCommands=candidateContext.otherCommands.slice(0,3);const proseRemainder=candidateContext.candidateTotal-proseCommands.length;const proseRemainderText=proseRemainder>0?` and ${String(proseRemainder)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",suggestions.length?`Nearest supported options: ${suggestions.join(", ")}`:void 0,proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,candidateContext.optionScope==="declared_nowhere"?`${optionName} is not declared on any command path. Use a nearest supported option on ${commandName??"the attempted command"}, or inspect that command's help.`:void 0,retryCommand?`Replay with suggested correction: ${retryCommand}`:void 0].filter(entry=>typeof entry==="string")}function resolveUnknownOptionRetry(context,optionName){if(context.suggestedRetryCommand!==void 0){return{retryCommand:context.suggestedRetryCommand}}const normalizedArgs=context.normalizedInvocationArgs;if(normalizedArgs===void 0)return{};if(normalizedArgs.filter(argument=>argument===optionName||argument.startsWith(`${optionName}=`)).length!==1){return{}}const optionIndex=normalizedArgs.findIndex(argument=>argument===optionName||argument.startsWith(`${optionName}=`));if(optionIndex<0||normalizedArgs.includes("--")||!normalizedArgs[optionIndex]?.includes("=")&&optionIndex!==normalizedArgs.length-1&&normalizedArgs[optionIndex+1]?.startsWith("-")!==true){return{}}const suggestedRetryArgs=stripGlobalBootstrapTokens(normalizedArgs.filter((_,index)=>index!==optionIndex));return{retryCommand:renderPmCommand(suggestedRetryArgs),suggestedRetryArgs}}function buildUnknownOptionGuidance(message,commandName,context){const unknownOption=message.match(/unknown option '([^']+)'/);if(!unknownOption){return null}const guidanceContext=context??{};const optionName=unknownOption[1];const suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[];const{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc")){return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions)}const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext);const nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);const examples=[retryCommand,`pm ${commandName?resolvePmCommandAlias(commandName)?.canonical??commandName:"<command>"} --help`].filter(entry=>typeof entry==="string");return makeGuidanceMessage({code:"unknown_option",title:`Unknown option ${optionName}`,happened:`Commander does not recognize option ${optionName} for this command path.`,required:UNKNOWN_OPTION_REQUIRED_BY_SCOPE[candidateContext.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:optionName,value:optionName,examples,nextSteps,recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions.length>0?suggestions:void 0,suggested_retry:retryCommand,suggested_retry_args:suggestedRetryArgs,candidate_commands:candidateContext.otherCommands,candidate_commands_total:candidateContext.candidateTotal||void 0,candidate_commands_truncated:guidanceContext.unknownOptionOtherCommandsTruncated,option_scope:candidateContext.optionScope})})}function buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context){const installStep=`"${commandToken}" is provided by the ${packageHint.packageName} package. Install it with: ${packageHint.installCommand}`;const nextSteps=baseNextSteps.filter(step=>!step.endsWith(`: ${packageHint.installCommand}`));return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration. It is shipped by the optional ${packageHint.packageName} package.`,required:`Install the ${packageHint.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:dedupeStrings([packageHint.installCommand,...baseExamples]),nextSteps:dedupeStrings([installStep,...nextSteps]),recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownCommandGuidance(message,context){const unknownCommand=message.match(/unknown command '([^']+)'/);if(!unknownCommand){return null}const commandToken=unknownCommand[1];const runtimeExamples=normalizeContextList(context?.unknownCommandExamples);const runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps);const packageHint=resolveKnownPackageCommandHint(commandToken);const baseExamples=runtimeExamples??["pm --help"];const baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."];const failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase()));const hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();if(packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))){return buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context)}return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:baseExamples,nextSteps:baseNextSteps,recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownSubcommandGuidance(context){const commandPath=context?.unknownSubcommandPath?.trim();const token=context?.unknownSubcommandToken?.trim();const allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed){return null}const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,happened:`The positional token sequence "${token}" is not a declared ${commandPath} subcommand.`,required:`Use one of: ${allowed.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...retryCommand?[retryCommand]:[],`pm ${resolvePmCommandAlias(commandPath)?.canonical??commandPath} --help`],nextSteps:retryCommand?[`Retry with the declared hyphenated action: ${retryCommand}`]:["Choose one value from recovery.allowed_values."],recovery:buildCommanderRecoveryPayload(context,{allowed_values:allowed,suggested_retry:retryCommand})})}function buildLinkedTestValueNotQuotedGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||commandName!=="test"){return null}const argv=context?.normalizedInvocationArgs;const mutationFlag=findLinkedTestMutationFlag(argv);if(!mutationFlag){return null}const retryCommand=buildLinkedTestQuotedRetryCommand(argv);return makeGuidanceMessage({code:"linked_test_value_not_quoted",title:`Linked-test ${mutationFlag} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${mutationFlag} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${mutationFlag} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...retryCommand?[retryCommand]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...retryCommand?[`Replay with the value re-joined into one argument: ${retryCommand}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:buildCommanderRecoveryPayload(context,retryCommand?{suggested_retry:retryCommand}:{})})}const TRANSPOSED_COLLECTION_COMMANDS=new Set(["comments","docs","files","learnings","notes","test"]);function buildTransposedCollectionActionGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!TRANSPOSED_COLLECTION_COMMANDS.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>token===commandName);const action=argv[commandIndex+1];const parsedItemId=argv[commandIndex+2];const itemId=context?.verifiedCollectionItemId?.trim();if(action?.toLowerCase()!=="add"||!parsedItemId||parsedItemId.startsWith("-")||!itemId||itemId.toLowerCase()!==parsedItemId.toLowerCase()){return null}const suggestedRetry=`pm ${commandName} ${itemId} --add <value>`;return makeGuidanceMessage({code:"collection_transposed_subcommand",title:`Transposed ${commandName} add syntax`,happened:`The positional token "add" occupied the item-id role and "${itemId}" occupied the next positional role. pm ${commandName} does not use an add subcommand.`,required:`Place the item id immediately after ${commandName}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[suggestedRetry,`pm ${commandName} --help`],recovery:buildCommanderRecoveryPayload(context,{parsed_positionals:[{role:"transposed_subcommand",value:action},{role:"item_id",value:itemId}],suggested_retry:suggestedRetry})})}const CONTEXT_GUIDANCE_VALUE_FLAGS=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]);const CONTEXT_GUIDANCE_COMMAND_NAMES=new Set(["context","ctx"]);function buildContextItemArgumentGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!CONTEXT_GUIDANCE_COMMAND_NAMES.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token));const searchIndex=commandIndex===-1?1:commandIndex+1;const match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=false;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=false;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(token.startsWith("-")){continue}positional=token;break}}if(!positional){return null}const getCommand=`pm get ${positional}`;return makeGuidanceMessage({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${positional}".`,required:`Use ${getCommand} for one item's full details, or pm context --parent ${positional} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[getCommand,`pm context --parent ${positional}`],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:getCommand})})}function buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context){const message=normalizeMessage(rawMessage);const guidance=buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context)??buildMissingRequiredArgumentGuidance(message,commandName,context)??buildUnknownOptionGuidance(message,commandName,context)??buildUnknownCommandGuidance(message,context)??buildUnknownSubcommandGuidance(context)??buildTransposedCollectionActionGuidance(message,commandName,context)??buildLinkedTestValueNotQuotedGuidance(message,commandName,context)??buildContextItemArgumentGuidance(message,commandName,context);if(guidance){return guidance}return makeGuidanceMessage({code:"invalid_command_usage",title:"Invalid command usage",happened:message,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context)})}function formatPmCliErrorForDisplay(rawMessage,context){const guidance=buildPmCliErrorGuidance(rawMessage,context);if((context?.code==="tracker_root_missing"||context?.code==="tracker_not_initialized")&&guidance.title==="Tracker is not initialized"&&guidance.recovery?.suggested_retry_args){return[`Error: ${guidance.title}`,`Run: ${renderPmCommand(guidance.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join("\n")}return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyPmCliError(rawMessage,context){return guidanceToClassification(buildPmCliErrorGuidance(rawMessage,context))}function formatPmCliErrorForJson(rawMessage,exitCode,context){return projectJsonErrorGuidance(buildPmCliErrorGuidance(rawMessage,context),exitCode)}function formatCommanderErrorForDisplay(rawMessage,commandName,allowedTypes,context){const guidance=buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context);return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyCommanderError(rawMessage,commandName,allowedTypes,context){return guidanceToClassification(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context))}function formatCommanderErrorForJson(rawMessage,commandName,allowedTypes,exitCode,context){return projectJsonErrorGuidance(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context),exitCode)}function formatUnknownErrorForJson(rawMessage,exitCode){const guidance=buildUnknownErrorGuidance(rawMessage);return projectJsonErrorGuidance(guidance,exitCode)}function buildUnknownErrorGuidance(rawMessage){const message=normalizeMessage(rawMessage);if(isModuleResolutionErrorMessage(message)){return makeGuidanceMessage({code:"module_import_failed",title:"Module import failed",happened:message,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]})}return makeGuidanceMessage({code:"unknown_error",title:"Unhandled error",happened:message,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function classifyUnknownError(rawMessage){return guidanceToClassification(buildUnknownErrorGuidance(rawMessage))}const _testOnly={applyPmCliErrorContext,appendIfMissing,buildCommanderRecoveryPayload,buildFallbackTitleFromMessage,commandExampleForRequiredOption,dedupeStrings,guidanceToClassification,guidanceToJsonEnvelope,normalizeRecoveryPayload,renderList,resolveKnownPackageCommandHint};export{_testOnly,buildLinkedTestQuotedRetryCommand,classifyCommanderError,classifyPmCliError,classifyUnknownError,formatCommanderErrorForDisplay,formatCommanderErrorForJson,formatPmCliErrorForDisplay,formatPmCliErrorForJson,formatUnknownErrorForJson,projectLeanErrorEnvelope,renderGuidanceMessage};
2
2
  //# sourceMappingURL=error-guidance.js.map
package/dist/cli/main.js CHANGED
@@ -1,6 +1,6 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="55cf18ea-fea1-5b3e-b10f-46f67f7f482b")}catch(e2){}})();import{Command,CommanderError}from"commander";import{findPmNamespacedCommand,resolvePmCommandOperation}from"../sdk/cli-contracts/command-aliases.js";import{createPmCliProgram}from"../sdk/cli-program.js";import{runWithDiscoveredContextIntentContracts}from"../sdk/context-intent-runtime.js";import{describeUnknownError,isCommanderError,normalizeThrownExitCode,readThrownExitCode,wrapThrownErrorForSentry}from"../sdk/error-runtime.js";import{createExtensionCommandSdk}from"../sdk/extension-command-context.js";import{runExtensionMigrations}from"../sdk/extension/migrations.js";import{applyInvocationAuthorOverride}from"../sdk/invocation-author.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{validateReadOutputOptions}from"../sdk/read-output-contracts.js";import{runWithReproducibleProcessEnvironment}from"../sdk/reproducibility/process.js";import{EXIT_CODE,PmCliError,activateExtensions,clearActiveExtensionHooks,consumeAfterCommandAffectedItems,createCoreCommandHookContext,createEmptyExtensionRegistrationRegistry,createLazyModule,deriveTelemetryCommandResolution,discoverExtensions,emitTelemetryErrorEvent,ensureSentryInit,getActiveCommandResult,getActiveExtensionRegistrations,getSettingsPath,loadExtensions,maybeRunFirstUseTelemetryPrompt,pathExists,printError,printResult,readSettings,readSettingsWithMetadata,resetActiveExtensionRuntimeState,resolveItemTypeRegistry,resolvePmCliVersion,resolvePmPackageRootFromModule,resolvePmRoot,resolveRuntimeFieldRegistry,resolveTelemetryErrorCategory,runActiveCommandHandler,runActiveParserOverride,runActivePreflightOverride,runAfterCommandHooks,runBeforeCommandHooks,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,sentryCaptureCliError,sentryFinishCommandSpan,sentryFlush,sentryLogCliUsageError,sentrySetCommandContext,sentryStartCommandSpan,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices,startTelemetryCommand,writeStderr}from"../sdk/runtime-primitives.js";import{PmClient}from"../sdk/runtime.js";import{finishActiveTelemetryCommand,recordAfterCommandContextUsage}from"./after-command-context-usage.js";import{extractProvidedOptionFlags,normalizeLongOptionFlag,redactSensitiveCommandArgs,renderPmCommand}from"./argv-utils.js";import{applyBootstrapPagerPolicy,findBootstrapCommandTokenIndex,normalizeBootstrapInvocation,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,stripGlobalBootstrapTokens}from"./bootstrap-args.js";import{installCommandNamespaces}from"./command-namespaces.js";import{appendCommanderExtensionFailures,formatCommanderUsageJson,formatCommanderUsageMessage,isKnownHelpCommandPath,resolveCommanderUsageContext,resolveUnknownCommanderToken}from"./commander-usage.js";import{loadContextIntentSnapshotForInvocation}from"./context-intent-invocation.js";import{classifyCommanderError,classifyPmCliError,classifyUnknownError,formatPmCliErrorForDisplay,formatPmCliErrorForJson,formatUnknownErrorForJson,projectLeanErrorEnvelope}from"./error-guidance.js";import{applyDynamicExtensionArguments,applyDynamicExtensionFlagOptions,buildCanonicalExtensionAliases,buildDynamicExtensionCommandMetadataHelp,buildResidualDynamicExtensionFlagHelp,collectDynamicExtensionFlagHelpByCommand,collectExtensionCommandHelpDescriptors,collectSafeExtensionCommandPaths,ensureCommandPath,extensionFlagTakesValueForInvocation,findCommandByPath,normalizeExtensionCommandPath,reportExtensionCommandCollision}from"./extension-command-help.js";import{collectLoosePositionalArgs,stripLooseCommandOptionTokens}from"./extension-command-options.js";import{loadExtensionRecoveryFailures,loadUnknownCommandRecoveryFailures}from"./extension-recovery.js";import{attachRichHelpText,isFullHelpDiscovery,setPmCommandHelpVisibilityTier}from"./help-content.js";import{attachCreateUpdatePolicyHelpText,maybeRenderBootstrapJsonHelp}from"./help-json-payload.js";import{collectMandatoryMigrationBlockers,enforceItemFormatWriteGateAndPreflightMigration,enforceMandatoryMigrationWriteGate,enforceMutationGuardPreflight}from"./migration-gates.js";import{applyDefaultOutputFormat,clearResolvedGlobalOptions,collect,formatHookWarnings,getCommandPath,getGlobalOptions,invalidateSearchCachesForMutation,setResolvedGlobalOptions,syncCommanderActionOptions}from"./registration-helpers.js";import{activationCommandMatchesProbe,buildBootstrapActivationProbe,buildRuntimeExtensionActivationScope,buildRuntimeExtensionFilterForProbe,collectActivationCommandCandidates,collectLeadingCommandArgs,collectParsedActivationCommandArgs,commandPathNeedsSearchExtensions,commandPathNeedsTemplateExtensions,discoveryNeedsActivationForProbe,extensionActivationCommands,extensionCapabilities,extensionNeedsActivationForProbe,extensionProvidesTemplatesRuntime,hasAnyCapability,hasGlobalExtensionContributions,matchesStaticExtensionCommand,probeUsesAnyFlag,resolveStaticExtensionActivationDecision}from"./runtime/activation.js";import{collectExtensionFlagDefinitionsForCommand,collectExtensionFlagDefinitionsForInvocation,dynamicCommandArguments,extractCommandScopedOptions,forwardReadOutputIncludeModes,isImporterOrExporterCommandPath,recordCliReadOutputInvocationProvenance,validateDynamicExtensionCommandArgs,validateDynamicExtensionCommandInvocation}from"./runtime/invocation-options.js";import{LIST_QUERY_COMMAND_NAMES,enforceExplicitRetryForFlagTypos,invocationRequestsVersion,resolveCoreCommandRegistrationSelection,shouldAttachRichHelpTextForInvocation,shouldRegisterDynamicExtensionPaths,shouldRegisterRuntimeSchemaFlags}from"./runtime/selection.js";import{buildPostActionTelemetryOutcome,inferPostActionErrorCode,inferPostActionFailureMessage,normalizeTelemetryCommandResolution,normalizeTelemetryErrorCategory,normalizeTelemetryResolutionStage,readRecordBoolean,readRecordNumber,readRecordString}from"./runtime/telemetry-outcome.js";const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT";function resolvePmPackageRoot(){return resolvePmPackageRootFromModule(import.meta.url,["../.."])}if(typeof process.env[PM_PACKAGE_ROOT_ENV]!=="string"||process.env[PM_PACKAGE_ROOT_ENV]?.trim().length===0){process.env[PM_PACKAGE_ROOT_ENV]=resolvePmPackageRoot()}let activeExtensionHookContext=null;let activeTelemetryCommandContext=null;function setActiveExtensionHookContextForTest(context){activeExtensionHookContext=context}function setActiveRuntimeExtensionCommandDescriptorsForTest(descriptors){activeRuntimeExtensionCommandDescriptors=descriptors}let runtimeExtensionSnapshotCache=null;let runtimeExtensionDiscoverySnapshotCache=null;let activeRuntimeExtensionCommandDescriptors=new Map;const HANDLED_ERROR_SENTRY_FLUSH_TIMEOUT_MS=250;const EXPECTED_HANDLED_ERROR_EXIT_CODES=new Set([EXIT_CODE.USAGE,EXIT_CODE.NOT_FOUND,EXIT_CODE.CONFLICT]);const TRUE_LIKE_ENV_VALUES=new Set(["1","true","yes","on"]);const loadSetupRegistrationModule=createLazyModule(()=>import("./register-setup.js"));const loadListQueryRegistrationModule=createLazyModule(()=>import("./register-list-query.js"));const loadMutationRegistrationModule=createLazyModule(()=>import("./register-mutation.js"));const loadOperationRegistrationModule=createLazyModule(()=>import("./register-operations.js"));function renderAttemptedCommand(argv){return renderPmCommand(argv)}function inferMissingFieldsFromErrorMessage(message){const matches=message.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!matches||matches.length===0){return void 0}const normalized=[...new Set(matches.map(entry=>normalizeLongOptionFlag(entry)??entry))];return normalized.length>0?normalized:void 0}function inferMissingFieldsForRecovery(rawMessage,invocationArgv,existingRecovery){if(existingRecovery?.suggested_retry||rawMessage.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(rawMessage)){return void 0}const providedFields=extractProvidedOptionFlags(invocationArgv);const providedSet=new Set(providedFields.map(flag=>normalizeLongOptionFlag(flag)??flag));const rawInferred=inferMissingFieldsFromErrorMessage(rawMessage);const commandName=invocationArgv.find(token=>program.commands.some(candidate=>candidate.name()===token));const command=commandName?program.commands.find(candidate=>candidate.name()===commandName):void 0;const declaredFlags=new Set([...program.options,...command?.options??[]].flatMap(option=>option.flags.split(/[ ,|]+/).map(flag=>normalizeLongOptionFlag(flag)).filter(flag=>flag!==void 0)));const trulyMissing=rawInferred?.filter(flag=>{const normalized=normalizeLongOptionFlag(flag)??flag;if(providedSet.has(normalized)){return false}return declaredFlags.has(normalized)||extensionFlagTakesValueForInvocation(invocationArgv,commandName,normalized,activeRuntimeExtensionCommandDescriptors)!==void 0});return trulyMissing&&trulyMissing.length>0?trulyMissing:void 0}function resolveRecoverySuggestedRetry(invocationArgv,attemptedCommand,inferredMissing,existingRecovery){if(existingRecovery?.suggested_retry){return existingRecovery.suggested_retry}const missingFlag=inferredMissing?.[0];const normalizedMissing=missingFlag?normalizeLongOptionFlag(missingFlag):void 0;const commandName=invocationArgv.find(token=>program.commands.some(candidate=>candidate.name()===token));const command=commandName?program.commands.find(candidate=>candidate.name()===commandName):void 0;const missingOption=normalizedMissing?command?.options.find(option=>option.flags.split(/[ ,|]+/).includes(normalizedMissing)):void 0;const extensionFlagTakesValue=extensionFlagTakesValueForInvocation(invocationArgv,commandName,normalizedMissing,activeRuntimeExtensionCommandDescriptors);const missingTokens=normalizedMissing?missingOption?.isBoolean()===true||extensionFlagTakesValue===false?[normalizedMissing]:[normalizedMissing,"<value>"]:[];const suggestedRetry=normalizedMissing?renderAttemptedCommand([...invocationArgv,...missingTokens]):attemptedCommand;return suggestedRetry===attemptedCommand?void 0:suggestedRetry}function projectExistingRecoveryOptionalFields(existingRecovery){if(!existingRecovery){return{}}const optionalFields=["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"];const projected={};for(const field of optionalFields){const value=existingRecovery[field];if(value!==void 0&&value!==null){projected[field]=value}}return projected}function buildRecoveryPayload(params){const existingRecovery=params.existingRecovery;return{attempted_command:existingRecovery?.attempted_command??params.attemptedCommand,normalized_args:existingRecovery?.normalized_args??[...params.invocationArgv],provided_fields:existingRecovery?.provided_fields??(params.providedFields.length>0?params.providedFields:void 0),missing:existingRecovery?.missing??params.inferredMissing,...projectExistingRecoveryOptionalFields(existingRecovery),...params.suggestedRetry?{suggested_retry:params.suggestedRetry}:{}}}function buildPmCliRecoveryContext(context,invocationArgv,rawMessage){const safeInvocationArgv=redactSensitiveCommandArgs(invocationArgv);const commandArgs=stripGlobalBootstrapTokens(safeInvocationArgv);const commandIndex=findBootstrapCommandTokenIndex(commandArgs);const[rootCommand,subcommand]=commandIndex===void 0?[]:commandArgs.slice(commandIndex,commandIndex+2);const explainRequested=safeInvocationArgv.includes("--explain");const rawExistingRecovery=context?.recovery;const existingRecovery=rawExistingRecovery&&(rootCommand==="history-redact"||rootCommand==="history"&&subcommand==="redact")?{...rawExistingRecovery,...rawExistingRecovery.attempted_command?{attempted_command:renderAttemptedCommand(safeInvocationArgv)}:{},...rawExistingRecovery.normalized_args?{normalized_args:[...safeInvocationArgv]}:{},...rawExistingRecovery.suggested_retry?{suggested_retry:renderAttemptedCommand(safeInvocationArgv)}:{},...rawExistingRecovery.suggested_retry_args?{suggested_retry_args:[...safeInvocationArgv]}:{}}:rawExistingRecovery;if(existingRecovery?.recovery_mode==="compact"&&!explainRequested){return{...context,recovery:existingRecovery}}const attemptedCommand=renderAttemptedCommand(safeInvocationArgv);const providedFields=extractProvidedOptionFlags(safeInvocationArgv);const inferredMissing=inferMissingFieldsForRecovery(rawMessage,safeInvocationArgv,existingRecovery);const suggestedRetry=resolveRecoverySuggestedRetry(safeInvocationArgv,attemptedCommand,inferredMissing,existingRecovery);const recovery=buildRecoveryPayload({invocationArgv:safeInvocationArgv,attemptedCommand,providedFields,inferredMissing,suggestedRetry,existingRecovery});return{...context,recovery}}async function runAndClearAfterCommandHooks(outcome){const telemetryRuntime=activeTelemetryCommandContext;activeTelemetryCommandContext=null;await finishActiveTelemetryCommand(telemetryRuntime,outcome);const runtime=activeExtensionHookContext;activeExtensionHookContext=null;if(!runtime){clearActiveExtensionHooks();return}let hookWarnings=[];const affected=consumeAfterCommandAffectedItems();try{await recordAfterCommandContextUsage({pmRoot:runtime.pmRoot,author:runtime.globalOptions.author,itemIds:outcome.ok?affected?.map(item=>item.id)??[]:[],intent:runtime.commandName})}catch{hookWarnings.push("context_usage_feedback_write_failed")}try{hookWarnings.push(...await runAfterCommandHooks(runtime.hooks,{command:runtime.commandName,args:runtime.commandArgs,options:{...runtime.commandOptions},global:{...runtime.globalOptions},pm_root:runtime.pmRoot,ok:outcome.ok,error:outcome.error,result:getActiveCommandResult(),affected}))}catch(error){const message=error instanceof Error?error.message:String(error);hookWarnings=[`afterCommand hooks failed: ${message}`]}finally{clearActiveExtensionHooks()}if(!runtime.globalOptions.json&&hookWarnings.length>0){printError(`[pm] warning: afterCommand hook_warnings=${formatHookWarnings(hookWarnings)}`)}if(runtime.profileEnabled&&hookWarnings.length>0){printError(`profile:extensions hook_warnings=${formatHookWarnings(hookWarnings)}`)}}async function ensureSentryForErrorReporting(){await ensureSentryInit()}function envFlagEnabled(key){return TRUE_LIKE_ENV_VALUES.has((process.env[key]??"").trim().toLowerCase())}function shouldLogHandledErrorToSentry(exitCode){if(envFlagEnabled("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")){return true}return!EXPECTED_HANDLED_ERROR_EXIT_CODES.has(Math.trunc(exitCode))}async function maybeLogHandledCliErrorToSentry(params){if(!shouldLogHandledErrorToSentry(params.exit_code)){return false}await ensureSentryForErrorReporting();sentryLogCliUsageError(params);return true}async function handleGenericRunPmCliError(params){const message=describeUnknownError(params.error);const classification=classifyUnknownError(message);if(params.bootstrapGlobal.json){printError(JSON.stringify(formatUnknownErrorForJson(message,EXIT_CODE.GENERIC_FAILURE),null,2))}else{printError(message)}process.exitCode=EXIT_CODE.GENERIC_FAILURE;let errorCategory="runtime";let commandResolution="runtime_failed";try{await ensureSentryForErrorReporting();sentryCaptureCliError(params.error);const telemetry=await params.emitTelemetryCommandError({command:params.attemptedCommand,errorCode:classification.code,errorMessage:classification.detail,exitCode:EXIT_CODE.GENERIC_FAILURE,options:{bootstrap_global_options:params.bootstrapGlobal},resolutionStage:"execute"});errorCategory=telemetry.errorCategory;commandResolution=telemetry.commandResolution;sentryFinishCommandSpan(false,message,{error_code:classification.code,error_category:errorCategory,exit_code:EXIT_CODE.GENERIC_FAILURE,command_resolution:commandResolution,resolution_stage:"execute"})}catch(reportingError){if(!params.bootstrapGlobal.json){printError(`Failed to report error: ${describeUnknownError(reportingError)}`)}}try{await runAndClearAfterCommandHooks({ok:false,error:message,exit_code:EXIT_CODE.GENERIC_FAILURE,error_code:classification.code,error_category:errorCategory,command_resolution:commandResolution,resolution_stage:"execute"})}catch(hookError){if(!params.bootstrapGlobal.json){printError(`Failed to run error hooks: ${describeUnknownError(hookError)}`)}}try{await sentryFlush()}catch(flushError){if(!params.bootstrapGlobal.json){printError(`Failed to flush error reporting: ${describeUnknownError(flushError)}`)}}}const RUNTIME_FIELD_COMMAND_BY_COMMAND_PATH={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"};const runtimeFieldLooseFlagDefinitionCache=new Map;function toLooseFieldDefinitionType(fieldType){if(fieldType==="number"){return"number"}if(fieldType==="boolean"){return"boolean"}return"string"}function commandHasLongOption(command,longFlag){return command.options.some(option=>option.long===longFlag)}function commandHasShortOption(command,shortFlag){return command.options.some(option=>option.short===shortFlag)}function addRuntimeFieldOption(command,flagToken,description,repeatable){const normalizedToken=flagToken.trim();if(!normalizedToken){return}const helpText=description.length>0?description:`Runtime schema field (${flagToken})`;if(normalizedToken.startsWith("-")&&!normalizedToken.startsWith("--")){if(commandHasShortOption(command,normalizedToken)){return}if(repeatable){command.option(`${normalizedToken} <value>`,`${helpText} (repeatable)`,collect);return}command.option(`${normalizedToken} <value>`,helpText);return}const longFlag=normalizedToken.startsWith("--")?normalizedToken:`--${normalizedToken}`;if(commandHasLongOption(command,longFlag)){return}if(repeatable){command.option(`${longFlag} <value>`,`${helpText} (repeatable)`,collect);return}command.option(`${longFlag} <value>`,helpText)}async function collectRuntimeFieldLooseFlagDefinitionsForCommand(commandPath,pmRoot){const runtimeCommand=RUNTIME_FIELD_COMMAND_BY_COMMAND_PATH[commandPath];if(!runtimeCommand){return[]}const cacheKey=`${pmRoot}:${runtimeCommand}`;const cached=runtimeFieldLooseFlagDefinitionCache.get(cacheKey);if(cached){return cached}if(!await pathExists(getSettingsPath(pmRoot))){runtimeFieldLooseFlagDefinitionCache.set(cacheKey,[]);return[]}const settings=await readSettings(pmRoot);const fieldRegistry=resolveRuntimeFieldRegistry(settings.schema);const definitions=(fieldRegistry.command_to_fields.get(runtimeCommand)??[]).flatMap(field=>{const flagTokens=[field.cli_flag,...field.cli_aliases];return flagTokens.map(token=>({long:`--${token}`,type:toLooseFieldDefinitionType(field.type),value_type:toLooseFieldDefinitionType(field.type)}))});runtimeFieldLooseFlagDefinitionCache.set(cacheKey,definitions);return definitions}async function registerRuntimeSchemaFieldFlags(rootProgram,invocationArgv){const bootstrapGlobalOptions=parseBootstrapGlobalOptions(invocationArgv);const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobalOptions.path);if(!await pathExists(getSettingsPath(pmRoot))){return}const cachedDiscovery=runtimeExtensionDiscoverySnapshotCache?.key===buildRuntimeExtensionDiscoverySnapshotCacheKey(pmRoot)?runtimeExtensionDiscoverySnapshotCache.snapshot:null;const settings=cachedDiscovery===null?await readSettings(pmRoot):cachedDiscovery.settings;const fieldRegistry=resolveRuntimeFieldRegistry(settings.schema);const mappings=[{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 mapping of mappings){const command=findCommandByPath(rootProgram,mapping.path.split(" "));if(!command){continue}for(const field of fieldRegistry.command_to_fields.get(mapping.command)??[]){const description=field.description??"";addRuntimeFieldOption(command,field.cli_flag,description,field.repeatable);for(const alias of field.cli_aliases){addRuntimeFieldOption(command,alias,`Alias for --${field.cli_flag}`,field.repeatable)}}}}async function maybeAttachCreateUpdatePolicyHelpText(rootProgram,pmRoot,invocationArgv,registrations,settings){const bootstrapCommand=parseBootstrapCommandName(invocationArgv);if(bootstrapCommand!=="create"&&bootstrapCommand!=="update"){return}try{const resolvedSettings=settings??await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(resolvedSettings,registrations);attachCreateUpdatePolicyHelpText(rootProgram,typeRegistry,invocationArgv)}catch{}}function defaultPreflightDecision(){return{enforce_item_format_gate:true,run_preflight_item_format_sync:true,run_extension_migrations:true,enforce_mandatory_migration_gate:true}}function buildRuntimeExtensionSnapshotCacheKey(pmRoot,activationScope="all"){return activationScope==="all"?`pm-root:${pmRoot}`:`pm-root:${pmRoot}:activation:${activationScope}`}function bootstrapProfileEnabled(invocationArgv){return invocationArgv.some(token=>token==="--profile")}function buildRuntimeExtensionDiscoverySnapshotCacheKey(pmRoot){return`pm-root:${pmRoot}`}function emitSettingsReadWarnings(warnings){for(const warning of warnings){if(warning.startsWith("settings_read_")){printError(`[pm] warning: ${warning} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}}}function emitExtensionProfile(globalOptions,snapshot){if(!globalOptions.profile){return}printError(`profile:extensions loaded=${snapshot.loadedCount} failed=${snapshot.loadFailedCount} warnings=${snapshot.loadWarnings.length} activation_failed=${snapshot.activationFailedCount} hook_counts=before:${snapshot.hooks.beforeCommand.length}|after:${snapshot.hooks.afterCommand.length}|write:${snapshot.hooks.onWrite.length}|read:${snapshot.hooks.onRead.length}|index:${snapshot.hooks.onIndex.length} command_overrides=${snapshot.commands.overrides.length} command_handlers=${snapshot.commands.handlers.length} parser_overrides=${snapshot.parsers.overrides.length} preflight_overrides=${snapshot.preflight.overrides.length} service_overrides=${snapshot.services.overrides.length} renderer_overrides=${snapshot.renderers.overrides.length}`);if(snapshot.activationWarnings.length>0){printError(`profile:extensions activation_warnings=${formatHookWarnings(snapshot.activationWarnings)}`)}}function emitExtensionSkippedProfile(profileEnabled,snapshot,probe){if(!profileEnabled){return}const command=normalizeExtensionCommandPath(probe.commandPath??"")||"<none>";printError(`profile:extensions activation=skipped command=${command} effective=${snapshot.discovery.effective.length} warnings=${snapshot.discovery.warnings.length} discovery_ms=${snapshot.discoveryMs}`)}async function loadRuntimeExtensionDiscoverySnapshot(pmRoot,readSettingsWithMetadataFn=readSettingsWithMetadata){const cacheKey=buildRuntimeExtensionDiscoverySnapshotCacheKey(pmRoot);if(runtimeExtensionDiscoverySnapshotCache?.key===cacheKey){return runtimeExtensionDiscoverySnapshotCache.snapshot}try{const startedAt=Date.now();const{settings,warnings:settingsReadWarnings}=await readSettingsWithMetadataFn(pmRoot);const discovery=await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:false});const snapshot={pmRoot,settings,discovery,discoveryMs:Date.now()-startedAt,settingsReadWarnings:[...settingsReadWarnings]};runtimeExtensionDiscoverySnapshotCache={key:cacheKey,snapshot};return snapshot}catch{runtimeExtensionDiscoverySnapshotCache={key:cacheKey,snapshot:null};return null}}async function loadRuntimeExtensionSnapshot(pmRoot,probe,readSettingsFn=readSettings){const activationScope=probe?buildRuntimeExtensionActivationScope(probe):"all";const cacheKey=buildRuntimeExtensionSnapshotCacheKey(pmRoot,activationScope);if(runtimeExtensionSnapshotCache?.key===cacheKey){return runtimeExtensionSnapshotCache.snapshot}try{const settings=await readSettingsFn(pmRoot);const loadResult=await loadExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:false,extensionFilter:probe?buildRuntimeExtensionFilterForProbe(probe):void 0});const activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});const commandHandlers=[...new Set(activationResult.commands.handlers.map(entry=>normalizeExtensionCommandPath(entry.command)))].filter(entry=>entry.length>0).sort((left,right)=>left.localeCompare(right));const commandFlagHelp=collectDynamicExtensionFlagHelpByCommand(activationResult.registrations.flags);const canonicalAliases=buildCanonicalExtensionAliases(activationResult.commands.handlers,activationResult.registrations.commands);const commandDescriptors=collectExtensionCommandHelpDescriptors(commandHandlers,activationResult.registrations.commands,activationResult.registrations.flags,canonicalAliases);const snapshot={hooks:activationResult.hooks,commands:activationResult.commands,parsers:activationResult.parsers,preflight:activationResult.preflight,services:activationResult.services,renderers:activationResult.renderers,registrations:activationResult.registrations,pmRoot,settings,commandHandlers,commandFlagHelp,commandDescriptors,commandAliases:canonicalAliases,loadWarnings:[...loadResult.warnings],activationWarnings:[...activationResult.warnings],loadedCount:loadResult.loaded.length,loadFailedCount:loadResult.failed.length,activationFailedCount:activationResult.failed.length,contextIntentPackages:loadResult.loaded.map(({name,module})=>({name,module}))};runtimeExtensionSnapshotCache={key:cacheKey,snapshot};return snapshot}catch{runtimeExtensionSnapshotCache={key:cacheKey,snapshot:null};return null}}async function maybeLoadRuntimeExtensions(command){const globalOptions=getGlobalOptions(command);if(globalOptions.noExtensions){const noExtPmRoot=resolvePmRoot(process.cwd(),globalOptions.path);if(await pathExists(getSettingsPath(noExtPmRoot))){emitSettingsReadWarnings((await readSettingsWithMetadata(noExtPmRoot)).warnings)}return null}const pmRoot=resolvePmRoot(process.cwd(),globalOptions.path);const discoverySnapshot=await loadRuntimeExtensionDiscoverySnapshot(pmRoot);if(!discoverySnapshot){return null}emitSettingsReadWarnings(discoverySnapshot.settingsReadWarnings);const probe={commandPath:getCommandPath(command),commandArgs:collectParsedActivationCommandArgs(command)};if(!discoveryNeedsActivationForProbe(discoverySnapshot.discovery,probe)){emitExtensionSkippedProfile(globalOptions.profile,discoverySnapshot,probe);return null}const snapshot=await loadRuntimeExtensionSnapshot(pmRoot,probe);if(!snapshot){return null}emitExtensionProfile(globalOptions,snapshot);return{hooks:snapshot.hooks,commands:snapshot.commands,parsers:snapshot.parsers,preflight:snapshot.preflight,services:snapshot.services,renderers:snapshot.renderers,registrations:snapshot.registrations,pmRoot}}async function loadRuntimeExtensionCommandDescriptorsForRecovery(pmRoot){const snapshot=await loadRuntimeExtensionSnapshot(pmRoot);return snapshot?new Map(snapshot.commandDescriptors):activeRuntimeExtensionCommandDescriptors}async function executeRegisteredRuntimeMigrations(migrations,pmRoot){const result=await runExtensionMigrations({pmRoot,migrations,author:"pm-extension-migration"});return result.migrations.filter(migration=>migration.outcome==="failed").map(migration=>`extension_migration_failed:${migration.layer}:${migration.extension}:${migration.id}`)}function buildExtensionCommandSdk(pmRoot,global2){const author=typeof global2.author==="string"&&global2.author.trim()?global2.author.trim():"pm-extension";return createExtensionCommandSdk(pmRoot,PmClient.forActiveExtensionHost({pmRoot,author}))}async function runRequiredExtensionCommand(command,options,globalOptions,extensionFlagDefinitions=[]){const commandPath=getCommandPath(command);let commandArgs=stripLooseCommandOptionTokens(command.args.map(String),extensionFlagDefinitions);let commandOptions={...options};let resolvedGlobalOptions={...globalOptions};const pmRoot=resolvePmRoot(process.cwd(),globalOptions.path);const parserOverride=await runActiveParserOverride({command:commandPath,args:commandArgs,options:commandOptions,global:resolvedGlobalOptions,pm_root:pmRoot});if(globalOptions.profile&&parserOverride.warnings.length>0){printError(`profile:extensions parser_warnings=${formatHookWarnings(parserOverride.warnings)}`)}commandArgs=parserOverride.context.args;commandOptions=parserOverride.context.options;resolvedGlobalOptions=parserOverride.context.global;validateDynamicExtensionCommandInvocation(activeRuntimeExtensionCommandDescriptors.get(normalizeExtensionCommandPath(commandPath)),commandArgs,commandOptions,extensionFlagDefinitions);setActiveCommandResult(void 0);setActiveCommandContext({command:commandPath,args:commandArgs,options:{...commandOptions},global:{...resolvedGlobalOptions},pm_root:pmRoot});const extensionCommandResult=await runActiveCommandHandler({command:commandPath,args:commandArgs,options:commandOptions,global:resolvedGlobalOptions,pm_root:pmRoot,sdk:buildExtensionCommandSdk(pmRoot,resolvedGlobalOptions)});if(resolvedGlobalOptions.profile&&extensionCommandResult.warnings.length>0){printError(`profile:extensions command_handler_warnings=${formatHookWarnings(extensionCommandResult.warnings)}`)}if(!extensionCommandResult.handled){if(extensionCommandResult.warnings.length>0){const warningCode=extensionCommandResult.warnings[0];const cause=extensionCommandResult.errorMessage?.trim();const causeSuffix=cause?` ${cause}`:"";throw new PmCliError(`Command "${commandPath}" failed in extension handler (${warningCode}).${causeSuffix}`,EXIT_CODE.GENERIC_FAILURE,{code:extensionCommandResult.errorCode??"command_failed",nextSteps:extensionCommandResult.remediation?[extensionCommandResult.remediation]:void 0})}throw new PmCliError(`Command "${commandPath}" is provided by extensions and is not currently available.`,EXIT_CODE.NOT_FOUND)}if(extensionCommandResult.exitCode!==void 0){process.exitCode=extensionCommandResult.exitCode}setActiveCommandResult(extensionCommandResult.result);return extensionCommandResult.result}const WRAPPED_ACTION_HANDLER=Symbol("pm.wrappedActionHandler");function resolveActionCommand(actionArgs,fallback){const possibleCommand=actionArgs[actionArgs.length-1];return possibleCommand instanceof Command?possibleCommand:fallback}function maybePrintExtensionProfileWarnings(enabled,label,warnings){if(enabled&&warnings.length>0){printError(`profile:extensions ${label}=${formatHookWarnings(warnings)}`)}}function validateDynamicInvocationArgs(params){const dynamicDescriptor=activeRuntimeExtensionCommandDescriptors.get(normalizeExtensionCommandPath(params.commandPath));if(!dynamicDescriptor||!isImporterOrExporterCommandPath(params.activeRegistrations,params.commandPath)){return}const positionalArgs=dynamicCommandArguments(dynamicDescriptor).length===0?collectLoosePositionalArgs(params.commandArgs):stripLooseCommandOptionTokens(params.commandArgs,params.extensionFlagDefinitions);validateDynamicExtensionCommandArgs(dynamicDescriptor,positionalArgs)}function syncCommanderActionArgs(actionCommand,actionArgs,commandArgs){actionCommand.args=[...commandArgs];if("_processArguments"in actionCommand&&typeof actionCommand._processArguments==="function"){actionCommand._processArguments()}if(actionArgs.length>0&&Array.isArray(actionArgs[0])){actionArgs[0]=[...actionCommand.processedArgs]}}function wrapProgramActionsForExtensionHandlers(rootProgram){const visit=entry=>{const actionEntry=entry;if(typeof actionEntry._actionHandler==="function"&&actionEntry[WRAPPED_ACTION_HANDLER]!==true){const originalAction=actionEntry._actionHandler;actionEntry._actionHandler=async function wrappedActionHandler(...actionArgs){const actionCommand=resolveActionCommand(actionArgs,entry);const startedAt=Date.now();clearResolvedGlobalOptions(actionCommand);let globalOptions=getGlobalOptions(actionCommand);const commandPath=resolvePmCommandOperation(getCommandPath(actionCommand));const pmRoot=resolvePmRoot(process.cwd(),globalOptions.path);let commandArgs=actionCommand.args.map(String);const activeRegistrations=getActiveExtensionRegistrations();const extensionFlagDefinitions=activeRegistrations?collectExtensionFlagDefinitionsForInvocation(activeRegistrations,commandPath,commandArgs):[];const runtimeFieldFlagDefinitions=await collectRuntimeFieldLooseFlagDefinitionsForCommand(commandPath,pmRoot);let commandOptions=extractCommandScopedOptions(actionCommand,commandArgs,[...extensionFlagDefinitions,...runtimeFieldFlagDefinitions]);const parserOverride=await runActiveParserOverride({command:commandPath,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:pmRoot});maybePrintExtensionProfileWarnings(globalOptions.profile,"parser_warnings",parserOverride.warnings);commandArgs=parserOverride.context.args;commandOptions=parserOverride.context.options;globalOptions=parserOverride.context.global;validateDynamicInvocationArgs({activeRegistrations,commandPath,commandArgs,extensionFlagDefinitions});globalOptions=await applyDefaultOutputFormat(globalOptions);setResolvedGlobalOptions(actionCommand,globalOptions);syncCommanderActionArgs(actionCommand,actionArgs,commandArgs);syncCommanderActionOptions(actionCommand,commandOptions);setActiveCommandResult(void 0);setActiveCommandContext({command:commandPath,args:commandArgs,options:{...commandOptions},global:{...globalOptions},pm_root:pmRoot});const extensionCommandResult=await runActiveCommandHandler({command:commandPath,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:pmRoot,sdk:buildExtensionCommandSdk(pmRoot,globalOptions)});maybePrintExtensionProfileWarnings(globalOptions.profile,"command_handler_warnings",extensionCommandResult.warnings);if(extensionCommandResult.handled){setActiveCommandResult(extensionCommandResult.result);printResult(extensionCommandResult.result,{...globalOptions,command:commandPath,commandArgs,commandOptions,pmRoot});if(globalOptions.profile){printError(`profile:command=${commandPath} took_ms=${Date.now()-startedAt}`)}return}return await originalAction.apply(this,actionArgs)};actionEntry[WRAPPED_ACTION_HANDLER]=true}for(const child of entry.commands){visit(child)}};visit(rootProgram)}async function clearDynamicExtensionCommandState(params){activeRuntimeExtensionCommandDescriptors=new Map;setActiveExtensionServices({overrides:[]});if(params){await maybeAttachCreateUpdatePolicyHelpText(params.rootProgram,params.pmRoot,params.invocationArgv,createEmptyExtensionRegistrationRegistry(),params.settings)}}function attachDynamicExtensionHelp(command,descriptor,flagHelp,metadataHelp){if(descriptor?.flags&&descriptor.flags.length>0){applyDynamicExtensionFlagOptions(command,descriptor.flags);const residualFlagHelp=buildResidualDynamicExtensionFlagHelp(command,descriptor.flags);if(residualFlagHelp){command.addHelpText("after",residualFlagHelp)}}else if(flagHelp){command.addHelpText("after",flagHelp)}if(metadataHelp){command.addHelpText("after",metadataHelp)}}function applyDynamicExtensionRootHelpVisibility(rootProgram,preexistingTopLevelCommands,descriptors){const tierRank={core:0,standard:1,full:2,internal:3};const applyVisibility=(command,pathParts)=>{const commandPath=pathParts.join(" ");const matchingDescriptors=[...descriptors.entries()].filter(([path])=>path===commandPath||path.startsWith(`${commandPath} `)).map(([,descriptor])=>descriptor);const tier=matchingDescriptors.length===0?"standard":matchingDescriptors.reduce((selected,descriptor)=>tierRank[descriptor.tier]<tierRank[selected]?descriptor.tier:selected,"internal");setPmCommandHelpVisibilityTier(command,tier);for(const child of command.commands){applyVisibility(child,[...pathParts,child.name()])}};for(const command of rootProgram.commands){if(!preexistingTopLevelCommands.has(command.name())){applyVisibility(command,[command.name()])}}}async function registerDynamicExtensionCommandPaths(rootProgram,invocationArgv){const bootstrapGlobalOptions=parseBootstrapGlobalOptions(invocationArgv);const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobalOptions.path);if(bootstrapGlobalOptions.noExtensions){await clearDynamicExtensionCommandState({rootProgram,pmRoot,invocationArgv});return}const discoverySnapshot=await loadRuntimeExtensionDiscoverySnapshot(pmRoot);const probe=buildBootstrapActivationProbe(invocationArgv);if(!discoverySnapshot){await clearDynamicExtensionCommandState();return}if(!discoveryNeedsActivationForProbe(discoverySnapshot.discovery,probe)){await clearDynamicExtensionCommandState({rootProgram,pmRoot,invocationArgv,settings:discoverySnapshot.settings});emitExtensionSkippedProfile(bootstrapProfileEnabled(invocationArgv),discoverySnapshot,probe);return}const snapshot=await loadRuntimeExtensionSnapshot(pmRoot,probe);if(!snapshot){await clearDynamicExtensionCommandState({rootProgram,pmRoot,invocationArgv,settings:discoverySnapshot.settings});return}setActiveExtensionServices(snapshot.services);activeRuntimeExtensionCommandDescriptors=new Map(snapshot.commandDescriptors);await maybeAttachCreateUpdatePolicyHelpText(rootProgram,pmRoot,invocationArgv,snapshot.registrations,snapshot.settings);const commandPaths=collectSafeExtensionCommandPaths(rootProgram,snapshot.commandHandlers,snapshot.commandDescriptors,snapshot.commandAliases,warning=>reportExtensionCommandCollision(snapshot.activationWarnings,printError,warning));const preexistingTopLevelCommands=new Set(rootProgram.commands.map(command=>command.name()));const registerCommandPath=commandPath=>{const pathParts=commandPath.split(" ").filter(part=>part.length>0);const descriptor=snapshot.commandDescriptors.get(commandPath);const existingCommand=findCommandByPath(rootProgram,pathParts);const flagHelp=snapshot.commandFlagHelp.get(commandPath);const metadataHelp=descriptor?buildDynamicExtensionCommandMetadataHelp(descriptor):null;if(existingCommand){attachDynamicExtensionHelp(existingCommand,descriptor,flagHelp,metadataHelp);return}const dynamicCommand=ensureCommandPath(rootProgram,pathParts);if(descriptor?.description){dynamicCommand.description(descriptor.description)}let residualDynamicFlagHelp=flagHelp;if(descriptor){applyDynamicExtensionArguments(dynamicCommand,descriptor);if(descriptor.flags.length>0){applyDynamicExtensionFlagOptions(dynamicCommand,descriptor.flags);residualDynamicFlagHelp=buildResidualDynamicExtensionFlagHelp(dynamicCommand,descriptor.flags)??void 0}}if(residualDynamicFlagHelp){dynamicCommand.addHelpText("after",residualDynamicFlagHelp)}if(metadataHelp){dynamicCommand.addHelpText("after",metadataHelp)}dynamicCommand.allowUnknownOption(true).allowExcessArguments(true).action(async(...actionArgs)=>{const maybeCommand=actionArgs[actionArgs.length-1];const command=maybeCommand instanceof Command?maybeCommand:dynamicCommand;const globalOptions=getGlobalOptions(command);const startedAt=Date.now();const extensionFlagDefinitions=collectExtensionFlagDefinitionsForInvocation(snapshot.registrations,commandPath,command.args.map(String));const scopedOptions=extractCommandScopedOptions(command,command.args.map(String),extensionFlagDefinitions);const result=await runRequiredExtensionCommand(command,scopedOptions,globalOptions,extensionFlagDefinitions);await invalidateSearchCachesForMutation(globalOptions,result);printResult(result,{...globalOptions,command:commandPath,commandArgs:command.args.map(String),commandOptions:scopedOptions,pmRoot});if(globalOptions.profile){printError(`profile:command=${commandPath} took_ms=${Date.now()-startedAt}`)}})};for(const commandPath of commandPaths){registerCommandPath(commandPath)}applyDynamicExtensionRootHelpVisibility(rootProgram,preexistingTopLevelCommands,snapshot.commandDescriptors)}const CLI_VERSION=resolvePmCliVersion(import.meta.url,["../.."])??"0.0.0";let program=createPmCliProgram(CLI_VERSION);function attachProgramLifecycleHooks(rootProgram){rootProgram.hook("preAction",async(_thisCommand,actionCommand)=>{activeExtensionHookContext=null;activeTelemetryCommandContext=null;clearActiveExtensionHooks();clearResolvedGlobalOptions(actionCommand);const rawGlobalOptions=actionCommand.optsWithGlobals();const bootstrapGlobalOptions=getGlobalOptions(actionCommand);const commandPath=resolvePmCommandOperation(getCommandPath(actionCommand));let commandArgs=actionCommand.args.map(String);let commandOptions=extractCommandScopedOptions(actionCommand,commandArgs);let globalOptions={...bootstrapGlobalOptions};validateReadOutputOptions(commandPath,{...commandOptions,outputInclude:rawGlobalOptions.outputInclude,outputLimit:rawGlobalOptions.outputLimit,outputBudget:rawGlobalOptions.outputBudget,outputFormat:rawGlobalOptions.outputFormat,outputSession:rawGlobalOptions.outputSession,outputCursor:rawGlobalOptions.outputCursor});forwardReadOutputIncludeModes(actionCommand,commandPath,globalOptions,commandOptions);await maybeRunFirstUseTelemetryPrompt(commandPath,globalOptions);const fallbackPmRoot=resolvePmRoot(process.cwd(),bootstrapGlobalOptions.path);const runtimeExtensions=await maybeLoadRuntimeExtensions(actionCommand);if(!runtimeExtensions){activeExtensionHookContext=createCoreCommandHookContext({commandName:commandPath,commandArgs,commandOptions,globalOptions,pmRoot:fallbackPmRoot});activeTelemetryCommandContext=await startTelemetryCommand({command:commandPath,pm_version:CLI_VERSION,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:fallbackPmRoot});sentrySetCommandContext(commandPath,commandArgs,commandOptions,{source_context:activeTelemetryCommandContext?.source_context,source_context_source:activeTelemetryCommandContext?.source_context_source});sentryStartCommandSpan(commandPath);await enforceItemFormatWriteGateAndPreflightMigration(commandPath,commandOptions,fallbackPmRoot,defaultPreflightDecision());await enforceMutationGuardPreflight(commandPath,commandArgs,commandOptions,globalOptions,fallbackPmRoot);return}setActiveExtensionHooks(runtimeExtensions.hooks);setActiveExtensionCommands(runtimeExtensions.commands);setActiveExtensionParsers(runtimeExtensions.parsers);setActiveExtensionPreflight(runtimeExtensions.preflight);setActiveExtensionServices(runtimeExtensions.services);setActiveExtensionRenderers(runtimeExtensions.renderers);setActiveExtensionRegistrations(runtimeExtensions.registrations);const extensionFlagDefinitions=collectExtensionFlagDefinitionsForInvocation(runtimeExtensions.registrations,commandPath,commandArgs);commandOptions=extractCommandScopedOptions(actionCommand,commandArgs,extensionFlagDefinitions);forwardReadOutputIncludeModes(actionCommand,commandPath,globalOptions,commandOptions);const parserOverride=await runActiveParserOverride({command:commandPath,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:runtimeExtensions.pmRoot});if(globalOptions.profile&&parserOverride.warnings.length>0){printError(`profile:extensions parser_warnings=${formatHookWarnings(parserOverride.warnings)}`)}commandArgs=parserOverride.context.args;commandOptions=parserOverride.context.options;globalOptions=parserOverride.context.global;syncCommanderActionOptions(actionCommand,commandOptions);const preflightOverride=await runActivePreflightOverride({command:commandPath,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:runtimeExtensions.pmRoot,decision:defaultPreflightDecision()});if(globalOptions.profile&&preflightOverride.warnings.length>0){printError(`profile:extensions preflight_warnings=${formatHookWarnings(preflightOverride.warnings)}`)}commandArgs=preflightOverride.context.args;commandOptions=preflightOverride.context.options;globalOptions=preflightOverride.context.global;syncCommanderActionOptions(actionCommand,commandOptions);const preflightDecision=preflightOverride.decision;await enforceItemFormatWriteGateAndPreflightMigration(commandPath,commandOptions,runtimeExtensions.pmRoot,preflightDecision);await enforceMutationGuardPreflight(commandPath,commandArgs,commandOptions,globalOptions,runtimeExtensions.pmRoot);const migrationWarnings=preflightDecision.run_extension_migrations?await executeRegisteredRuntimeMigrations(runtimeExtensions.registrations.migrations,runtimeExtensions.pmRoot):[];if(globalOptions.profile&&migrationWarnings.length>0){printError(`profile:extensions migration_warnings=${formatHookWarnings(migrationWarnings)}`)}const migrationBlockers=collectMandatoryMigrationBlockers(runtimeExtensions.registrations.migrations);activeExtensionHookContext={hooks:runtimeExtensions.hooks,commandName:commandPath,commandArgs,commandOptions:{...commandOptions},globalOptions:{...globalOptions},pmRoot:runtimeExtensions.pmRoot,profileEnabled:Boolean(globalOptions.profile),migrationBlockers};setActiveCommandResult(void 0);setActiveCommandContext({command:commandPath,args:commandArgs,options:{...commandOptions},global:{...globalOptions},pm_root:runtimeExtensions.pmRoot});activeTelemetryCommandContext=await startTelemetryCommand({command:commandPath,pm_version:CLI_VERSION,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:runtimeExtensions.pmRoot});sentrySetCommandContext(commandPath,commandArgs,commandOptions,{source_context:activeTelemetryCommandContext?.source_context,source_context_source:activeTelemetryCommandContext?.source_context_source});sentryStartCommandSpan(commandPath);const hookWarnings=await runBeforeCommandHooks(runtimeExtensions.hooks,{command:commandPath,args:commandArgs,options:{...commandOptions},global:{...globalOptions},pm_root:runtimeExtensions.pmRoot});if(globalOptions.profile&&hookWarnings.length>0){printError(`profile:extensions hook_warnings=${formatHookWarnings(hookWarnings)}`)}if(preflightDecision.enforce_mandatory_migration_gate){enforceMandatoryMigrationWriteGate(commandPath,commandOptions,migrationBlockers)}});rootProgram.hook("postAction",async()=>{const outcome=buildPostActionTelemetryOutcome();sentryFinishCommandSpan(outcome.ok,outcome.error,{error_code:outcome.error_code,error_category:outcome.error_category,exit_code:outcome.exit_code,command_resolution:outcome.command_resolution,resolution_stage:outcome.resolution_stage});await runAndClearAfterCommandHooks(outcome)})}attachProgramLifecycleHooks(program);const IDEMPOTENT_TOP_LEVEL_REGISTRATION=Symbol("pmCliIdempotentTopLevelRegistration");function ensureIdempotentTopLevelCommandRegistration(rootProgram){const guarded=rootProgram;if(guarded[IDEMPOTENT_TOP_LEVEL_REGISTRATION]){return}guarded[IDEMPOTENT_TOP_LEVEL_REGISTRATION]=true;const registerOriginalCommand=rootProgram.command.bind(rootProgram);rootProgram.command=((nameAndArgs,...rest)=>{const commandName=nameAndArgs.split(/\s+/u)[0];if(rootProgram.commands.some(existing=>existing.name()===commandName||existing.aliases().includes(commandName))){return new Command(commandName)}return registerOriginalCommand(nameAndArgs,...rest)})}async function registerCoreCommandFamilies(rootProgram,selection){ensureIdempotentTopLevelCommandRegistration(rootProgram);if(selection.setup){const{registerSetupCommands}=await loadSetupRegistrationModule();registerSetupCommands(rootProgram)}if(selection.listQuery){const{registerListQueryCommands}=await loadListQueryRegistrationModule();const commandFilter=typeof selection.targetCommandName==="string"&&LIST_QUERY_COMMAND_NAMES.has(selection.targetCommandName)?new Set([selection.targetCommandName]):void 0;registerListQueryCommands(rootProgram,commandFilter?{commandFilter}:void 0)}if(selection.mutation){const{registerMutationCommands}=await loadMutationRegistrationModule();registerMutationCommands(rootProgram,{targetCommandName:selection.targetCommandName})}if(selection.operation){const{registerOperationCommands}=await loadOperationRegistrationModule();registerOperationCommands(rootProgram)}}function createTelemetryCommandErrorEmitter(params){return async event=>{const errorCategory=resolveTelemetryErrorCategory(event.errorCode);const commandResolution=deriveTelemetryCommandResolution({ok:false,errorCode:event.errorCode,errorCategory});await emitTelemetryErrorEvent({command:event.command,args:params.invocationArgv,options:event.options,global:params.bootstrapGlobal,pm_version:CLI_VERSION,pm_root:params.bootstrapPmRoot,error_code:event.errorCode,error_message:event.errorMessage,exit_code:event.exitCode,error_category:errorCategory,command_resolution:commandResolution,resolution_stage:event.resolutionStage});return{errorCategory,commandResolution}}}async function prepareExtensionServicesForRunPmCliError(params){if(params.bootstrapGlobal.noExtensions){return}const bootstrapProbe=buildBootstrapActivationProbe(params.invocationArgv);const discoverySnapshot=await loadRuntimeExtensionDiscoverySnapshot(params.bootstrapPmRoot);if(discoverySnapshot&&discoveryNeedsActivationForProbe(discoverySnapshot.discovery,bootstrapProbe)){const bootstrapSnapshot=await loadRuntimeExtensionSnapshot(params.bootstrapPmRoot,bootstrapProbe);setRecoveredExtensionServices(bootstrapSnapshot);return}if(discoverySnapshot){emitExtensionSkippedProfile(bootstrapProfileEnabled(params.invocationArgv),discoverySnapshot,bootstrapProbe)}setActiveExtensionServices({overrides:[]})}function setRecoveredExtensionServices(bootstrapSnapshot){if(!bootstrapSnapshot){setActiveExtensionServices({overrides:[]});return}setActiveExtensionServices(bootstrapSnapshot.services)}async function finishRunPmCliFailure(params){sentryFinishCommandSpan(false,params.errorMessage,{error_code:params.classificationCode,error_category:params.errorCategory,exit_code:params.exitCode,command_resolution:params.commandResolution,resolution_stage:params.resolutionStage});await runAndClearAfterCommandHooks({ok:false,error:params.errorMessage,exit_code:params.exitCode,error_code:params.classificationCode,error_category:params.errorCategory,command_resolution:params.commandResolution,resolution_stage:params.resolutionStage})}async function finishRunPmCliSuccessParse(){sentryFinishCommandSpan(true,void 0,{exit_code:EXIT_CODE.SUCCESS,command_resolution:"success",resolution_stage:"parse"});await runAndClearAfterCommandHooks({ok:true,exit_code:EXIT_CODE.SUCCESS,command_resolution:"success",resolution_stage:"parse"});process.exitCode=EXIT_CODE.SUCCESS}async function handleRunPmCliKnownError(context,numericExitCode){const hasExplicitExitCode=typeof numericExitCode==="number"&&Number.isFinite(numericExitCode);if(!(context.error instanceof PmCliError)&&(isCommanderError(context.error)||!hasExplicitExitCode)){return false}const errorMessage=describeUnknownError(context.error);const exitCode=context.error instanceof PmCliError?context.error.exitCode:normalizeThrownExitCode(numericExitCode);const rawContext=context.error instanceof PmCliError?context.error.context:void 0;const enrichedContext=buildPmCliRecoveryContext(rawContext,context.invocationArgv,errorMessage);const classification=classifyPmCliError(errorMessage,enrichedContext);const jsonErrorPayload=context.bootstrapGlobal.lean?projectLeanErrorEnvelope(formatPmCliErrorForJson(errorMessage,exitCode,enrichedContext)):formatPmCliErrorForJson(errorMessage,exitCode,enrichedContext);const renderedError=context.jsonErrors?JSON.stringify(context.bootstrapGlobal.tokenAccounting?attachOutputTokenAccounting(jsonErrorPayload,value=>`${JSON.stringify(value,null,2)}
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2a6936ec-d28f-5fba-9585-8cb5bcba103b")}catch(e2){}})();import{Command,CommanderError}from"commander";import{findPmNamespacedCommand,resolvePmCommandOperation}from"../sdk/cli-contracts/command-aliases.js";import{createPmCliProgram}from"../sdk/cli-program.js";import{runWithDiscoveredContextIntentContracts}from"../sdk/context-intent-runtime.js";import{describeUnknownError,isCommanderError,normalizeThrownExitCode,readThrownExitCode,wrapThrownErrorForSentry}from"../sdk/error-runtime.js";import{createExtensionCommandSdk}from"../sdk/extension-command-context.js";import{runExtensionMigrations}from"../sdk/extension/migrations.js";import{applyInvocationAuthorOverride}from"../sdk/invocation-author.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{validateReadOutputOptions}from"../sdk/read-output-contracts.js";import{runWithReproducibleProcessEnvironment}from"../sdk/reproducibility/process.js";import{EXIT_CODE,PmCliError,activateExtensions,clearActiveExtensionHooks,consumeAfterCommandAffectedItems,createCoreCommandHookContext,createEmptyExtensionRegistrationRegistry,createLazyModule,deriveTelemetryCommandResolution,discoverExtensions,emitTelemetryErrorEvent,ensureSentryInit,getActiveCommandResult,getActiveExtensionRegistrations,getSettingsPath,loadExtensions,maybeRunFirstUseTelemetryPrompt,pathExists,printError,printResult,readSettings,readSettingsWithMetadata,resetActiveExtensionRuntimeState,resolveItemTypeRegistry,resolvePmCliVersion,resolvePmPackageRootFromModule,resolvePmRoot,resolveRuntimeFieldRegistry,resolveTelemetryErrorCategory,runActiveCommandHandler,runActiveParserOverride,runActivePreflightOverride,runAfterCommandHooks,runBeforeCommandHooks,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,sentryCaptureCliError,sentryFinishCommandSpan,sentryFlush,sentryLogCliUsageError,sentrySetCommandContext,sentryStartCommandSpan,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices,startTelemetryCommand,writeStderr}from"../sdk/runtime-primitives.js";import{PmClient}from"../sdk/runtime.js";import{finishActiveTelemetryCommand,recordAfterCommandContextUsage}from"./after-command-context-usage.js";import{extractProvidedOptionFlags,normalizeLongOptionFlag,redactSensitiveCommandArgs,renderPmCommand}from"./argv-utils.js";import{applyBootstrapPagerPolicy,findBootstrapCommandTokenIndex,normalizeBootstrapInvocation,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,stripGlobalBootstrapTokens}from"./bootstrap-args.js";import{installCommandNamespaces}from"./command-namespaces.js";import{appendCommanderExtensionFailures,formatCommanderUsageJson,formatCommanderUsageMessage,isKnownHelpCommandPath,resolveCommanderUsageContext,resolveUnknownCommanderToken}from"./commander-usage.js";import{loadContextIntentSnapshotForInvocation}from"./context-intent-invocation.js";import{classifyCommanderError,classifyPmCliError,classifyUnknownError,formatPmCliErrorForDisplay,formatPmCliErrorForJson,formatUnknownErrorForJson,projectLeanErrorEnvelope}from"./error-guidance.js";import{applyDynamicExtensionArguments,applyDynamicExtensionFlagOptions,buildCanonicalExtensionAliases,buildDynamicExtensionCommandMetadataHelp,buildResidualDynamicExtensionFlagHelp,collectDynamicExtensionFlagHelpByCommand,collectExtensionCommandHelpDescriptors,collectSafeExtensionCommandPaths,ensureCommandPath,extensionFlagTakesValueForInvocation,findCommandByPath,normalizeExtensionCommandPath,reportExtensionCommandCollision}from"./extension-command-help.js";import{collectLoosePositionalArgs,stripLooseCommandOptionTokens}from"./extension-command-options.js";import{loadExtensionRecoveryFailures,loadUnknownCommandRecoveryFailures}from"./extension-recovery.js";import{attachRichHelpText,isFullHelpDiscovery,setPmCommandHelpVisibilityTier}from"./help-content.js";import{attachCreateUpdatePolicyHelpText,maybeRenderBootstrapJsonHelp}from"./help-json-payload.js";import{collectMandatoryMigrationBlockers,enforceItemFormatWriteGateAndPreflightMigration,enforceMandatoryMigrationWriteGate,enforceMutationGuardPreflight}from"./migration-gates.js";import{applyDefaultOutputFormat,clearResolvedGlobalOptions,collect,formatHookWarnings,getCommandPath,getGlobalOptions,invalidateSearchCachesForMutation,setResolvedGlobalOptions,syncCommanderActionOptions}from"./registration-helpers.js";import{activationCommandMatchesProbe,buildBootstrapActivationProbe,buildRuntimeExtensionActivationScope,buildRuntimeExtensionFilterForProbe,collectActivationCommandCandidates,collectLeadingCommandArgs,collectParsedActivationCommandArgs,commandPathNeedsSearchExtensions,commandPathNeedsTemplateExtensions,discoveryNeedsActivationForProbe,extensionActivationCommands,extensionCapabilities,extensionNeedsActivationForProbe,extensionProvidesTemplatesRuntime,hasAnyCapability,hasGlobalExtensionContributions,matchesStaticExtensionCommand,probeUsesAnyFlag,resolveStaticExtensionActivationDecision}from"./runtime/activation.js";import{collectExtensionFlagDefinitionsForCommand,collectExtensionFlagDefinitionsForInvocation,dynamicCommandArguments,extractCommandScopedOptions,forwardReadOutputIncludeModes,isImporterOrExporterCommandPath,recordCliReadOutputInvocationProvenance,validateDynamicExtensionCommandArgs,validateDynamicExtensionCommandInvocation}from"./runtime/invocation-options.js";import{LIST_QUERY_COMMAND_NAMES,enforceExplicitRetryForFlagTypos,invocationRequestsVersion,isStaticExtensionInventoryInvocation,resolveCoreCommandRegistrationSelection,shouldAttachRichHelpTextForInvocation,shouldRegisterDynamicExtensionPaths,shouldRegisterRuntimeSchemaFlags}from"./runtime/selection.js";import{buildPostActionTelemetryOutcome,inferPostActionErrorCode,inferPostActionFailureMessage,normalizeTelemetryCommandResolution,normalizeTelemetryErrorCategory,normalizeTelemetryResolutionStage,readRecordBoolean,readRecordNumber,readRecordString}from"./runtime/telemetry-outcome.js";const PM_PACKAGE_ROOT_ENV="PM_CLI_PACKAGE_ROOT";function resolvePmPackageRoot(){return resolvePmPackageRootFromModule(import.meta.url,["../.."])}if(typeof process.env[PM_PACKAGE_ROOT_ENV]!=="string"||process.env[PM_PACKAGE_ROOT_ENV]?.trim().length===0){process.env[PM_PACKAGE_ROOT_ENV]=resolvePmPackageRoot()}let activeExtensionHookContext=null;let activeTelemetryCommandContext=null;function setActiveExtensionHookContextForTest(context){activeExtensionHookContext=context}function setActiveRuntimeExtensionCommandDescriptorsForTest(descriptors){activeRuntimeExtensionCommandDescriptors=descriptors}let runtimeExtensionSnapshotCache=null;let runtimeExtensionDiscoverySnapshotCache=null;let activeRuntimeExtensionCommandDescriptors=new Map;const HANDLED_ERROR_SENTRY_FLUSH_TIMEOUT_MS=250;const EXPECTED_HANDLED_ERROR_EXIT_CODES=new Set([EXIT_CODE.USAGE,EXIT_CODE.NOT_FOUND,EXIT_CODE.CONFLICT]);const TRUE_LIKE_ENV_VALUES=new Set(["1","true","yes","on"]);const loadSetupRegistrationModule=createLazyModule(()=>import("./register-setup.js"));const loadListQueryRegistrationModule=createLazyModule(()=>import("./register-list-query.js"));const loadMutationRegistrationModule=createLazyModule(()=>import("./register-mutation.js"));const loadOperationRegistrationModule=createLazyModule(()=>import("./register-operations.js"));function renderAttemptedCommand(argv){return renderPmCommand(argv)}function inferMissingFieldsFromErrorMessage(message){const matches=message.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!matches||matches.length===0){return void 0}const normalized=[...new Set(matches.map(entry=>normalizeLongOptionFlag(entry)??entry))];return normalized.length>0?normalized:void 0}function inferMissingFieldsForRecovery(rawMessage,invocationArgv,existingRecovery){if(existingRecovery?.suggested_retry||rawMessage.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(rawMessage)){return void 0}const providedFields=extractProvidedOptionFlags(invocationArgv);const providedSet=new Set(providedFields.map(flag=>normalizeLongOptionFlag(flag)??flag));const rawInferred=inferMissingFieldsFromErrorMessage(rawMessage);const commandName=invocationArgv.find(token=>program.commands.some(candidate=>candidate.name()===token));const command=commandName?program.commands.find(candidate=>candidate.name()===commandName):void 0;const declaredFlags=new Set([...program.options,...command?.options??[]].flatMap(option=>option.flags.split(/[ ,|]+/).map(flag=>normalizeLongOptionFlag(flag)).filter(flag=>flag!==void 0)));const trulyMissing=rawInferred?.filter(flag=>{const normalized=normalizeLongOptionFlag(flag)??flag;if(providedSet.has(normalized)){return false}return declaredFlags.has(normalized)||extensionFlagTakesValueForInvocation(invocationArgv,commandName,normalized,activeRuntimeExtensionCommandDescriptors)!==void 0});return trulyMissing&&trulyMissing.length>0?trulyMissing:void 0}function resolveRecoverySuggestedRetry(invocationArgv,attemptedCommand,inferredMissing,existingRecovery){if(existingRecovery?.suggested_retry){return existingRecovery.suggested_retry}const missingFlag=inferredMissing?.[0];const normalizedMissing=missingFlag?normalizeLongOptionFlag(missingFlag):void 0;const commandName=invocationArgv.find(token=>program.commands.some(candidate=>candidate.name()===token));const command=commandName?program.commands.find(candidate=>candidate.name()===commandName):void 0;const missingOption=normalizedMissing?command?.options.find(option=>option.flags.split(/[ ,|]+/).includes(normalizedMissing)):void 0;const extensionFlagTakesValue=extensionFlagTakesValueForInvocation(invocationArgv,commandName,normalizedMissing,activeRuntimeExtensionCommandDescriptors);const missingTokens=normalizedMissing?missingOption?.isBoolean()===true||extensionFlagTakesValue===false?[normalizedMissing]:[normalizedMissing,"<value>"]:[];const suggestedRetry=normalizedMissing?renderAttemptedCommand([...invocationArgv,...missingTokens]):attemptedCommand;return suggestedRetry===attemptedCommand?void 0:suggestedRetry}function projectExistingRecoveryOptionalFields(existingRecovery){if(!existingRecovery){return{}}const optionalFields=["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"];const projected={};for(const field of optionalFields){const value=existingRecovery[field];if(value!==void 0&&value!==null){projected[field]=value}}return projected}function buildRecoveryPayload(params){const existingRecovery=params.existingRecovery;return{attempted_command:existingRecovery?.attempted_command??params.attemptedCommand,normalized_args:existingRecovery?.normalized_args??[...params.invocationArgv],provided_fields:existingRecovery?.provided_fields??(params.providedFields.length>0?params.providedFields:void 0),missing:existingRecovery?.missing??params.inferredMissing,...projectExistingRecoveryOptionalFields(existingRecovery),...params.suggestedRetry?{suggested_retry:params.suggestedRetry}:{}}}function buildPmCliRecoveryContext(context,invocationArgv,rawMessage){const safeInvocationArgv=redactSensitiveCommandArgs(invocationArgv);const commandArgs=stripGlobalBootstrapTokens(safeInvocationArgv);const commandIndex=findBootstrapCommandTokenIndex(commandArgs);const[rootCommand,subcommand]=commandIndex===void 0?[]:commandArgs.slice(commandIndex,commandIndex+2);const explainRequested=safeInvocationArgv.includes("--explain");const rawExistingRecovery=context?.recovery;const existingRecovery=rawExistingRecovery&&(rootCommand==="history-redact"||rootCommand==="history"&&subcommand==="redact")?{...rawExistingRecovery,...rawExistingRecovery.attempted_command?{attempted_command:renderAttemptedCommand(safeInvocationArgv)}:{},...rawExistingRecovery.normalized_args?{normalized_args:[...safeInvocationArgv]}:{},...rawExistingRecovery.suggested_retry?{suggested_retry:renderAttemptedCommand(safeInvocationArgv)}:{},...rawExistingRecovery.suggested_retry_args?{suggested_retry_args:[...safeInvocationArgv]}:{}}:rawExistingRecovery;if(existingRecovery?.recovery_mode==="compact"&&!explainRequested){return{...context,recovery:existingRecovery}}const attemptedCommand=renderAttemptedCommand(safeInvocationArgv);const providedFields=extractProvidedOptionFlags(safeInvocationArgv);const inferredMissing=inferMissingFieldsForRecovery(rawMessage,safeInvocationArgv,existingRecovery);const suggestedRetry=resolveRecoverySuggestedRetry(safeInvocationArgv,attemptedCommand,inferredMissing,existingRecovery);const recovery=buildRecoveryPayload({invocationArgv:safeInvocationArgv,attemptedCommand,providedFields,inferredMissing,suggestedRetry,existingRecovery});return{...context,recovery}}async function runAndClearAfterCommandHooks(outcome){const telemetryRuntime=activeTelemetryCommandContext;activeTelemetryCommandContext=null;await finishActiveTelemetryCommand(telemetryRuntime,outcome);const runtime=activeExtensionHookContext;activeExtensionHookContext=null;if(!runtime){clearActiveExtensionHooks();return}let hookWarnings=[];const affected=consumeAfterCommandAffectedItems();try{await recordAfterCommandContextUsage({pmRoot:runtime.pmRoot,author:runtime.globalOptions.author,itemIds:outcome.ok?affected?.map(item=>item.id)??[]:[],intent:runtime.commandName})}catch{hookWarnings.push("context_usage_feedback_write_failed")}try{hookWarnings.push(...await runAfterCommandHooks(runtime.hooks,{command:runtime.commandName,args:runtime.commandArgs,options:{...runtime.commandOptions},global:{...runtime.globalOptions},pm_root:runtime.pmRoot,ok:outcome.ok,error:outcome.error,result:getActiveCommandResult(),affected}))}catch(error){const message=error instanceof Error?error.message:String(error);hookWarnings=[`afterCommand hooks failed: ${message}`]}finally{clearActiveExtensionHooks()}if(!runtime.globalOptions.json&&hookWarnings.length>0){printError(`[pm] warning: afterCommand hook_warnings=${formatHookWarnings(hookWarnings)}`)}if(runtime.profileEnabled&&hookWarnings.length>0){printError(`profile:extensions hook_warnings=${formatHookWarnings(hookWarnings)}`)}}async function ensureSentryForErrorReporting(){await ensureSentryInit()}function envFlagEnabled(key){return TRUE_LIKE_ENV_VALUES.has((process.env[key]??"").trim().toLowerCase())}function shouldLogHandledErrorToSentry(exitCode){if(envFlagEnabled("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")){return true}return!EXPECTED_HANDLED_ERROR_EXIT_CODES.has(Math.trunc(exitCode))}async function maybeLogHandledCliErrorToSentry(params){if(!shouldLogHandledErrorToSentry(params.exit_code)){return false}await ensureSentryForErrorReporting();sentryLogCliUsageError(params);return true}async function handleGenericRunPmCliError(params){const message=describeUnknownError(params.error);const classification=classifyUnknownError(message);if(params.bootstrapGlobal.json){printError(JSON.stringify(formatUnknownErrorForJson(message,EXIT_CODE.GENERIC_FAILURE),null,2))}else{printError(message)}process.exitCode=EXIT_CODE.GENERIC_FAILURE;let errorCategory="runtime";let commandResolution="runtime_failed";try{await ensureSentryForErrorReporting();sentryCaptureCliError(params.error);const telemetry=await params.emitTelemetryCommandError({command:params.attemptedCommand,errorCode:classification.code,errorMessage:classification.detail,exitCode:EXIT_CODE.GENERIC_FAILURE,options:{bootstrap_global_options:params.bootstrapGlobal},resolutionStage:"execute"});errorCategory=telemetry.errorCategory;commandResolution=telemetry.commandResolution;sentryFinishCommandSpan(false,message,{error_code:classification.code,error_category:errorCategory,exit_code:EXIT_CODE.GENERIC_FAILURE,command_resolution:commandResolution,resolution_stage:"execute"})}catch(reportingError){if(!params.bootstrapGlobal.json){printError(`Failed to report error: ${describeUnknownError(reportingError)}`)}}try{await runAndClearAfterCommandHooks({ok:false,error:message,exit_code:EXIT_CODE.GENERIC_FAILURE,error_code:classification.code,error_category:errorCategory,command_resolution:commandResolution,resolution_stage:"execute"})}catch(hookError){if(!params.bootstrapGlobal.json){printError(`Failed to run error hooks: ${describeUnknownError(hookError)}`)}}try{await sentryFlush()}catch(flushError){if(!params.bootstrapGlobal.json){printError(`Failed to flush error reporting: ${describeUnknownError(flushError)}`)}}}const RUNTIME_FIELD_COMMAND_BY_COMMAND_PATH={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"};const runtimeFieldLooseFlagDefinitionCache=new Map;function toLooseFieldDefinitionType(fieldType){if(fieldType==="number"){return"number"}if(fieldType==="boolean"){return"boolean"}return"string"}function commandHasLongOption(command,longFlag){return command.options.some(option=>option.long===longFlag)}function commandHasShortOption(command,shortFlag){return command.options.some(option=>option.short===shortFlag)}function addRuntimeFieldOption(command,flagToken,description,repeatable){const normalizedToken=flagToken.trim();if(!normalizedToken){return}const helpText=description.length>0?description:`Runtime schema field (${flagToken})`;if(normalizedToken.startsWith("-")&&!normalizedToken.startsWith("--")){if(commandHasShortOption(command,normalizedToken)){return}if(repeatable){command.option(`${normalizedToken} <value>`,`${helpText} (repeatable)`,collect);return}command.option(`${normalizedToken} <value>`,helpText);return}const longFlag=normalizedToken.startsWith("--")?normalizedToken:`--${normalizedToken}`;if(commandHasLongOption(command,longFlag)){return}if(repeatable){command.option(`${longFlag} <value>`,`${helpText} (repeatable)`,collect);return}command.option(`${longFlag} <value>`,helpText)}async function collectRuntimeFieldLooseFlagDefinitionsForCommand(commandPath,pmRoot){const runtimeCommand=RUNTIME_FIELD_COMMAND_BY_COMMAND_PATH[commandPath];if(!runtimeCommand){return[]}const cacheKey=`${pmRoot}:${runtimeCommand}`;const cached=runtimeFieldLooseFlagDefinitionCache.get(cacheKey);if(cached){return cached}if(!await pathExists(getSettingsPath(pmRoot))){runtimeFieldLooseFlagDefinitionCache.set(cacheKey,[]);return[]}const settings=await readSettings(pmRoot);const fieldRegistry=resolveRuntimeFieldRegistry(settings.schema);const definitions=(fieldRegistry.command_to_fields.get(runtimeCommand)??[]).flatMap(field=>{const flagTokens=[field.cli_flag,...field.cli_aliases];return flagTokens.map(token=>({long:`--${token}`,type:toLooseFieldDefinitionType(field.type),value_type:toLooseFieldDefinitionType(field.type)}))});runtimeFieldLooseFlagDefinitionCache.set(cacheKey,definitions);return definitions}async function registerRuntimeSchemaFieldFlags(rootProgram,invocationArgv){const bootstrapGlobalOptions=parseBootstrapGlobalOptions(invocationArgv);const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobalOptions.path);if(!await pathExists(getSettingsPath(pmRoot))){return}const cachedDiscovery=runtimeExtensionDiscoverySnapshotCache?.key===buildRuntimeExtensionDiscoverySnapshotCacheKey(pmRoot)?runtimeExtensionDiscoverySnapshotCache.snapshot:null;const settings=cachedDiscovery===null?await readSettings(pmRoot):cachedDiscovery.settings;const fieldRegistry=resolveRuntimeFieldRegistry(settings.schema);const mappings=[{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 mapping of mappings){const command=findCommandByPath(rootProgram,mapping.path.split(" "));if(!command){continue}for(const field of fieldRegistry.command_to_fields.get(mapping.command)??[]){const description=field.description??"";addRuntimeFieldOption(command,field.cli_flag,description,field.repeatable);for(const alias of field.cli_aliases){addRuntimeFieldOption(command,alias,`Alias for --${field.cli_flag}`,field.repeatable)}}}}async function maybeAttachCreateUpdatePolicyHelpText(rootProgram,pmRoot,invocationArgv,registrations,settings){const bootstrapCommand=parseBootstrapCommandName(invocationArgv);if(bootstrapCommand!=="create"&&bootstrapCommand!=="update"){return}try{const resolvedSettings=settings??await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(resolvedSettings,registrations);attachCreateUpdatePolicyHelpText(rootProgram,typeRegistry,invocationArgv)}catch{}}function defaultPreflightDecision(){return{enforce_item_format_gate:true,run_preflight_item_format_sync:true,run_extension_migrations:true,enforce_mandatory_migration_gate:true}}function buildRuntimeExtensionSnapshotCacheKey(pmRoot,activationScope="all"){return activationScope==="all"?`pm-root:${pmRoot}`:`pm-root:${pmRoot}:activation:${activationScope}`}function bootstrapProfileEnabled(invocationArgv){return invocationArgv.some(token=>token==="--profile")}function buildRuntimeExtensionDiscoverySnapshotCacheKey(pmRoot){return`pm-root:${pmRoot}`}function emitSettingsReadWarnings(warnings){for(const warning of warnings){if(warning.startsWith("settings_read_")){printError(`[pm] warning: ${warning} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}}}function emitExtensionProfile(globalOptions,snapshot){if(!globalOptions.profile){return}printError(`profile:extensions loaded=${snapshot.loadedCount} failed=${snapshot.loadFailedCount} warnings=${snapshot.loadWarnings.length} activation_failed=${snapshot.activationFailedCount} hook_counts=before:${snapshot.hooks.beforeCommand.length}|after:${snapshot.hooks.afterCommand.length}|write:${snapshot.hooks.onWrite.length}|read:${snapshot.hooks.onRead.length}|index:${snapshot.hooks.onIndex.length} command_overrides=${snapshot.commands.overrides.length} command_handlers=${snapshot.commands.handlers.length} parser_overrides=${snapshot.parsers.overrides.length} preflight_overrides=${snapshot.preflight.overrides.length} service_overrides=${snapshot.services.overrides.length} renderer_overrides=${snapshot.renderers.overrides.length}`);if(snapshot.activationWarnings.length>0){printError(`profile:extensions activation_warnings=${formatHookWarnings(snapshot.activationWarnings)}`)}}function emitExtensionSkippedProfile(profileEnabled,snapshot,probe){if(!profileEnabled){return}const command=normalizeExtensionCommandPath(probe.commandPath??"")||"<none>";printError(`profile:extensions activation=skipped command=${command} effective=${snapshot.discovery.effective.length} warnings=${snapshot.discovery.warnings.length} discovery_ms=${snapshot.discoveryMs}`)}async function loadRuntimeExtensionDiscoverySnapshot(pmRoot,readSettingsWithMetadataFn=readSettingsWithMetadata){const cacheKey=buildRuntimeExtensionDiscoverySnapshotCacheKey(pmRoot);if(runtimeExtensionDiscoverySnapshotCache?.key===cacheKey){return runtimeExtensionDiscoverySnapshotCache.snapshot}try{const startedAt=Date.now();const{settings,warnings:settingsReadWarnings}=await readSettingsWithMetadataFn(pmRoot);const discovery=await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:false});const snapshot={pmRoot,settings,discovery,discoveryMs:Date.now()-startedAt,settingsReadWarnings:[...settingsReadWarnings]};runtimeExtensionDiscoverySnapshotCache={key:cacheKey,snapshot};return snapshot}catch{runtimeExtensionDiscoverySnapshotCache={key:cacheKey,snapshot:null};return null}}async function loadRuntimeExtensionSnapshot(pmRoot,probe,readSettingsFn=readSettings){const activationScope=probe?buildRuntimeExtensionActivationScope(probe):"all";const cacheKey=buildRuntimeExtensionSnapshotCacheKey(pmRoot,activationScope);if(runtimeExtensionSnapshotCache?.key===cacheKey){return runtimeExtensionSnapshotCache.snapshot}try{const settings=await readSettingsFn(pmRoot);const loadResult=await loadExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:false,extensionFilter:probe?buildRuntimeExtensionFilterForProbe(probe):void 0});const activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});const commandHandlers=[...new Set(activationResult.commands.handlers.map(entry=>normalizeExtensionCommandPath(entry.command)))].filter(entry=>entry.length>0).sort((left,right)=>left.localeCompare(right));const commandFlagHelp=collectDynamicExtensionFlagHelpByCommand(activationResult.registrations.flags);const canonicalAliases=buildCanonicalExtensionAliases(activationResult.commands.handlers,activationResult.registrations.commands);const commandDescriptors=collectExtensionCommandHelpDescriptors(commandHandlers,activationResult.registrations.commands,activationResult.registrations.flags,canonicalAliases);const snapshot={hooks:activationResult.hooks,commands:activationResult.commands,parsers:activationResult.parsers,preflight:activationResult.preflight,services:activationResult.services,renderers:activationResult.renderers,registrations:activationResult.registrations,pmRoot,settings,commandHandlers,commandFlagHelp,commandDescriptors,commandAliases:canonicalAliases,loadWarnings:[...loadResult.warnings],activationWarnings:[...activationResult.warnings],loadedCount:loadResult.loaded.length,loadFailedCount:loadResult.failed.length,activationFailedCount:activationResult.failed.length,contextIntentPackages:loadResult.loaded.map(({name,module})=>({name,module}))};runtimeExtensionSnapshotCache={key:cacheKey,snapshot};return snapshot}catch{runtimeExtensionSnapshotCache={key:cacheKey,snapshot:null};return null}}async function maybeLoadRuntimeExtensions(command){const globalOptions=getGlobalOptions(command);if(globalOptions.noExtensions){const noExtPmRoot=resolvePmRoot(process.cwd(),globalOptions.path);if(await pathExists(getSettingsPath(noExtPmRoot))){emitSettingsReadWarnings((await readSettingsWithMetadata(noExtPmRoot)).warnings)}return null}const pmRoot=resolvePmRoot(process.cwd(),globalOptions.path);const discoverySnapshot=await loadRuntimeExtensionDiscoverySnapshot(pmRoot);if(!discoverySnapshot){return null}emitSettingsReadWarnings(discoverySnapshot.settingsReadWarnings);const probe={commandPath:getCommandPath(command),commandArgs:collectParsedActivationCommandArgs(command)};if(!discoveryNeedsActivationForProbe(discoverySnapshot.discovery,probe)){emitExtensionSkippedProfile(globalOptions.profile,discoverySnapshot,probe);return null}const snapshot=await loadRuntimeExtensionSnapshot(pmRoot,probe);if(!snapshot){return null}emitExtensionProfile(globalOptions,snapshot);return{hooks:snapshot.hooks,commands:snapshot.commands,parsers:snapshot.parsers,preflight:snapshot.preflight,services:snapshot.services,renderers:snapshot.renderers,registrations:snapshot.registrations,pmRoot}}async function loadRuntimeExtensionCommandDescriptorsForRecovery(pmRoot){const snapshot=await loadRuntimeExtensionSnapshot(pmRoot);return snapshot?new Map(snapshot.commandDescriptors):activeRuntimeExtensionCommandDescriptors}async function executeRegisteredRuntimeMigrations(migrations,pmRoot){const result=await runExtensionMigrations({pmRoot,migrations,author:"pm-extension-migration"});return result.migrations.filter(migration=>migration.outcome==="failed").map(migration=>`extension_migration_failed:${migration.layer}:${migration.extension}:${migration.id}`)}function buildExtensionCommandSdk(pmRoot,global2){const author=typeof global2.author==="string"&&global2.author.trim()?global2.author.trim():"pm-extension";return createExtensionCommandSdk(pmRoot,PmClient.forActiveExtensionHost({pmRoot,author}))}async function runRequiredExtensionCommand(command,options,globalOptions,extensionFlagDefinitions=[]){const commandPath=getCommandPath(command);let commandArgs=stripLooseCommandOptionTokens(command.args.map(String),extensionFlagDefinitions);let commandOptions={...options};let resolvedGlobalOptions={...globalOptions};const pmRoot=resolvePmRoot(process.cwd(),globalOptions.path);const parserOverride=await runActiveParserOverride({command:commandPath,args:commandArgs,options:commandOptions,global:resolvedGlobalOptions,pm_root:pmRoot});if(globalOptions.profile&&parserOverride.warnings.length>0){printError(`profile:extensions parser_warnings=${formatHookWarnings(parserOverride.warnings)}`)}commandArgs=parserOverride.context.args;commandOptions=parserOverride.context.options;resolvedGlobalOptions=parserOverride.context.global;validateDynamicExtensionCommandInvocation(activeRuntimeExtensionCommandDescriptors.get(normalizeExtensionCommandPath(commandPath)),commandArgs,commandOptions,extensionFlagDefinitions);setActiveCommandResult(void 0);setActiveCommandContext({command:commandPath,args:commandArgs,options:{...commandOptions},global:{...resolvedGlobalOptions},pm_root:pmRoot});const extensionCommandResult=await runActiveCommandHandler({command:commandPath,args:commandArgs,options:commandOptions,global:resolvedGlobalOptions,pm_root:pmRoot,sdk:buildExtensionCommandSdk(pmRoot,resolvedGlobalOptions)});if(resolvedGlobalOptions.profile&&extensionCommandResult.warnings.length>0){printError(`profile:extensions command_handler_warnings=${formatHookWarnings(extensionCommandResult.warnings)}`)}if(!extensionCommandResult.handled){if(extensionCommandResult.warnings.length>0){const warningCode=extensionCommandResult.warnings[0];const cause=extensionCommandResult.errorMessage?.trim();const causeSuffix=cause?` ${cause}`:"";throw new PmCliError(`Command "${commandPath}" failed in extension handler (${warningCode}).${causeSuffix}`,EXIT_CODE.GENERIC_FAILURE,{code:extensionCommandResult.errorCode??"command_failed",nextSteps:extensionCommandResult.remediation?[extensionCommandResult.remediation]:void 0})}throw new PmCliError(`Command "${commandPath}" is provided by extensions and is not currently available.`,EXIT_CODE.NOT_FOUND)}if(extensionCommandResult.exitCode!==void 0){process.exitCode=extensionCommandResult.exitCode}setActiveCommandResult(extensionCommandResult.result);return extensionCommandResult.result}const WRAPPED_ACTION_HANDLER=Symbol("pm.wrappedActionHandler");function resolveActionCommand(actionArgs,fallback){const possibleCommand=actionArgs[actionArgs.length-1];return possibleCommand instanceof Command?possibleCommand:fallback}function maybePrintExtensionProfileWarnings(enabled,label,warnings){if(enabled&&warnings.length>0){printError(`profile:extensions ${label}=${formatHookWarnings(warnings)}`)}}function validateDynamicInvocationArgs(params){const dynamicDescriptor=activeRuntimeExtensionCommandDescriptors.get(normalizeExtensionCommandPath(params.commandPath));if(!dynamicDescriptor||!isImporterOrExporterCommandPath(params.activeRegistrations,params.commandPath)){return}const positionalArgs=dynamicCommandArguments(dynamicDescriptor).length===0?collectLoosePositionalArgs(params.commandArgs):stripLooseCommandOptionTokens(params.commandArgs,params.extensionFlagDefinitions);validateDynamicExtensionCommandArgs(dynamicDescriptor,positionalArgs)}function syncCommanderActionArgs(actionCommand,actionArgs,commandArgs){actionCommand.args=[...commandArgs];if("_processArguments"in actionCommand&&typeof actionCommand._processArguments==="function"){actionCommand._processArguments()}if(actionArgs.length>0&&Array.isArray(actionArgs[0])){actionArgs[0]=[...actionCommand.processedArgs]}}function wrapProgramActionsForExtensionHandlers(rootProgram){const visit=entry=>{const actionEntry=entry;if(typeof actionEntry._actionHandler==="function"&&actionEntry[WRAPPED_ACTION_HANDLER]!==true){const originalAction=actionEntry._actionHandler;actionEntry._actionHandler=async function wrappedActionHandler(...actionArgs){const actionCommand=resolveActionCommand(actionArgs,entry);const startedAt=Date.now();clearResolvedGlobalOptions(actionCommand);let globalOptions=getGlobalOptions(actionCommand);const commandPath=resolvePmCommandOperation(getCommandPath(actionCommand));if(["package inventory","packages inventory","extension inventory"].includes(commandPath)){return await originalAction.apply(this,actionArgs)}const pmRoot=resolvePmRoot(process.cwd(),globalOptions.path);let commandArgs=actionCommand.args.map(String);const activeRegistrations=getActiveExtensionRegistrations();const extensionFlagDefinitions=activeRegistrations?collectExtensionFlagDefinitionsForInvocation(activeRegistrations,commandPath,commandArgs):[];const runtimeFieldFlagDefinitions=await collectRuntimeFieldLooseFlagDefinitionsForCommand(commandPath,pmRoot);let commandOptions=extractCommandScopedOptions(actionCommand,commandArgs,[...extensionFlagDefinitions,...runtimeFieldFlagDefinitions]);const parserOverride=await runActiveParserOverride({command:commandPath,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:pmRoot});maybePrintExtensionProfileWarnings(globalOptions.profile,"parser_warnings",parserOverride.warnings);commandArgs=parserOverride.context.args;commandOptions=parserOverride.context.options;globalOptions=parserOverride.context.global;validateDynamicInvocationArgs({activeRegistrations,commandPath,commandArgs,extensionFlagDefinitions});globalOptions=await applyDefaultOutputFormat(globalOptions);setResolvedGlobalOptions(actionCommand,globalOptions);syncCommanderActionArgs(actionCommand,actionArgs,commandArgs);syncCommanderActionOptions(actionCommand,commandOptions);setActiveCommandResult(void 0);setActiveCommandContext({command:commandPath,args:commandArgs,options:{...commandOptions},global:{...globalOptions},pm_root:pmRoot});const extensionCommandResult=await runActiveCommandHandler({command:commandPath,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:pmRoot,sdk:buildExtensionCommandSdk(pmRoot,globalOptions)});maybePrintExtensionProfileWarnings(globalOptions.profile,"command_handler_warnings",extensionCommandResult.warnings);if(extensionCommandResult.handled){setActiveCommandResult(extensionCommandResult.result);printResult(extensionCommandResult.result,{...globalOptions,command:commandPath,commandArgs,commandOptions,pmRoot});if(globalOptions.profile){printError(`profile:command=${commandPath} took_ms=${Date.now()-startedAt}`)}return}return await originalAction.apply(this,actionArgs)};actionEntry[WRAPPED_ACTION_HANDLER]=true}for(const child of entry.commands){visit(child)}};visit(rootProgram)}async function clearDynamicExtensionCommandState(params){activeRuntimeExtensionCommandDescriptors=new Map;setActiveExtensionServices({overrides:[]});if(params){await maybeAttachCreateUpdatePolicyHelpText(params.rootProgram,params.pmRoot,params.invocationArgv,createEmptyExtensionRegistrationRegistry(),params.settings)}}function attachDynamicExtensionHelp(command,descriptor,flagHelp,metadataHelp){if(descriptor?.flags&&descriptor.flags.length>0){applyDynamicExtensionFlagOptions(command,descriptor.flags);const residualFlagHelp=buildResidualDynamicExtensionFlagHelp(command,descriptor.flags);if(residualFlagHelp){command.addHelpText("after",residualFlagHelp)}}else if(flagHelp){command.addHelpText("after",flagHelp)}if(metadataHelp){command.addHelpText("after",metadataHelp)}}function applyDynamicExtensionRootHelpVisibility(rootProgram,preexistingTopLevelCommands,descriptors){const tierRank={core:0,standard:1,full:2,internal:3};const applyVisibility=(command,pathParts)=>{const commandPath=pathParts.join(" ");const matchingDescriptors=[...descriptors.entries()].filter(([path])=>path===commandPath||path.startsWith(`${commandPath} `)).map(([,descriptor])=>descriptor);const tier=matchingDescriptors.length===0?"standard":matchingDescriptors.reduce((selected,descriptor)=>tierRank[descriptor.tier]<tierRank[selected]?descriptor.tier:selected,"internal");setPmCommandHelpVisibilityTier(command,tier);for(const child of command.commands){applyVisibility(child,[...pathParts,child.name()])}};for(const command of rootProgram.commands){if(!preexistingTopLevelCommands.has(command.name())){applyVisibility(command,[command.name()])}}}async function registerDynamicExtensionCommandPaths(rootProgram,invocationArgv){const bootstrapGlobalOptions=parseBootstrapGlobalOptions(invocationArgv);const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobalOptions.path);if(bootstrapGlobalOptions.noExtensions){await clearDynamicExtensionCommandState({rootProgram,pmRoot,invocationArgv});return}const discoverySnapshot=await loadRuntimeExtensionDiscoverySnapshot(pmRoot);const probe=buildBootstrapActivationProbe(invocationArgv);if(!discoverySnapshot){await clearDynamicExtensionCommandState();return}if(!discoveryNeedsActivationForProbe(discoverySnapshot.discovery,probe)){await clearDynamicExtensionCommandState({rootProgram,pmRoot,invocationArgv,settings:discoverySnapshot.settings});emitExtensionSkippedProfile(bootstrapProfileEnabled(invocationArgv),discoverySnapshot,probe);return}const snapshot=await loadRuntimeExtensionSnapshot(pmRoot,probe);if(!snapshot){await clearDynamicExtensionCommandState({rootProgram,pmRoot,invocationArgv,settings:discoverySnapshot.settings});return}setActiveExtensionServices(snapshot.services);activeRuntimeExtensionCommandDescriptors=new Map(snapshot.commandDescriptors);await maybeAttachCreateUpdatePolicyHelpText(rootProgram,pmRoot,invocationArgv,snapshot.registrations,snapshot.settings);const commandPaths=collectSafeExtensionCommandPaths(rootProgram,snapshot.commandHandlers,snapshot.commandDescriptors,snapshot.commandAliases,warning=>reportExtensionCommandCollision(snapshot.activationWarnings,printError,warning));const preexistingTopLevelCommands=new Set(rootProgram.commands.map(command=>command.name()));const registerCommandPath=commandPath=>{const pathParts=commandPath.split(" ").filter(part=>part.length>0);const descriptor=snapshot.commandDescriptors.get(commandPath);const existingCommand=findCommandByPath(rootProgram,pathParts);const flagHelp=snapshot.commandFlagHelp.get(commandPath);const metadataHelp=descriptor?buildDynamicExtensionCommandMetadataHelp(descriptor):null;if(existingCommand){attachDynamicExtensionHelp(existingCommand,descriptor,flagHelp,metadataHelp);return}const dynamicCommand=ensureCommandPath(rootProgram,pathParts);if(descriptor?.description){dynamicCommand.description(descriptor.description)}let residualDynamicFlagHelp=flagHelp;if(descriptor){applyDynamicExtensionArguments(dynamicCommand,descriptor);if(descriptor.flags.length>0){applyDynamicExtensionFlagOptions(dynamicCommand,descriptor.flags);residualDynamicFlagHelp=buildResidualDynamicExtensionFlagHelp(dynamicCommand,descriptor.flags)??void 0}}if(residualDynamicFlagHelp){dynamicCommand.addHelpText("after",residualDynamicFlagHelp)}if(metadataHelp){dynamicCommand.addHelpText("after",metadataHelp)}dynamicCommand.allowUnknownOption(true).allowExcessArguments(true).action(async(...actionArgs)=>{const maybeCommand=actionArgs[actionArgs.length-1];const command=maybeCommand instanceof Command?maybeCommand:dynamicCommand;const globalOptions=getGlobalOptions(command);const startedAt=Date.now();const extensionFlagDefinitions=collectExtensionFlagDefinitionsForInvocation(snapshot.registrations,commandPath,command.args.map(String));const scopedOptions=extractCommandScopedOptions(command,command.args.map(String),extensionFlagDefinitions);const result=await runRequiredExtensionCommand(command,scopedOptions,globalOptions,extensionFlagDefinitions);await invalidateSearchCachesForMutation(globalOptions,result);printResult(result,{...globalOptions,command:commandPath,commandArgs:command.args.map(String),commandOptions:scopedOptions,pmRoot});if(globalOptions.profile){printError(`profile:command=${commandPath} took_ms=${Date.now()-startedAt}`)}})};for(const commandPath of commandPaths){registerCommandPath(commandPath)}applyDynamicExtensionRootHelpVisibility(rootProgram,preexistingTopLevelCommands,snapshot.commandDescriptors)}const CLI_VERSION=resolvePmCliVersion(import.meta.url,["../.."])??"0.0.0";let program=createPmCliProgram(CLI_VERSION);function attachProgramLifecycleHooks(rootProgram,invocationArgv){if(invocationArgv&&isStaticExtensionInventoryInvocation(invocationArgv))return;rootProgram.hook("preAction",async(_thisCommand,actionCommand)=>{activeExtensionHookContext=null;activeTelemetryCommandContext=null;clearActiveExtensionHooks();clearResolvedGlobalOptions(actionCommand);const rawGlobalOptions=actionCommand.optsWithGlobals();const bootstrapGlobalOptions=getGlobalOptions(actionCommand);const commandPath=resolvePmCommandOperation(getCommandPath(actionCommand));let commandArgs=actionCommand.args.map(String);let commandOptions=extractCommandScopedOptions(actionCommand,commandArgs);let globalOptions={...bootstrapGlobalOptions};validateReadOutputOptions(commandPath,{...commandOptions,outputInclude:rawGlobalOptions.outputInclude,outputLimit:rawGlobalOptions.outputLimit,outputBudget:rawGlobalOptions.outputBudget,outputFormat:rawGlobalOptions.outputFormat,outputSession:rawGlobalOptions.outputSession,outputCursor:rawGlobalOptions.outputCursor});forwardReadOutputIncludeModes(actionCommand,commandPath,globalOptions,commandOptions);await maybeRunFirstUseTelemetryPrompt(commandPath,globalOptions);const fallbackPmRoot=resolvePmRoot(process.cwd(),bootstrapGlobalOptions.path);const runtimeExtensions=await maybeLoadRuntimeExtensions(actionCommand);if(!runtimeExtensions){activeExtensionHookContext=createCoreCommandHookContext({commandName:commandPath,commandArgs,commandOptions,globalOptions,pmRoot:fallbackPmRoot});activeTelemetryCommandContext=await startTelemetryCommand({command:commandPath,pm_version:CLI_VERSION,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:fallbackPmRoot});sentrySetCommandContext(commandPath,commandArgs,commandOptions,{source_context:activeTelemetryCommandContext?.source_context,source_context_source:activeTelemetryCommandContext?.source_context_source});sentryStartCommandSpan(commandPath);await enforceItemFormatWriteGateAndPreflightMigration(commandPath,commandOptions,fallbackPmRoot,defaultPreflightDecision());await enforceMutationGuardPreflight(commandPath,commandArgs,commandOptions,globalOptions,fallbackPmRoot);return}setActiveExtensionHooks(runtimeExtensions.hooks);setActiveExtensionCommands(runtimeExtensions.commands);setActiveExtensionParsers(runtimeExtensions.parsers);setActiveExtensionPreflight(runtimeExtensions.preflight);setActiveExtensionServices(runtimeExtensions.services);setActiveExtensionRenderers(runtimeExtensions.renderers);setActiveExtensionRegistrations(runtimeExtensions.registrations);const extensionFlagDefinitions=collectExtensionFlagDefinitionsForInvocation(runtimeExtensions.registrations,commandPath,commandArgs);commandOptions=extractCommandScopedOptions(actionCommand,commandArgs,extensionFlagDefinitions);forwardReadOutputIncludeModes(actionCommand,commandPath,globalOptions,commandOptions);const parserOverride=await runActiveParserOverride({command:commandPath,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:runtimeExtensions.pmRoot});if(globalOptions.profile&&parserOverride.warnings.length>0){printError(`profile:extensions parser_warnings=${formatHookWarnings(parserOverride.warnings)}`)}commandArgs=parserOverride.context.args;commandOptions=parserOverride.context.options;globalOptions=parserOverride.context.global;syncCommanderActionOptions(actionCommand,commandOptions);const preflightOverride=await runActivePreflightOverride({command:commandPath,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:runtimeExtensions.pmRoot,decision:defaultPreflightDecision()});if(globalOptions.profile&&preflightOverride.warnings.length>0){printError(`profile:extensions preflight_warnings=${formatHookWarnings(preflightOverride.warnings)}`)}commandArgs=preflightOverride.context.args;commandOptions=preflightOverride.context.options;globalOptions=preflightOverride.context.global;syncCommanderActionOptions(actionCommand,commandOptions);const preflightDecision=preflightOverride.decision;await enforceItemFormatWriteGateAndPreflightMigration(commandPath,commandOptions,runtimeExtensions.pmRoot,preflightDecision);await enforceMutationGuardPreflight(commandPath,commandArgs,commandOptions,globalOptions,runtimeExtensions.pmRoot);const migrationWarnings=preflightDecision.run_extension_migrations?await executeRegisteredRuntimeMigrations(runtimeExtensions.registrations.migrations,runtimeExtensions.pmRoot):[];if(globalOptions.profile&&migrationWarnings.length>0){printError(`profile:extensions migration_warnings=${formatHookWarnings(migrationWarnings)}`)}const migrationBlockers=collectMandatoryMigrationBlockers(runtimeExtensions.registrations.migrations);activeExtensionHookContext={hooks:runtimeExtensions.hooks,commandName:commandPath,commandArgs,commandOptions:{...commandOptions},globalOptions:{...globalOptions},pmRoot:runtimeExtensions.pmRoot,profileEnabled:Boolean(globalOptions.profile),migrationBlockers};setActiveCommandResult(void 0);setActiveCommandContext({command:commandPath,args:commandArgs,options:{...commandOptions},global:{...globalOptions},pm_root:runtimeExtensions.pmRoot});activeTelemetryCommandContext=await startTelemetryCommand({command:commandPath,pm_version:CLI_VERSION,args:commandArgs,options:commandOptions,global:globalOptions,pm_root:runtimeExtensions.pmRoot});sentrySetCommandContext(commandPath,commandArgs,commandOptions,{source_context:activeTelemetryCommandContext?.source_context,source_context_source:activeTelemetryCommandContext?.source_context_source});sentryStartCommandSpan(commandPath);const hookWarnings=await runBeforeCommandHooks(runtimeExtensions.hooks,{command:commandPath,args:commandArgs,options:{...commandOptions},global:{...globalOptions},pm_root:runtimeExtensions.pmRoot});if(globalOptions.profile&&hookWarnings.length>0){printError(`profile:extensions hook_warnings=${formatHookWarnings(hookWarnings)}`)}if(preflightDecision.enforce_mandatory_migration_gate){enforceMandatoryMigrationWriteGate(commandPath,commandOptions,migrationBlockers)}});rootProgram.hook("postAction",async()=>{const outcome=buildPostActionTelemetryOutcome();sentryFinishCommandSpan(outcome.ok,outcome.error,{error_code:outcome.error_code,error_category:outcome.error_category,exit_code:outcome.exit_code,command_resolution:outcome.command_resolution,resolution_stage:outcome.resolution_stage});await runAndClearAfterCommandHooks(outcome)})}attachProgramLifecycleHooks(program);const IDEMPOTENT_TOP_LEVEL_REGISTRATION=Symbol("pmCliIdempotentTopLevelRegistration");function ensureIdempotentTopLevelCommandRegistration(rootProgram){const guarded=rootProgram;if(guarded[IDEMPOTENT_TOP_LEVEL_REGISTRATION]){return}guarded[IDEMPOTENT_TOP_LEVEL_REGISTRATION]=true;const registerOriginalCommand=rootProgram.command.bind(rootProgram);rootProgram.command=((nameAndArgs,...rest)=>{const commandName=nameAndArgs.split(/\s+/u)[0];if(rootProgram.commands.some(existing=>existing.name()===commandName||existing.aliases().includes(commandName))){return new Command(commandName)}return registerOriginalCommand(nameAndArgs,...rest)})}async function registerCoreCommandFamilies(rootProgram,selection){ensureIdempotentTopLevelCommandRegistration(rootProgram);if(selection.setup){const{registerSetupCommands}=await loadSetupRegistrationModule();registerSetupCommands(rootProgram)}if(selection.listQuery){const{registerListQueryCommands}=await loadListQueryRegistrationModule();const commandFilter=typeof selection.targetCommandName==="string"&&LIST_QUERY_COMMAND_NAMES.has(selection.targetCommandName)?new Set([selection.targetCommandName]):void 0;registerListQueryCommands(rootProgram,commandFilter?{commandFilter}:void 0)}if(selection.mutation){const{registerMutationCommands}=await loadMutationRegistrationModule();registerMutationCommands(rootProgram,{targetCommandName:selection.targetCommandName})}if(selection.operation){const{registerOperationCommands}=await loadOperationRegistrationModule();registerOperationCommands(rootProgram)}}function createTelemetryCommandErrorEmitter(params){return async event=>{const errorCategory=resolveTelemetryErrorCategory(event.errorCode);const commandResolution=deriveTelemetryCommandResolution({ok:false,errorCode:event.errorCode,errorCategory});await emitTelemetryErrorEvent({command:event.command,args:params.invocationArgv,options:event.options,global:params.bootstrapGlobal,pm_version:CLI_VERSION,pm_root:params.bootstrapPmRoot,error_code:event.errorCode,error_message:event.errorMessage,exit_code:event.exitCode,error_category:errorCategory,command_resolution:commandResolution,resolution_stage:event.resolutionStage});return{errorCategory,commandResolution}}}async function prepareExtensionServicesForRunPmCliError(params){if(params.bootstrapGlobal.noExtensions||isStaticExtensionInventoryInvocation(params.invocationArgv)){return}const bootstrapProbe=buildBootstrapActivationProbe(params.invocationArgv);const discoverySnapshot=await loadRuntimeExtensionDiscoverySnapshot(params.bootstrapPmRoot);if(discoverySnapshot&&discoveryNeedsActivationForProbe(discoverySnapshot.discovery,bootstrapProbe)){const bootstrapSnapshot=await loadRuntimeExtensionSnapshot(params.bootstrapPmRoot,bootstrapProbe);setRecoveredExtensionServices(bootstrapSnapshot);return}if(discoverySnapshot){emitExtensionSkippedProfile(bootstrapProfileEnabled(params.invocationArgv),discoverySnapshot,bootstrapProbe)}setActiveExtensionServices({overrides:[]})}function setRecoveredExtensionServices(bootstrapSnapshot){if(!bootstrapSnapshot){setActiveExtensionServices({overrides:[]});return}setActiveExtensionServices(bootstrapSnapshot.services)}async function finishRunPmCliFailure(params){sentryFinishCommandSpan(false,params.errorMessage,{error_code:params.classificationCode,error_category:params.errorCategory,exit_code:params.exitCode,command_resolution:params.commandResolution,resolution_stage:params.resolutionStage});await runAndClearAfterCommandHooks({ok:false,error:params.errorMessage,exit_code:params.exitCode,error_code:params.classificationCode,error_category:params.errorCategory,command_resolution:params.commandResolution,resolution_stage:params.resolutionStage})}async function finishRunPmCliSuccessParse(){sentryFinishCommandSpan(true,void 0,{exit_code:EXIT_CODE.SUCCESS,command_resolution:"success",resolution_stage:"parse"});await runAndClearAfterCommandHooks({ok:true,exit_code:EXIT_CODE.SUCCESS,command_resolution:"success",resolution_stage:"parse"});process.exitCode=EXIT_CODE.SUCCESS}async function handleRunPmCliKnownError(context,numericExitCode){const hasExplicitExitCode=typeof numericExitCode==="number"&&Number.isFinite(numericExitCode);if(!(context.error instanceof PmCliError)&&(isCommanderError(context.error)||!hasExplicitExitCode)){return false}const errorMessage=describeUnknownError(context.error);const exitCode=context.error instanceof PmCliError?context.error.exitCode:normalizeThrownExitCode(numericExitCode);const rawContext=context.error instanceof PmCliError?context.error.context:void 0;const enrichedContext=buildPmCliRecoveryContext(rawContext,context.invocationArgv,errorMessage);const classification=classifyPmCliError(errorMessage,enrichedContext);const jsonErrorPayload=context.bootstrapGlobal.lean?projectLeanErrorEnvelope(formatPmCliErrorForJson(errorMessage,exitCode,enrichedContext)):formatPmCliErrorForJson(errorMessage,exitCode,enrichedContext);const renderedError=context.jsonErrors?JSON.stringify(context.bootstrapGlobal.tokenAccounting?attachOutputTokenAccounting(jsonErrorPayload,value=>`${JSON.stringify(value,null,2)}
2
2
  `):jsonErrorPayload,null,2):formatPmCliErrorForDisplay(errorMessage,enrichedContext);if(context.jsonErrors)writeStderr(`${renderedError}
3
3
  `);else printError(renderedError);const{errorCategory,commandResolution}=await context.emitTelemetryCommandError({command:context.attemptedCommand,errorCode:classification.code,errorMessage:classification.detail,exitCode,options:{bootstrap_global_options:context.bootstrapGlobal},resolutionStage:"execute"});const loggedHandledErrorToSentry=await maybeLogHandledCliErrorToSentry({command:context.attemptedCommand,error_code:classification.code,error_category:errorCategory,exit_code:exitCode,error_message:classification.detail,command_resolution:commandResolution,resolution_stage:"execute",source_context:activeTelemetryCommandContext?.source_context});await finishRunPmCliFailure({errorMessage,exitCode,classificationCode:classification.code,errorCategory,commandResolution,resolutionStage:"execute"});if(loggedHandledErrorToSentry){sentryCaptureCliError(wrapThrownErrorForSentry(context.error,errorMessage));await sentryFlush(HANDLED_ERROR_SENTRY_FLUSH_TIMEOUT_MS)}process.exitCode=exitCode;return true}async function handleUnknownHelpCommandError(context,code){const unknownToken=resolvePmCommandOperation(parseBootstrapHelpRequest(context.invocationArgv).commandPathTokens.join(" "))||resolveUnknownCommanderToken(context.invocationArgv);const unknownMessage=`unknown command '${unknownToken}'`;const pmRoot=resolvePmRoot(process.cwd(),context.bootstrapGlobal.path);const recoveryCommandDescriptors=await loadRuntimeExtensionCommandDescriptorsForRecovery(pmRoot);const recoveryProbe=buildBootstrapActivationProbe(context.invocationArgv);const failedExtensions=await loadExtensionRecoveryFailures(pmRoot,{},collectActivationCommandCandidates(recoveryProbe));const usageContext=await resolveCommanderUsageContext({message:unknownMessage},program,recoveryCommandDescriptors,{failedExtensions});const classification=classifyCommanderError(usageContext.message,usageContext.commandName,usageContext.allowedTypes,{unknownCommandExamples:usageContext.unknownCommandExamples,unknownCommandNextSteps:usageContext.unknownCommandNextSteps,attemptedCommand:usageContext.attemptedCommand,normalizedInvocationArgs:usageContext.normalizedInvocationArgs,providedOptionFlags:usageContext.providedOptionFlags,unknownOptionSuggestions:usageContext.unknownOptionSuggestions,suggestedRetryCommand:usageContext.suggestedRetryCommand,failedExtensions});const{errorCategory,commandResolution}=await context.emitTelemetryCommandError({command:unknownToken,errorCode:classification.code,errorMessage:classification.detail,exitCode:EXIT_CODE.USAGE,options:{bootstrap_global_options:context.bootstrapGlobal,commander_code:code??"commander.helpDisplayed"},resolutionStage:"parse"});const loggedHandledErrorToSentry=await maybeLogHandledCliErrorToSentry({command:unknownToken,error_code:classification.code,error_category:errorCategory,exit_code:EXIT_CODE.USAGE,error_message:classification.detail,command_resolution:commandResolution,resolution_stage:"parse"});const baseRenderedUsage=context.jsonErrors?await formatCommanderUsageJson({message:unknownMessage},program,recoveryCommandDescriptors,context.bootstrapGlobal.lean===true,{failedExtensions}):await formatCommanderUsageMessage({message:unknownMessage},program,recoveryCommandDescriptors,{failedExtensions});const renderedUsage=appendCommanderExtensionFailures(baseRenderedUsage,context.jsonErrors,failedExtensions);await finishRunPmCliFailure({errorMessage:unknownMessage,exitCode:EXIT_CODE.USAGE,classificationCode:classification.code,errorCategory,commandResolution,resolutionStage:"parse"});if(context.jsonErrors)writeStderr(`${renderedUsage}
4
4
  `);else printError(renderedUsage);if(loggedHandledErrorToSentry){await sentryFlush(HANDLED_ERROR_SENTRY_FLUSH_TIMEOUT_MS)}process.exitCode=EXIT_CODE.USAGE}async function handleRunPmCliHelpDisplayError(context,code,rawMessage){const isHelpDisplayCode=code==="commander.helpDisplayed"||code==="commander.help"||code==="commander.helpCommand";if(!isHelpDisplayCode&&!rawMessage.includes("(outputHelp)")){return false}const helpRequest=parseBootstrapHelpRequest(context.invocationArgv);if(helpRequest.requested&&!isKnownHelpCommandPath(program,helpRequest.commandPathTokens)){await handleUnknownHelpCommandError(context,code);return true}await finishRunPmCliSuccessParse();return true}async function handleRunPmCliCommanderUsageError(context,code){const usageContext=await resolveCommanderUsageContext(context.error,program,activeRuntimeExtensionCommandDescriptors);const classification=classifyCommanderError(usageContext.message,usageContext.commandName,usageContext.allowedTypes,{unknownCommandExamples:usageContext.unknownCommandExamples,unknownCommandNextSteps:usageContext.unknownCommandNextSteps,attemptedCommand:usageContext.attemptedCommand,normalizedInvocationArgs:usageContext.normalizedInvocationArgs,providedOptionFlags:usageContext.providedOptionFlags,unknownOptionSuggestions:usageContext.unknownOptionSuggestions,suggestedRetryCommand:usageContext.suggestedRetryCommand});const{errorCategory,commandResolution}=await context.emitTelemetryCommandError({command:context.attemptedCommand,errorCode:classification.code,errorMessage:classification.detail,exitCode:EXIT_CODE.USAGE,options:{bootstrap_global_options:context.bootstrapGlobal,commander_code:code},resolutionStage:"parse"});const loggedHandledErrorToSentry=await maybeLogHandledCliErrorToSentry({command:context.attemptedCommand,error_code:classification.code,error_category:errorCategory,exit_code:EXIT_CODE.USAGE,error_message:classification.detail,command_resolution:commandResolution,resolution_stage:"parse",source_context:activeTelemetryCommandContext?.source_context});const baseRenderedUsage=context.jsonErrors?await formatCommanderUsageJson(context.error,program,activeRuntimeExtensionCommandDescriptors,context.bootstrapGlobal.lean===true):await formatCommanderUsageMessage(context.error,program,activeRuntimeExtensionCommandDescriptors);const recoveryFailures=await loadUnknownCommandRecoveryFailures(classification.code,context.bootstrapPmRoot,{},collectActivationCommandCandidates(buildBootstrapActivationProbe(context.invocationArgv)));const renderedUsage=appendCommanderExtensionFailures(baseRenderedUsage,context.jsonErrors,recoveryFailures);await finishRunPmCliFailure({errorMessage:usageContext.message,exitCode:EXIT_CODE.USAGE,classificationCode:classification.code,errorCategory,commandResolution,resolutionStage:"parse"});if(context.jsonErrors)writeStderr(`${renderedUsage}
5
- `);else printError(renderedUsage);if(loggedHandledErrorToSentry){await sentryFlush(HANDLED_ERROR_SENTRY_FLUSH_TIMEOUT_MS)}process.exitCode=EXIT_CODE.USAGE}function shouldHandleRunPmCliCommanderError(error){if(typeof error!=="object"||error===null||!("code"in error)){return false}const code=error.code;if(typeof code==="string"&&(code==="commander.version"||code.startsWith("commander."))){return true}const rawMessage=String(error.message??"");return rawMessage.includes("(outputHelp)")}async function handleRunPmCliCommanderError(context){const code=context.error.code;const rawMessage=String(context.error.message??"");if(await handleRunPmCliHelpDisplayError(context,code,rawMessage)){return}if(code==="commander.version"){await finishRunPmCliSuccessParse();return}await handleRunPmCliCommanderUsageError(context,code)}async function handleRunPmCliError(params){const bootstrapGlobal=parseBootstrapGlobalOptions(params.invocationArgv);const bootstrapPmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);const context={error:params.error,invocationArgv:params.invocationArgv,bootstrapGlobal,jsonErrors:bootstrapGlobal.json,bootstrapPmRoot,attemptedCommand:parseBootstrapCommandName(params.invocationArgv)??"<unknown>",emitTelemetryCommandError:createTelemetryCommandErrorEmitter({invocationArgv:params.invocationArgv,bootstrapGlobal,bootstrapPmRoot})};await prepareExtensionServicesForRunPmCliError({invocationArgv:params.invocationArgv,bootstrapGlobal,bootstrapPmRoot});if(await handleRunPmCliKnownError(context,readThrownExitCode(params.error))){return}if(shouldHandleRunPmCliCommanderError(params.error)){await handleRunPmCliCommanderError(context);return}await handleGenericRunPmCliError({error:params.error,attemptedCommand:context.attemptedCommand,bootstrapGlobal,emitTelemetryCommandError:context.emitTelemetryCommandError})}function assertRequestedNamespaceAvailable(program2,invocationArgv,helpRequest){const tokens=helpRequest.requested?helpRequest.commandPathTokens:stripGlobalBootstrapTokens(invocationArgv);const requestedNamespace=findPmNamespacedCommand(tokens);if(requestedNamespace&&!findCommandByPath(program2,[...requestedNamespace.canonical_argv])){throw new CommanderError(EXIT_CODE.USAGE,"commander.unknownCommand",`unknown command '${requestedNamespace.alias}'`)}}async function runPmCliInReproducibleContext(rawArgv){program=createPmCliProgram(CLI_VERSION);attachProgramLifecycleHooks(program);runtimeExtensionSnapshotCache=null;runtimeExtensionDiscoverySnapshotCache=null;activeRuntimeExtensionCommandDescriptors=new Map;resetActiveExtensionRuntimeState();let invocationArgv=[...rawArgv];let restorePmAuthor;let restorePagerPolicy;try{const bootstrapInvocation=normalizeBootstrapInvocation(rawArgv);invocationArgv=bootstrapInvocation.argv;const invocationProcessArgv=[process.argv[0],process.argv[1],...invocationArgv];const isBareInvocation=invocationArgv.length===0;const bootstrapGlobal=parseBootstrapGlobalOptions(invocationArgv);if(bootstrapGlobal.authorMissingValue){throw new PmCliError("--author requires a non-empty value.",EXIT_CODE.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]})}restorePmAuthor=applyInvocationAuthorOverride(bootstrapGlobal.author);enforceExplicitRetryForFlagTypos(bootstrapInvocation);restorePagerPolicy=applyBootstrapPagerPolicy(invocationArgv);const registrationSelection=resolveCoreCommandRegistrationSelection(invocationArgv);await registerCoreCommandFamilies(program,registrationSelection);installCommandNamespaces(program,true);const registerDynamicCommands=shouldRegisterDynamicExtensionPaths(program,invocationArgv);if(registerDynamicCommands){await registerDynamicExtensionCommandPaths(program,invocationArgv)}else{activeRuntimeExtensionCommandDescriptors=new Map;setActiveExtensionServices({overrides:[]})}if(shouldRegisterRuntimeSchemaFlags(invocationArgv)){await registerRuntimeSchemaFieldFlags(program,invocationArgv)}installCommandNamespaces(program);const helpRequest=parseBootstrapHelpRequest(invocationArgv);assertRequestedNamespaceAvailable(program,invocationArgv,helpRequest);if(shouldAttachRichHelpTextForInvocation(invocationArgv)){attachRichHelpText(program,invocationArgv)}wrapProgramActionsForExtensionHandlers(program);const renderedBootstrapJsonHelp=await maybeRenderBootstrapJsonHelp(program,invocationArgv,activeRuntimeExtensionCommandDescriptors,rawArgv);if(renderedBootstrapJsonHelp){return}if(helpRequest.requested&&!isKnownHelpCommandPath(program,helpRequest.commandPathTokens)){throw new CommanderError(EXIT_CODE.USAGE,"commander.helpDisplayed","(outputHelp)")}if(isBareInvocation||isFullHelpDiscovery(invocationArgv)&&parseBootstrapCommandName(invocationArgv)===void 0){program.outputHelp();return}const invocationPmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);const invocationSettings=await readSettings(invocationPmRoot);const intentSnapshot=await loadContextIntentSnapshotForInvocation(invocationArgv,invocationPmRoot,bootstrapGlobal.noExtensions,loadRuntimeExtensionSnapshot);await runWithDiscoveredContextIntentContracts({pmRoot:invocationPmRoot,packages:intentSnapshot?.contextIntentPackages},()=>runWithHarnessDetectionSignals({env:{...process.env,PM_PATH:invocationPmRoot},argv:invocationProcessArgv,cwd:process.cwd()},()=>runWithWorkspaceHarnessSignalDescriptors(invocationSettings.agent_identity.harness_signals,()=>program.parseAsync(invocationProcessArgv),{probesEnabled:invocationSettings.agent_identity?.probes_enabled})))}catch(error){await handleRunPmCliError({error,invocationArgv})}finally{restorePagerPolicy?.();restorePmAuthor?.()}}async function runPmCli(rawArgv=process.argv.slice(2)){try{await runWithReproducibleProcessEnvironment(process.env,()=>runPmCliInReproducibleContext(rawArgv))}catch(error){await handleRunPmCliError({error,invocationArgv:[...rawArgv]})}}const _testOnly={activationCommandMatchesProbe,applyDynamicExtensionRootHelpVisibility,bootstrapProfileEnabled,buildBootstrapActivationProbe,buildPostActionTelemetryOutcome,buildPmCliRecoveryContext,buildRuntimeExtensionDiscoverySnapshotCacheKey,buildRuntimeExtensionActivationScope,buildRuntimeExtensionSnapshotCacheKey,buildRuntimeExtensionFilterForProbe,addRuntimeFieldOption,collectActivationCommandCandidates,collectExtensionFlagDefinitionsForCommand,collectExtensionFlagDefinitionsForInvocation,collectLeadingCommandArgs,collectParsedActivationCommandArgs,collectRuntimeFieldLooseFlagDefinitionsForCommand,commandHasLongOption,commandHasShortOption,commandPathNeedsSearchExtensions,commandPathNeedsTemplateExtensions,describeUnknownError,defaultPreflightDecision,discoveryNeedsActivationForProbe,emitExtensionProfile,emitExtensionSkippedProfile,emitSettingsReadWarnings,ensureIdempotentTopLevelCommandRegistration,enforceExplicitRetryForFlagTypos,envFlagEnabled,executeRegisteredRuntimeMigrations,extractCommandScopedOptions,extensionActivationCommands,extensionCapabilities,extensionNeedsActivationForProbe,extensionProvidesTemplatesRuntime,hasAnyCapability,hasGlobalExtensionContributions,handleGenericRunPmCliError,handleRunPmCliCommanderError,handleRunPmCliError,handleRunPmCliHelpDisplayError,handleRunPmCliKnownError,handleRunPmCliCommanderUsageError,handleUnknownHelpCommandError,inferMissingFieldsFromErrorMessage,inferPostActionErrorCode,inferPostActionFailureMessage,invocationRequestsVersion,isCommanderError,loadRuntimeExtensionCommandDescriptorsForRecovery,loadRuntimeExtensionDiscoverySnapshot,loadRuntimeExtensionSnapshot,maybeLoadRuntimeExtensions,maybeAttachCreateUpdatePolicyHelpText,maybeLogHandledCliErrorToSentry,matchesStaticExtensionCommand,normalizeTelemetryCommandResolution,normalizeTelemetryErrorCategory,normalizeTelemetryResolutionStage,normalizeThrownExitCode,probeUsesAnyFlag,prepareExtensionServicesForRunPmCliError,readRecordBoolean,readRecordNumber,readRecordString,recordCliReadOutputInvocationProvenance,registerDynamicExtensionCommandPaths,registerRuntimeSchemaFieldFlags,resolveCoreCommandRegistrationSelection,resolveStaticExtensionActivationDecision,resolveUnknownHelpToken:resolveUnknownCommanderToken,readThrownExitCode,runAndClearAfterCommandHooks,runRequiredExtensionCommand,shouldAttachRichHelpTextForInvocation,shouldLogHandledErrorToSentry,shouldRegisterDynamicExtensionPaths,shouldRegisterRuntimeSchemaFlags,shouldHandleRunPmCliCommanderError,setActiveExtensionHookContextForTest,setActiveRuntimeExtensionCommandDescriptorsForTest,setRecoveredExtensionServices,toLooseFieldDefinitionType,isImporterOrExporterCommandPath,validateDynamicExtensionCommandInvocation,wrapProgramActionsForExtensionHandlers,wrapThrownErrorForSentry};export{_testOnly,runPmCli};
5
+ `);else printError(renderedUsage);if(loggedHandledErrorToSentry){await sentryFlush(HANDLED_ERROR_SENTRY_FLUSH_TIMEOUT_MS)}process.exitCode=EXIT_CODE.USAGE}function shouldHandleRunPmCliCommanderError(error){if(typeof error!=="object"||error===null||!("code"in error)){return false}const code=error.code;if(typeof code==="string"&&(code==="commander.version"||code.startsWith("commander."))){return true}const rawMessage=String(error.message??"");return rawMessage.includes("(outputHelp)")}async function handleRunPmCliCommanderError(context){const code=context.error.code;const rawMessage=String(context.error.message??"");if(await handleRunPmCliHelpDisplayError(context,code,rawMessage)){return}if(code==="commander.version"){await finishRunPmCliSuccessParse();return}await handleRunPmCliCommanderUsageError(context,code)}async function handleRunPmCliError(params){const bootstrapGlobal=parseBootstrapGlobalOptions(params.invocationArgv);const bootstrapPmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);const context={error:params.error,invocationArgv:params.invocationArgv,bootstrapGlobal,jsonErrors:bootstrapGlobal.json,bootstrapPmRoot,attemptedCommand:parseBootstrapCommandName(params.invocationArgv)??"<unknown>",emitTelemetryCommandError:createTelemetryCommandErrorEmitter({invocationArgv:params.invocationArgv,bootstrapGlobal,bootstrapPmRoot})};await prepareExtensionServicesForRunPmCliError({invocationArgv:params.invocationArgv,bootstrapGlobal,bootstrapPmRoot});if(await handleRunPmCliKnownError(context,readThrownExitCode(params.error))){return}if(shouldHandleRunPmCliCommanderError(params.error)){await handleRunPmCliCommanderError(context);return}await handleGenericRunPmCliError({error:params.error,attemptedCommand:context.attemptedCommand,bootstrapGlobal,emitTelemetryCommandError:context.emitTelemetryCommandError})}function assertRequestedNamespaceAvailable(program2,invocationArgv,helpRequest){const tokens=helpRequest.requested?helpRequest.commandPathTokens:stripGlobalBootstrapTokens(invocationArgv);const requestedNamespace=findPmNamespacedCommand(tokens);if(requestedNamespace&&!findCommandByPath(program2,[...requestedNamespace.canonical_argv])){throw new CommanderError(EXIT_CODE.USAGE,"commander.unknownCommand",`unknown command '${requestedNamespace.alias}'`)}}async function runPmCliInReproducibleContext(rawArgv){program=createPmCliProgram(CLI_VERSION);attachProgramLifecycleHooks(program,rawArgv);runtimeExtensionSnapshotCache=null;runtimeExtensionDiscoverySnapshotCache=null;activeRuntimeExtensionCommandDescriptors=new Map;resetActiveExtensionRuntimeState();let invocationArgv=[...rawArgv];let restorePmAuthor;let restorePagerPolicy;try{const bootstrapInvocation=normalizeBootstrapInvocation(rawArgv);invocationArgv=bootstrapInvocation.argv;const invocationProcessArgv=[process.argv[0],process.argv[1],...invocationArgv];const isBareInvocation=invocationArgv.length===0;const bootstrapGlobal=parseBootstrapGlobalOptions(invocationArgv);if(bootstrapGlobal.authorMissingValue){throw new PmCliError("--author requires a non-empty value.",EXIT_CODE.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]})}restorePmAuthor=applyInvocationAuthorOverride(bootstrapGlobal.author);enforceExplicitRetryForFlagTypos(bootstrapInvocation);restorePagerPolicy=applyBootstrapPagerPolicy(invocationArgv);const registrationSelection=resolveCoreCommandRegistrationSelection(invocationArgv);await registerCoreCommandFamilies(program,registrationSelection);installCommandNamespaces(program,true);const registerDynamicCommands=shouldRegisterDynamicExtensionPaths(program,invocationArgv);if(registerDynamicCommands){await registerDynamicExtensionCommandPaths(program,invocationArgv)}else{activeRuntimeExtensionCommandDescriptors=new Map;setActiveExtensionServices({overrides:[]})}if(shouldRegisterRuntimeSchemaFlags(invocationArgv)){await registerRuntimeSchemaFieldFlags(program,invocationArgv)}installCommandNamespaces(program);const helpRequest=parseBootstrapHelpRequest(invocationArgv);assertRequestedNamespaceAvailable(program,invocationArgv,helpRequest);if(shouldAttachRichHelpTextForInvocation(invocationArgv)){attachRichHelpText(program,invocationArgv)}wrapProgramActionsForExtensionHandlers(program);const renderedBootstrapJsonHelp=await maybeRenderBootstrapJsonHelp(program,invocationArgv,activeRuntimeExtensionCommandDescriptors,rawArgv);if(renderedBootstrapJsonHelp){return}if(helpRequest.requested&&!isKnownHelpCommandPath(program,helpRequest.commandPathTokens)){throw new CommanderError(EXIT_CODE.USAGE,"commander.helpDisplayed","(outputHelp)")}if(isBareInvocation||isFullHelpDiscovery(invocationArgv)&&parseBootstrapCommandName(invocationArgv)===void 0){program.outputHelp();return}if(isStaticExtensionInventoryInvocation(invocationArgv)){await program.parseAsync(invocationProcessArgv);return}const invocationPmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);const invocationSettings=await readSettings(invocationPmRoot);const intentSnapshot=await loadContextIntentSnapshotForInvocation(invocationArgv,invocationPmRoot,bootstrapGlobal.noExtensions,loadRuntimeExtensionSnapshot);await runWithDiscoveredContextIntentContracts({pmRoot:invocationPmRoot,packages:intentSnapshot?.contextIntentPackages},()=>runWithHarnessDetectionSignals({env:{...process.env,PM_PATH:invocationPmRoot},argv:invocationProcessArgv,cwd:process.cwd()},()=>runWithWorkspaceHarnessSignalDescriptors(invocationSettings.agent_identity.harness_signals,()=>program.parseAsync(invocationProcessArgv),{probesEnabled:invocationSettings.agent_identity?.probes_enabled})))}catch(error){await handleRunPmCliError({error,invocationArgv})}finally{restorePagerPolicy?.();restorePmAuthor?.()}}async function runPmCli(rawArgv=process.argv.slice(2)){try{await runWithReproducibleProcessEnvironment(process.env,()=>runPmCliInReproducibleContext(rawArgv))}catch(error){await handleRunPmCliError({error,invocationArgv:[...rawArgv]})}}const _testOnly={activationCommandMatchesProbe,applyDynamicExtensionRootHelpVisibility,bootstrapProfileEnabled,buildBootstrapActivationProbe,buildPostActionTelemetryOutcome,buildPmCliRecoveryContext,buildRuntimeExtensionDiscoverySnapshotCacheKey,buildRuntimeExtensionActivationScope,buildRuntimeExtensionSnapshotCacheKey,buildRuntimeExtensionFilterForProbe,addRuntimeFieldOption,collectActivationCommandCandidates,collectExtensionFlagDefinitionsForCommand,collectExtensionFlagDefinitionsForInvocation,collectLeadingCommandArgs,collectParsedActivationCommandArgs,collectRuntimeFieldLooseFlagDefinitionsForCommand,commandHasLongOption,commandHasShortOption,commandPathNeedsSearchExtensions,commandPathNeedsTemplateExtensions,describeUnknownError,defaultPreflightDecision,discoveryNeedsActivationForProbe,emitExtensionProfile,emitExtensionSkippedProfile,emitSettingsReadWarnings,ensureIdempotentTopLevelCommandRegistration,enforceExplicitRetryForFlagTypos,envFlagEnabled,executeRegisteredRuntimeMigrations,extractCommandScopedOptions,extensionActivationCommands,extensionCapabilities,extensionNeedsActivationForProbe,extensionProvidesTemplatesRuntime,hasAnyCapability,hasGlobalExtensionContributions,handleGenericRunPmCliError,handleRunPmCliCommanderError,handleRunPmCliError,handleRunPmCliHelpDisplayError,handleRunPmCliKnownError,handleRunPmCliCommanderUsageError,handleUnknownHelpCommandError,inferMissingFieldsFromErrorMessage,inferPostActionErrorCode,inferPostActionFailureMessage,invocationRequestsVersion,isCommanderError,loadRuntimeExtensionCommandDescriptorsForRecovery,loadRuntimeExtensionDiscoverySnapshot,loadRuntimeExtensionSnapshot,maybeLoadRuntimeExtensions,maybeAttachCreateUpdatePolicyHelpText,maybeLogHandledCliErrorToSentry,matchesStaticExtensionCommand,normalizeTelemetryCommandResolution,normalizeTelemetryErrorCategory,normalizeTelemetryResolutionStage,normalizeThrownExitCode,probeUsesAnyFlag,prepareExtensionServicesForRunPmCliError,readRecordBoolean,readRecordNumber,readRecordString,recordCliReadOutputInvocationProvenance,registerDynamicExtensionCommandPaths,registerRuntimeSchemaFieldFlags,resolveCoreCommandRegistrationSelection,resolveStaticExtensionActivationDecision,resolveUnknownHelpToken:resolveUnknownCommanderToken,readThrownExitCode,runAndClearAfterCommandHooks,runRequiredExtensionCommand,shouldAttachRichHelpTextForInvocation,shouldLogHandledErrorToSentry,shouldRegisterDynamicExtensionPaths,shouldRegisterRuntimeSchemaFlags,shouldHandleRunPmCliCommanderError,setActiveExtensionHookContextForTest,setActiveRuntimeExtensionCommandDescriptorsForTest,setRecoveredExtensionServices,toLooseFieldDefinitionType,isImporterOrExporterCommandPath,validateDynamicExtensionCommandInvocation,wrapProgramActionsForExtensionHandlers,wrapThrownErrorForSentry};export{_testOnly,runPmCli};
6
6
  //# sourceMappingURL=main.js.map