@unbrained/pm-cli 2026.10.11 → 2026.10.12

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 (130) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +18 -0
  3. package/dist/cli/commander-usage.d.ts +5 -5
  4. package/dist/cli/commander-usage.js +3 -3
  5. package/dist/cli/error-guidance.d.ts +2 -0
  6. package/dist/cli/error-guidance.js +2 -2
  7. package/dist/cli/help-json-payload.js +1 -1
  8. package/dist/cli/main.d.ts +1 -0
  9. package/dist/cli/main.js +4 -4
  10. package/dist/cli/register-operations.d.ts +9 -4
  11. package/dist/cli/register-operations.js +1 -1
  12. package/dist/cli-bundle/bundle-manifest.json +1 -1
  13. package/dist/cli-bundle/chunks/{chunk-2JYTSTQP.js → chunk-3LQTJN4J.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-YMLF6QT7.js → chunk-6PZPUJW3.js} +28 -28
  15. package/dist/cli-bundle/chunks/{chunk-RUT3CCAG.js → chunk-B465HPS5.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-ESRACL6K.js → chunk-DT3KUUKY.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-SSY4OSJR.js → chunk-GUVKPOY6.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-ILQEZ4Y6.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-RBPOO46D.js → chunk-JRRXWH5B.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-MEWBSWE3.js → chunk-LH5QDBMN.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-KNW3RSLS.js → chunk-M5NDSW6E.js} +30 -30
  22. package/dist/cli-bundle/chunks/{chunk-K2UTE75T.js → chunk-MHPU2LDF.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-OBLO45UM.js → chunk-QM3M7GB5.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-S445XEYT.js → chunk-UABZJXIS.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-ZWRLAOA4.js → chunk-X2I2EEAS.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-list-query-T6BOR67M.js → register-list-query-OR33UEML.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-mutation-6NXR7SAJ.js → register-mutation-R34EJ3NH.js} +2 -2
  28. package/dist/cli-bundle/chunks/register-operations-UHSMEHSF.js +2 -0
  29. package/dist/cli-bundle/chunks/{register-setup-MAYFPKBX.js → register-setup-5E3PT22L.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-SIEGIPNT.js → chunk-7QIZB2F2.js} +7 -7
  31. package/dist/cli-bundle/focused-chunks/{chunk-PLTTMQAW.js → chunk-AJG3DBXR.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/chunk-AXBO53EQ.js +2 -0
  33. package/dist/cli-bundle/focused-chunks/{chunk-W5AE7GKZ.js → chunk-CYEZLKLL.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-PBCYGO7X.js → chunk-FXRWJEQ5.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-GVGFUD52.js → chunk-IKJFAU32.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-DMSADMEU.js → chunk-OGOLIS5R.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/chunk-PPH5N26M.js +2 -0
  38. package/dist/cli-bundle/focused-chunks/{chunk-WAOXID5J.js → chunk-RNAWRTQV.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-B3YW6H2I.js → chunk-RZVNGUT7.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-52UJEHEV.js → chunk-SV6YYZLR.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-EIOQNLBQ.js → chunk-TS46OZD5.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-KNJR2WUO.js → chunk-VBTLX5SN.js} +62 -62
  43. package/dist/cli-bundle/focused-chunks/{chunk-JGFSSR3G.js → chunk-YCOJLIDI.js} +3 -3
  44. package/dist/cli-bundle/focused-chunks/chunk-YDJT33JU.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-AU6VJGTY.js → chunk-Z4T3637Y.js} +2 -2
  46. package/dist/cli-bundle/main.js +22 -22
  47. package/dist/cli-bundle/sdk-authoring.js +1 -1
  48. package/dist/cli-bundle/sdk-contracts.js +1 -1
  49. package/dist/cli-bundle/sdk-core.js +31 -31
  50. package/dist/cli-bundle/sdk-governance.js +1 -1
  51. package/dist/cli-bundle/sdk-graph.js +1 -1
  52. package/dist/cli-bundle/sdk-merge.js +24 -24
  53. package/dist/cli-bundle/sdk-query.js +1 -1
  54. package/dist/cli-bundle/sdk-runtime.js +1 -1
  55. package/dist/cli-bundle/sdk-testing.js +1 -1
  56. package/dist/cli-bundle/sdk.js +8 -8
  57. package/dist/core/history/event-classification.d.ts +1 -1
  58. package/dist/core/history/event-classification.js +1 -1
  59. package/dist/core/item/item-format.d.ts +2 -0
  60. package/dist/core/item/item-format.js +2 -2
  61. package/dist/core/telemetry/runtime.d.ts +1 -1
  62. package/dist/core/telemetry/runtime.js +2 -2
  63. package/dist/core/test/background-runs.d.ts +1 -0
  64. package/dist/core/test/background-runs.js +2 -2
  65. package/dist/sdk/agent/command-suggestions.d.ts +2 -0
  66. package/dist/sdk/agent/command-suggestions.js +1 -1
  67. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  68. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  69. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  70. package/dist/sdk/cli-contracts/registration-helpers.d.ts +1 -4
  71. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  72. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  73. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  74. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  75. package/dist/sdk/core.d.ts +1 -0
  76. package/dist/sdk/core.js +1 -1
  77. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  78. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  79. package/dist/sdk/governance/artifact-ledgers.js +1 -1
  80. package/dist/sdk/index.d.ts +2 -0
  81. package/dist/sdk/index.js +1 -1
  82. package/dist/sdk/public-surface.json +1 -1
  83. package/dist/sdk/test/batch.js +1 -1
  84. package/dist/sdk/test/command-args.d.ts +4 -0
  85. package/dist/sdk/test/command-args.js +2 -0
  86. package/dist/sdk/test/entry.d.ts +3 -0
  87. package/dist/sdk/test/entry.js +1 -1
  88. package/dist/sdk/test/execution.d.ts +15 -4
  89. package/dist/sdk/test/execution.js +2 -2
  90. package/dist/sdk/test/prerequisites.d.ts +6 -0
  91. package/dist/sdk/test/prerequisites.js +2 -0
  92. package/dist/sdk/test/trust.js +1 -1
  93. package/dist/sdk/test/update.d.ts +55 -0
  94. package/dist/sdk/test/update.js +2 -0
  95. package/dist/types.d.ts +4 -0
  96. package/dist/types.js +1 -1
  97. package/docs/LINKED_TEST_EDITS.md +79 -0
  98. package/docs/RELEASING.md +19 -8
  99. package/docs/SDK.md +178 -636
  100. package/docs/SDK_EVIDENCE_TRACEABILITY.md +4 -0
  101. package/docs/TESTING.md +13 -0
  102. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  103. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +8 -3
  104. package/docs/performance/runner-qualification.md +36 -0
  105. package/marketplace.json +1 -1
  106. package/package.json +1 -1
  107. package/packages/pm-beads/package.json +1 -1
  108. package/packages/pm-calendar/package.json +1 -1
  109. package/packages/pm-command-kit/package.json +1 -1
  110. package/packages/pm-digital-twin/package.json +1 -1
  111. package/packages/pm-governance-audit/package.json +1 -1
  112. package/packages/pm-guide-shell/package.json +1 -1
  113. package/packages/pm-kanban/package.json +1 -1
  114. package/packages/pm-lifecycle-hooks/package.json +1 -1
  115. package/packages/pm-linked-test-adapters/package.json +1 -1
  116. package/packages/pm-search-advanced/package.json +1 -1
  117. package/packages/pm-templates/package.json +1 -1
  118. package/packages/pm-todos/package.json +1 -1
  119. package/packages/pm-vcs/package.json +1 -1
  120. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  121. package/plugins/pm-claude/package.json +1 -1
  122. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  123. package/plugins/pm-codex/package.json +1 -1
  124. package/plugins/pm-codex/plugin.json +1 -1
  125. package/runtime-dependencies.json +1 -1
  126. package/dist/cli-bundle/chunks/chunk-BXSXT5Z6.js +0 -2
  127. package/dist/cli-bundle/chunks/register-operations-PDOBQZUJ.js +0 -2
  128. package/dist/cli-bundle/focused-chunks/chunk-2CJWTLQG.js +0 -2
  129. package/dist/cli-bundle/focused-chunks/chunk-MJQ253F3.js +0 -2
  130. package/dist/cli-bundle/focused-chunks/chunk-WOEZJUA2.js +0 -2
@@ -1 +1 @@
1
- {"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.10.11","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","description":"Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.","version":"2026.10.11","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
1
+ {"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.10.12","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","description":"Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.","version":"2026.10.12","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026.10.12 - 2026-10-12
4
+
5
+ ### Fixed
6
+
7
+ - GH-1440: validate linked-test context at write time and distinguish execution refusals ([pm-gh1440](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1440.toon))
8
+ - Declare calendar package positional signatures in the SDK grammar census ([pm-kki6bf](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-kki6bf.toon))
9
+ - Reject sparse artifact ledger inputs through both public SDK exports ([pm-ledger-sparse-delivery](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/changesets/pm-ledger-sparse-delivery.toon))
10
+ - Prevent exact-tag recovery from republishing an accepted npm version while public metadata is unavailable ([pm-publication-acceptance-fence](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-publication-acceptance-fence.toon))
11
+ - Expose the test measurement run prerequisite in help and recovery ([pm-test-measure-prerequisite](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-test-measure-prerequisite.toon))
12
+
13
+ ### Other
14
+
15
+ - Edit linked-test metadata in place with preserved provenance and atomic history ([pm-9djr6d](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-9djr6d.toon))
16
+ - Keep linked-test SDK delivery within publication budgets using authoritative API references ([pm-4g4qv0](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-4g4qv0.toon))
17
+ - Preserve fail-closed startup benchmark runner qualification and complete diagnostics ([pm-runner-qualification-delivery](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-runner-qualification-delivery.toon))
18
+ - Include declared morning automation in daily release blocker alerts and successful recovery ([pm-automatic-release-alerts](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-automatic-release-alerts.toon))
19
+ - Deliver unambiguous registry-derived namespace recovery across installed Node and Bun consumers ([pm-namespace-recovery-delivery](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-namespace-recovery-delivery.toon))
20
+
3
21
  ## 2026.10.11 - 2026-10-11
4
22
 
5
23
  ### Fixed
@@ -49,19 +49,19 @@ declare function resolveOptionalPackageInstallHint(commandPath: string): {
49
49
  declare function collectInstalledPackageCommandPathHints(unknownToken: string, extensionDescriptors: ReadonlyMap<string, ExtensionCommandHelpDescriptor>): string[];
50
50
  declare function collectKnownLongFlags(commandName: string | undefined, contractsOverride?: CliFlagContract[]): string[];
51
51
  declare function suggestNearestLongFlags(unknownOption: string, knownFlags: string[]): string[];
52
- /** Implements build unknown command guidance from runtime for the public runtime surface of this module. */
53
- export declare function buildUnknownCommandGuidanceFromRuntime(rawMessage: string, root: Command, extensionDescriptors: ReadonlyMap<string, ExtensionCommandHelpDescriptor>): CommanderGuidanceContext | undefined;
52
+ /** Build inspection-only recovery from installed commands, preserving tracker scope and explicit extension policy in executable retries. */
53
+ export declare function buildUnknownCommandGuidanceFromRuntime(rawMessage: string, root: Command, extensionDescriptors: ReadonlyMap<string, ExtensionCommandHelpDescriptor>, invocationArgv?: readonly string[]): CommanderGuidanceContext | undefined;
54
54
  /** Implements resolve child command by token for the public runtime surface of this module. */
55
55
  export declare function resolveChildCommandByToken(parent: Command, token: string): Command | undefined;
56
56
  /** Implements check whether known help command path for the public runtime surface of this module. */
57
57
  export declare function isKnownHelpCommandPath(root: Command, commandPathTokens: string[]): boolean;
58
58
  declare function resolveSuggestedRetryForMissingOption(message: string, invocationArgv: string[]): string | undefined;
59
59
  /** Resolve runtime command ownership, workspace types and executable recovery guidance for a parser refusal. */
60
- export declare function resolveCommanderUsageContext(error: unknown, rootProgram: Command, extensionDescriptors: ReadonlyMap<string, ExtensionCommandHelpDescriptor>, guidanceOverrides?: Partial<CommanderGuidanceContext>): Promise<CommanderUsageContext>;
60
+ export declare function resolveCommanderUsageContext(error: unknown, rootProgram: Command, extensionDescriptors: ReadonlyMap<string, ExtensionCommandHelpDescriptor>, guidanceOverrides?: Partial<CommanderGuidanceContext>, invocationArgs?: readonly string[]): Promise<CommanderUsageContext>;
61
61
  /** Implements format commander usage message for the public runtime surface of this module. */
62
- export declare function formatCommanderUsageMessage(error: unknown, rootProgram: Command, extensionDescriptors: ReadonlyMap<string, ExtensionCommandHelpDescriptor>, guidanceOverrides?: Partial<CommanderGuidanceContext>): Promise<string>;
62
+ export declare function formatCommanderUsageMessage(error: unknown, rootProgram: Command, extensionDescriptors: ReadonlyMap<string, ExtensionCommandHelpDescriptor>, guidanceOverrides?: Partial<CommanderGuidanceContext>, invocationArgs?: readonly string[]): Promise<string>;
63
63
  /** Implements format commander usage json for the public runtime surface of this module. */
64
- export declare function formatCommanderUsageJson(error: unknown, rootProgram: Command, extensionDescriptors: ReadonlyMap<string, ExtensionCommandHelpDescriptor>, lean?: boolean, guidanceOverrides?: Partial<CommanderGuidanceContext>): Promise<string>;
64
+ export declare function formatCommanderUsageJson(error: unknown, rootProgram: Command, extensionDescriptors: ReadonlyMap<string, ExtensionCommandHelpDescriptor>, lean?: boolean, guidanceOverrides?: Partial<CommanderGuidanceContext>, invocationArgs?: readonly string[]): Promise<string>;
65
65
  /** Public contract for test only, shared by SDK and presentation-layer consumers. */
66
66
  export declare const _testOnly: {
67
67
  collectKnownLongFlags: typeof collectKnownLongFlags;
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="fff71664-962d-55f6-b21e-dd2c7ca0f419")}catch{}})();import{pathExists,resolveItemTypeRegistry,EXIT_CODE,getSettingsPath,resolvePmRoot,readSettings,getActiveExtensionRegistrations,locateItem,runActiveServiceOverride,levenshteinDistanceWithinLimit}from"../sdk/runtime-primitives.js";import{BUILTIN_ITEM_TYPE_VALUES}from"../types/index.js";import{PM_CORE_COMMAND_NAMES,resolveSubcommandFlagContractsForCommand}from"../sdk/cli-contracts.js";import{formatCommanderErrorForDisplay,formatCommanderErrorForJson,projectLeanErrorEnvelope}from"./error-guidance.js";import{normalizeHelpCommandPath}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{EXECUTABLE_COMMAND_ALIASES,findBootstrapCommandTokenIndex,normalizeBootstrapInvocation,parseBootstrapHelpRequest,parseBootstrapGlobalOptions,parseBootstrapCommandName}from"./bootstrap-args.js";import{extractProvidedOptionFlags,normalizeLongFlag,renderPmCommand}from"./argv-utils.js";import{normalizeExtensionNameForMatch}from"./commands/extension/shared.js";import{canonicalizeCommandSuggestions,rankCommandPaths}from"../sdk/agent/command-suggestions.js";import{renderMissingOptionRetry}from"../sdk/agent/command-recovery.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{findPmNamespacedCommand,resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";const BUILTIN_TYPE_HELP_VALUES=BUILTIN_ITEM_TYPE_VALUES.join("|"),OPTIONAL_PACKAGE_INSTALL_HINTS={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}},SCHEMA_SUBCOMMAND_VALUES=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function getSemanticUnknownOptionSuggestions(commandName,unknownOption){const commandSuggestions=SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS[commandName];if(!commandSuggestions)return[];const normalizedUnknown=normalizeLongFlag(unknownOption);for(const[flag,suggestions]of Object.entries(commandSuggestions))if(normalizeLongFlag(flag)===normalizedUnknown)return suggestions;return[]}function appendCommanderExtensionFailures(renderedUsage,json,failures){if(failures.length===0)return renderedUsage;if(json){const primaryFailure2=failures.find(entry=>entry.declared_command_match===!0),{token_accounting:priorAccounting,...usage}=JSON.parse(renderedUsage),enriched={...usage,...primaryFailure2?{extension_command_failure:{code:"extension_command_activation_failed",extension:primaryFailure2.name,layer:primaryFailure2.layer,error:primaryFailure2.error,recovery_commands:primaryFailure2.recovery_commands??[]}}:{},failed_extensions:failures};return JSON.stringify(priorAccounting===void 0?enriched:attachOutputTokenAccounting(enriched,value=>`${JSON.stringify(value,null,2)}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b4a71f6d-b74c-557f-979d-973c26664e84")}catch{}})();import{pathExists,resolveItemTypeRegistry,EXIT_CODE,getSettingsPath,resolvePmRoot,readSettings,getActiveExtensionRegistrations,locateItem,runActiveServiceOverride,levenshteinDistanceWithinLimit}from"../sdk/runtime-primitives.js";import{BUILTIN_ITEM_TYPE_VALUES}from"../types/index.js";import{PM_CORE_COMMAND_NAMES,resolveSubcommandFlagContractsForCommand}from"../sdk/cli-contracts.js";import{formatCommanderErrorForDisplay,formatCommanderErrorForJson,projectLeanErrorEnvelope}from"./error-guidance.js";import{normalizeHelpCommandPath}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{EXECUTABLE_COMMAND_ALIASES,findBootstrapCommandTokenIndex,normalizeBootstrapInvocation,parseBootstrapHelpRequest,parseBootstrapGlobalOptions,parseBootstrapCommandName}from"./bootstrap-args.js";import{extractProvidedOptionFlags,normalizeLongFlag,renderPmCommand}from"./argv-utils.js";import{normalizeExtensionNameForMatch}from"./commands/extension/shared.js";import{canonicalizeCommandSuggestions,rankCommandPaths,resolveMisnestedCommandPath}from"../sdk/agent/command-suggestions.js";import{renderMissingOptionRetry}from"../sdk/agent/command-recovery.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{findPmNamespacedCommand,resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";const BUILTIN_TYPE_HELP_VALUES=BUILTIN_ITEM_TYPE_VALUES.join("|"),OPTIONAL_PACKAGE_INSTALL_HINTS={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}},SCHEMA_SUBCOMMAND_VALUES=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function getSemanticUnknownOptionSuggestions(commandName,unknownOption){const commandSuggestions=SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS[commandName];if(!commandSuggestions)return[];const normalizedUnknown=normalizeLongFlag(unknownOption);for(const[flag,suggestions]of Object.entries(commandSuggestions))if(normalizeLongFlag(flag)===normalizedUnknown)return suggestions;return[]}function appendCommanderExtensionFailures(renderedUsage,json,failures){if(failures.length===0)return renderedUsage;if(json){const primaryFailure2=failures.find(entry=>entry.declared_command_match===!0),{token_accounting:priorAccounting,...usage}=JSON.parse(renderedUsage),enriched={...usage,...primaryFailure2?{extension_command_failure:{code:"extension_command_activation_failed",extension:primaryFailure2.name,layer:primaryFailure2.layer,error:primaryFailure2.error,recovery_commands:primaryFailure2.recovery_commands??[]}}:{},failed_extensions:failures};return JSON.stringify(priorAccounting===void 0?enriched:attachOutputTokenAccounting(enriched,value=>`${JSON.stringify(value,null,2)}
2
2
  `),null,2)}const details=failures.map(entry=>`- ${entry.layer}:${entry.name}: ${entry.error}`).join(`
3
3
  `),primaryFailure=failures.find(entry=>entry.declared_command_match===!0);if(!primaryFailure)return`${renderedUsage}
4
4
  Extension activation failures:
@@ -10,7 +10,7 @@ ${recovery}`:""}
10
10
 
11
11
  ${renderedUsage}
12
12
  Extension activation failures:
13
- ${details}`}function resolveUnknownCommanderToken(invocationArgv){return parseBootstrapHelpRequest(invocationArgv).commandPathTokens[0]??parseBootstrapCommandName(invocationArgv)??"<command>"}function collectRuntimeCommandPaths(root,extensionDescriptors){const commandPaths=new Set,queue=[...root.commands];for(;queue.length>0;){const current=queue.shift();if(!current)continue;const normalizedPath=normalizeHelpCommandPath(getCommandPath(current)),hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));normalizedPath.length>0&&!hasInternalSegment&&commandPaths.add(normalizedPath),queue.push(...current.commands)}for(const descriptorPath of extensionDescriptors.keys()){const normalizedPath=normalizeHelpCommandPath(descriptorPath),hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));normalizedPath.length>0&&!hasInternalSegment&&commandPaths.add(normalizedPath)}return[...commandPaths].sort((left,right)=>left.localeCompare(right))}function scoreCommandPathMatch(commandPath,queryToken){const normalizedPath=commandPath.trim().toLowerCase(),normalizedToken=queryToken.trim().toLowerCase();if(normalizedToken.length===0)return Number.POSITIVE_INFINITY;const pathSegments=normalizedPath.split(" ");if(normalizedPath===normalizedToken)return 0;if(pathSegments.includes(normalizedToken))return 1;if(pathSegments.some(segment=>segment.startsWith(normalizedToken)))return 2;if(normalizedPath.includes(normalizedToken))return 3;const maxDistance=normalizedToken.length>=5?2:1;let bestDistance=Number.POSITIVE_INFINITY;for(const segment of pathSegments){const distance=levenshteinDistanceWithinLimit(segment,normalizedToken,maxDistance);distance!==null&&(bestDistance=Math.min(bestDistance,distance))}return Number.isFinite(bestDistance)?4+bestDistance:Number.POSITIVE_INFINITY}function toComparableFlag(flag){return normalizeLongFlag(flag).slice(2).replace(/-/g,"")}function renderAttemptedCommand(argv){return renderPmCommand(argv)}function resolveOptionalPackageInstallHint(commandPath){const canonicalPath=resolvePmCommandAlias(commandPath)?.canonical??EXECUTABLE_COMMAND_ALIASES[commandPath]??commandPath,topLevel=canonicalPath.split(" ")[0]?.trim().toLowerCase();if(!topLevel)return null;const packageAlias=OPTIONAL_PACKAGE_INSTALL_HINTS[topLevel];return packageAlias?{packageAlias,canonicalPath,installCommand:`pm package install ${packageAlias} --project`}:null}function normalizePackageCommandAliasToken(value){let normalized=normalizeExtensionNameForMatch(value);for(const prefix of["@unbrained/","builtin-","pm-"])normalized.startsWith(prefix)&&(normalized=normalized.slice(prefix.length));return normalized}function collectInstalledPackageCommandPathHints(unknownToken,extensionDescriptors){const normalizedUnknown=normalizePackageCommandAliasToken(unknownToken);if(normalizedUnknown.length===0)return[];const hints=[];for(const descriptor of extensionDescriptors.values()){const identifiers=new Set,source=descriptor.source;if(source)for(const identifier of[source.name,source.package]){const normalizedIdentifier=normalizePackageCommandAliasToken(identifier??"");normalizedIdentifier.length>0&&identifiers.add(normalizedIdentifier)}identifiers.size!==0&&[...identifiers].some(identifier=>identifier===normalizedUnknown||identifier.includes(normalizedUnknown)||normalizedUnknown.includes(identifier))&&hints.push(descriptor.command)}return[...new Set(hints)].sort((left,right)=>left.localeCompare(right))}function collectKnownLongFlags(commandName,contractsOverride){const flags=new Set,contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName);for(const contract of contracts){contract.flag.startsWith("--")&&flags.add(normalizeLongFlag(contract.flag));for(const alias of contract.aliases??[])alias.startsWith("--")&&flags.add(normalizeLongFlag(alias))}return[...flags].sort((left,right)=>left.localeCompare(right))}function suggestNearestLongFlags(unknownOption,knownFlags){if(!unknownOption.startsWith("--"))return[];const unknownComparable=toComparableFlag(unknownOption);if(unknownComparable.length===0)return[];const maxDistance=unknownComparable.length>=8?2:1,candidates=[];for(const flag of knownFlags){const flagComparable=toComparableFlag(flag);if(flagComparable===unknownComparable)continue;if(unknownComparable.length>=3&&flagComparable.startsWith(unknownComparable)){candidates.push({flag,rank:0,distance:flagComparable.length-unknownComparable.length});continue}const distance=levenshteinDistanceWithinLimit(unknownComparable,flagComparable,maxDistance);distance===null||distance<=0||candidates.push({flag,rank:1,distance})}return candidates.sort((left,right)=>left.rank!==right.rank?left.rank-right.rank:left.distance!==right.distance?left.distance-right.distance:left.flag.localeCompare(right.flag)).map(entry=>entry.flag).slice(0,3)}let crossCommandFlagIndexCache;const CROSS_COMMAND_FLAG_EXCLUSIONS=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function getCrossCommandFlagIndex(){if(crossCommandFlagIndexCache)return crossCommandFlagIndexCache;const index=new Map;for(const command of PM_CORE_COMMAND_NAMES)if(!CROSS_COMMAND_FLAG_EXCLUSIONS.has(command))for(const flag of collectKnownLongFlags(command)){const commands=index.get(flag)??[];commands.push(command),index.set(flag,commands)}return crossCommandFlagIndexCache=index,crossCommandFlagIndexCache}function findOtherCommandsForFlag(unknownOption,currentCommand){if(!unknownOption.startsWith("--"))return[];const commands=getCrossCommandFlagIndex().get(normalizeLongFlag(unknownOption));if(!commands)return[];const normalizedCurrent=currentCommand?.trim().toLowerCase(),currentFlags=new Set(collectKnownLongFlags(normalizedCurrent));return[...new Set(commands.filter(command=>command!==normalizedCurrent).map(command=>({command,sharedFlagCount:collectKnownLongFlags(command).filter(flag=>currentFlags.has(flag)).length})).sort((left,right)=>left.sharedFlagCount!==right.sharedFlagCount?right.sharedFlagCount-left.sharedFlagCount:left.command.localeCompare(right.command)).map(({command})=>resolvePmCommandAlias(command)?.canonical??command))]}function rewriteUnknownOptionArgv(argv,unknownOption,replacementFlag){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(!token.startsWith("--"))continue;const equalsIndex=token.indexOf("="),key=equalsIndex>=0?token.slice(0,equalsIndex):token;if(normalizeLongFlag(key)!==normalizeLongFlag(unknownOption))continue;const next=[...argv];return next[index]=equalsIndex>=0?`${replacementFlag}${token.slice(equalsIndex)}`:replacementFlag,next}}function scoreRuntimeCommandCandidates(params){const commandPathSet=new Set(params.commandPaths),scoreAgainstUnknown=candidatePath=>Math.min(scoreCommandPathMatch(candidatePath,params.normalizedUnknown),params.primaryToken!==params.normalizedUnknown?scoreCommandPathMatch(candidatePath,params.primaryToken):Number.POSITIVE_INFINITY),scoresByCommandPath=new Map,recordCandidateScore=(commandPath,score)=>{if(!Number.isFinite(score)||!commandPathSet.has(commandPath))return;const existing=scoresByCommandPath.get(commandPath);(existing===void 0||score<existing)&&scoresByCommandPath.set(commandPath,score)};for(const commandPath of params.commandPaths)recordCandidateScore(commandPath,scoreAgainstUnknown(commandPath));for(const[aliasToken,canonicalPath]of Object.entries(EXECUTABLE_COMMAND_ALIASES))aliasToken!=="read"&&recordCandidateScore(canonicalPath,scoreAgainstUnknown(aliasToken));return[...scoresByCommandPath.entries()].sort(([leftPath,leftScore],[rightPath,rightScore])=>leftScore!==rightScore?leftScore-rightScore:leftPath.localeCompare(rightPath)).map(([commandPath])=>commandPath)}function resolveUnknownCommandCandidates(params){const exactAlias=resolvePmCommandAlias(params.normalizedUnknown),semanticCandidates=rankCommandPaths(params.commandPaths,params.primaryToken),rankedCandidates=scoreRuntimeCommandCandidates(params),installedPackageCandidates=collectInstalledPackageCommandPathHints(params.primaryToken,params.extensionDescriptors).filter(commandPath=>params.commandPaths.includes(commandPath));return canonicalizeCommandSuggestions([...exactAlias&&params.commandPaths.includes(exactAlias.canonical)?[exactAlias.canonical_argv.join(" ")]:[],...semanticCandidates,...rankedCandidates,...installedPackageCandidates],params.commandPaths,params.primaryToken).filter(path=>!params.normalizedUnknown.includes(" ")||path!==params.normalizedUnknown)}function resolveUnknownCommandFallbacks(commandPaths){return[...new Set(commandPaths.map(commandPath=>commandPath.split(" ")[0]).filter(segment=>segment.length>0))].sort((left,right)=>left.localeCompare(right))}function buildUnknownCommandExamples(suggestedPaths,hasConcreteCandidates){const suggestedExamples=suggestedPaths.map(path=>`pm ${path} --help`);return hasConcreteCandidates?[...new Set([...suggestedExamples,"pm --help --all"])]:[...new Set(["pm --help --all",...suggestedExamples])]}function buildUnknownCommandGuidanceFromRuntime(rawMessage,root,extensionDescriptors){const unknownCommandMatch=rawMessage.match(/unknown command '([^']+)'/i);if(!unknownCommandMatch||typeof unknownCommandMatch[1]!="string")return;const normalizedUnknown=normalizeHelpCommandPath(unknownCommandMatch[1]);if(normalizedUnknown.length===0)return;const commandPaths=collectRuntimeCommandPaths(root,extensionDescriptors);if(commandPaths.length===0)return;const optionalPackageHint=resolveOptionalPackageInstallHint(normalizedUnknown);if(optionalPackageHint&&!commandPaths.includes(optionalPackageHint.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[optionalPackageHint.installCommand,`pm ${optionalPackageHint.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${normalizedUnknown}" is provided by the "${optionalPackageHint.packageAlias}" package. Install it with: ${optionalPackageHint.installCommand}. Command after installation: pm ${optionalPackageHint.canonicalPath}.`],suggestedRetryCommand:optionalPackageHint.installCommand};const primaryToken=normalizedUnknown.split(" ")[0],combinedCandidates=resolveUnknownCommandCandidates({commandPaths,normalizedUnknown,primaryToken,extensionDescriptors}),fallbackTopLevel=resolveUnknownCommandFallbacks(commandPaths),suggestedPaths=(combinedCandidates.length>0?combinedCandidates:canonicalizeCommandSuggestions(fallbackTopLevel,commandPaths)).slice(0,3),examples=buildUnknownCommandExamples(suggestedPaths,combinedCandidates.length>0),didYouMean=combinedCandidates.length>0?`Did you mean: ${suggestedPaths.join(", ")}?`:null;return{unknownCommandExamples:examples,unknownCommandNextSteps:[...didYouMean?[didYouMean]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...didYouMean?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function dedupeStrings(values){return Array.from(new Set(values))}function firstWhitespaceSeparatedToken(input){let token="";for(const character of input){if(character===" "||character===" "||character===`
14
- `||character==="\r"||character==="\f"||character==="\v")break;token+=character}return token}function trimTrailingPunctuationToken(token){let end=token.length;for(;end>0;){const character=token[end-1];if(character!==","&&character!==":"&&character!==";")break;end-=1}return token.slice(0,end)}function resolveChildCommandByToken(parent,token){const normalizedToken=token.trim().toLowerCase();return parent.commands.find(candidate=>candidate.name().trim().toLowerCase()===normalizedToken?!0:(typeof candidate.aliases=="function"?candidate.aliases():[]).some(alias=>alias.trim().toLowerCase()===normalizedToken))}function isKnownHelpCommandPath(root,commandPathTokens){if(commandPathTokens.length===0)return!0;let current=root;for(const[tokenIndex,token]of commandPathTokens.entries()){const next=resolveChildCommandByToken(current,token);if(!next){const declaredArguments=current.registeredArguments;return declaredArguments.length>0&&(current.commands.length===0||declaredArguments[0]?.required===!0)&&(declaredArguments.at(-1)?.variadic===!0||commandPathTokens.length-tokenIndex<=declaredArguments.length)}current=next}return!0}async function resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName){try{const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);if(!await pathExists(getSettingsPath(pmRoot)))return{allowedTypes:BUILTIN_TYPE_HELP_VALUES};const settings=await readSettings(pmRoot),extensionRegistrations=bootstrapGlobal.noExtensions?void 0:getActiveExtensionRegistrations(),typeRegistry=resolveItemTypeRegistry(settings,extensionRegistrations);let verifiedCollectionItemId;if(/too many arguments/i.test(message)&&["comments","docs","files","learnings","notes","test"].includes(commandName??"")){const commandIndex=invocationArgv.findIndex(token=>token===commandName),candidate=invocationArgv[commandIndex+2];if(invocationArgv[commandIndex+1]?.toLowerCase()==="add"&&candidate!==void 0&&!candidate.startsWith("-"))try{verifiedCollectionItemId=(await locateItem(pmRoot,candidate,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder))?.id}catch{}}return{allowedTypes:typeRegistry.types.length>0?typeRegistry.types.join("|"):BUILTIN_TYPE_HELP_VALUES,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,verifiedCollectionItemId}}catch{return{allowedTypes:BUILTIN_TYPE_HELP_VALUES}}}function resolveUnknownOptionSuggestions(message,commandName){const match=message.match(/unknown option '([^']+)'/i),suggestions=match&&commandName?dedupeStrings([...getSemanticUnknownOptionSuggestions(commandName,match[1]),...suggestNearestLongFlags(match[1],collectKnownLongFlags(commandName))]):void 0,otherCommands=match?findOtherCommandsForFlag(match[1],commandName):[],declaredOnPath=match!==null&&collectKnownLongFlags(commandName).includes(normalizeLongFlag(match[1]));return{match,suggestions,otherCommands,scope:declaredOnPath?"declared_on_path":otherCommands.length>0?"declared_elsewhere":"declared_nowhere"}}function resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOptionMatch,unknownOptionSuggestions){if(!unknownOptionMatch||!unknownOptionSuggestions||unknownOptionSuggestions.length===0)return;const rewritten=rewriteUnknownOptionArgv(invocationArgv,unknownOptionMatch[1],unknownOptionSuggestions[0]);return rewritten?renderAttemptedCommand(rewritten):void 0}function resolveSuggestedRetryForMissingOption(message,invocationArgv){const missingRequiredOption=message.match(/required option '([^']+)' not specified/i),requiredOptionToken=missingRequiredOption?.[1]?trimTrailingPunctuationToken(firstWhitespaceSeparatedToken(missingRequiredOption[1].trim())):void 0;if(!requiredOptionToken?.startsWith("--"))return;const commandName=parseBootstrapCommandName(invocationArgv);if(commandName)return renderMissingOptionRetry(invocationArgv,commandName,[requiredOptionToken])}function resolveSplitSchemaSubcommand(message,invocationArgv){if(!/too many arguments/i.test(message))return;const commandIndex=findBootstrapCommandTokenIndex(invocationArgv),namespaced=findPmNamespacedCommand(invocationArgv.slice(commandIndex));if(namespaced?.alias!=="schema")return;const schemaIndex=commandIndex+namespaced.canonical_argv.length-1,verb=invocationArgv[schemaIndex+1]?.trim().toLowerCase(),noun=invocationArgv[schemaIndex+2]?.trim().toLowerCase();if(!verb||!noun)return;const joined=`${verb}-${noun}`;if(!SCHEMA_SUBCOMMAND_VALUES.includes(joined))return;const rewritten=[...invocationArgv.slice(0,schemaIndex+1),joined,...invocationArgv.slice(schemaIndex+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${verb} ${noun}`,unknownSubcommandAllowedValues:[...SCHEMA_SUBCOMMAND_VALUES],suggestedRetryCommand:renderAttemptedCommand(rewritten)}}function resolveRecoveryCommandName(message,invocationArgv,rootProgram,extensionDescriptors){const commandIndex=findBootstrapCommandTokenIndex(invocationArgv),inferred=findPmNamespacedCommand(invocationArgv.slice(commandIndex))?.alias??parseBootstrapCommandName(invocationArgv);if(!/unknown option /i.test(message)||inferred===void 0)return inferred;const canonical=resolvePmCommandAlias(inferred)?.canonical??inferred;return PM_CORE_COMMAND_NAMES.some(name=>name===inferred)||collectRuntimeCommandPaths(rootProgram,extensionDescriptors).includes(canonical)?inferred:void 0}async function resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides={}){const message=(typeof error=="object"&&error!==null?error.message:void 0)??"Invalid command usage",invocationArgv=normalizeBootstrapInvocation(process.argv.slice(2)).argv,bootstrapGlobal=parseBootstrapGlobalOptions(invocationArgv),commandName=resolveRecoveryCommandName(message,invocationArgv,rootProgram,extensionDescriptors),attemptedCommand=renderAttemptedCommand(invocationArgv),providedOptionFlags=extractProvidedOptionFlags(invocationArgv),workspaceUsage=await resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName),allowedTypes=workspaceUsage.allowedTypes,unknownCommandGuidance=buildUnknownCommandGuidanceFromRuntime(message,rootProgram,extensionDescriptors),unknownOption=resolveUnknownOptionSuggestions(message,commandName),splitSchemaSubcommand=resolveSplitSchemaSubcommand(message,invocationArgv),suggestedRetryCommand=splitSchemaSubcommand?.suggestedRetryCommand??resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOption.match,unknownOption.suggestions)??resolveSuggestedRetryForMissingOption(message,invocationArgv);return{message,commandName,allowedTypes,attemptedCommand,normalizedInvocationArgs:[...invocationArgv],providedOptionFlags,unknownOptionSuggestions:unknownOption.suggestions,unknownOptionOtherCommands:unknownOption.otherCommands.length>0?unknownOption.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:unknownOption.otherCommands.length>0?unknownOption.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:unknownOption.otherCommands.length>12||void 0,unknownOptionScope:unknownOption.scope,suggestedRetryCommand,verifiedCollectionItemId:workspaceUsage.verifiedCollectionItemId,...splitSchemaSubcommand,...unknownCommandGuidance,...guidanceOverrides}}async function formatCommanderUsageMessage(error,rootProgram,extensionDescriptors,guidanceOverrides={}){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides),{message,commandName,allowedTypes,unknownCommandExamples,unknownCommandNextSteps,attemptedCommand,normalizedInvocationArgs,providedOptionFlags,unknownOptionSuggestions,unknownOptionOtherCommands,unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated,unknownOptionScope,unknownSubcommandPath,unknownSubcommandToken,unknownSubcommandAllowedValues,suggestedRetryCommand,verifiedCollectionItemId,failedExtensions}=usageContext,formatted=formatCommanderErrorForDisplay(message,commandName,allowedTypes,{unknownCommandExamples,unknownCommandNextSteps,attemptedCommand,normalizedInvocationArgs,providedOptionFlags,unknownOptionSuggestions,unknownOptionOtherCommands,unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated,unknownOptionScope,unknownSubcommandPath,unknownSubcommandToken,unknownSubcommandAllowedValues,suggestedRetryCommand,verifiedCollectionItemId,failedExtensions}),serviceOverride=await runActiveServiceOverride("help_format",{message:formatted,command:commandName,allowed_types:allowedTypes});return serviceOverride.handled&&typeof serviceOverride.result=="string"?serviceOverride.result:formatted}async function formatCommanderUsageJson(error,rootProgram,extensionDescriptors,lean=!1,guidanceOverrides={}){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides),envelope=formatCommanderErrorForJson(usageContext.message,usageContext.commandName,usageContext.allowedTypes,EXIT_CODE.USAGE,{unknownCommandExamples:usageContext.unknownCommandExamples,unknownCommandNextSteps:usageContext.unknownCommandNextSteps,attemptedCommand:usageContext.attemptedCommand,normalizedInvocationArgs:usageContext.normalizedInvocationArgs,providedOptionFlags:usageContext.providedOptionFlags,unknownOptionSuggestions:usageContext.unknownOptionSuggestions,unknownOptionOtherCommands:usageContext.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:usageContext.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:usageContext.unknownOptionOtherCommandsTruncated,unknownOptionScope:usageContext.unknownOptionScope,unknownSubcommandPath:usageContext.unknownSubcommandPath,unknownSubcommandToken:usageContext.unknownSubcommandToken,unknownSubcommandAllowedValues:usageContext.unknownSubcommandAllowedValues,suggestedRetryCommand:usageContext.suggestedRetryCommand,verifiedCollectionItemId:usageContext.verifiedCollectionItemId,failedExtensions:usageContext.failedExtensions}),projected=lean?projectLeanErrorEnvelope(envelope):envelope,accountingRequested=parseBootstrapGlobalOptions(usageContext.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(accountingRequested?attachOutputTokenAccounting(projected,value=>`${JSON.stringify(value,null,2)}
13
+ ${details}`}function resolveUnknownCommanderToken(invocationArgv){return parseBootstrapHelpRequest(invocationArgv).commandPathTokens[0]??parseBootstrapCommandName(invocationArgv)??"<command>"}function collectRuntimeCommandPaths(root,extensionDescriptors){const commandPaths=new Set,queue=[...root.commands];for(;queue.length>0;){const current=queue.shift();if(!current)continue;const normalizedPath=normalizeHelpCommandPath(getCommandPath(current)),hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));normalizedPath.length>0&&!hasInternalSegment&&commandPaths.add(normalizedPath),queue.push(...current.commands)}for(const descriptorPath of extensionDescriptors.keys()){const normalizedPath=normalizeHelpCommandPath(descriptorPath),hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));normalizedPath.length>0&&!hasInternalSegment&&commandPaths.add(normalizedPath)}return[...commandPaths].sort((left,right)=>left.localeCompare(right))}function scoreCommandPathMatch(commandPath,queryToken){const normalizedPath=commandPath.trim().toLowerCase(),normalizedToken=queryToken.trim().toLowerCase();if(normalizedToken.length===0)return Number.POSITIVE_INFINITY;const pathSegments=normalizedPath.split(" ");if(normalizedPath===normalizedToken)return 0;if(pathSegments.includes(normalizedToken))return 1;if(pathSegments.some(segment=>segment.startsWith(normalizedToken)))return 2;if(normalizedPath.includes(normalizedToken))return 3;const maxDistance=normalizedToken.length>=5?2:1;let bestDistance=Number.POSITIVE_INFINITY;for(const segment of pathSegments){const distance=levenshteinDistanceWithinLimit(segment,normalizedToken,maxDistance);distance!==null&&(bestDistance=Math.min(bestDistance,distance))}return Number.isFinite(bestDistance)?4+bestDistance:Number.POSITIVE_INFINITY}function toComparableFlag(flag){return normalizeLongFlag(flag).slice(2).replace(/-/g,"")}function renderAttemptedCommand(argv){return renderPmCommand(argv)}function resolveOptionalPackageInstallHint(commandPath){const canonicalPath=resolvePmCommandAlias(commandPath)?.canonical??EXECUTABLE_COMMAND_ALIASES[commandPath]??commandPath,topLevel=canonicalPath.split(" ")[0]?.trim().toLowerCase();if(!topLevel)return null;const packageAlias=OPTIONAL_PACKAGE_INSTALL_HINTS[topLevel];return packageAlias?{packageAlias,canonicalPath,installCommand:`pm package install ${packageAlias} --project`}:null}function normalizePackageCommandAliasToken(value){let normalized=normalizeExtensionNameForMatch(value);for(const prefix of["@unbrained/","builtin-","pm-"])normalized.startsWith(prefix)&&(normalized=normalized.slice(prefix.length));return normalized}function collectInstalledPackageCommandPathHints(unknownToken,extensionDescriptors){const normalizedUnknown=normalizePackageCommandAliasToken(unknownToken);if(normalizedUnknown.length===0)return[];const hints=[];for(const descriptor of extensionDescriptors.values()){const identifiers=new Set,source=descriptor.source;if(source)for(const identifier of[source.name,source.package]){const normalizedIdentifier=normalizePackageCommandAliasToken(identifier??"");normalizedIdentifier.length>0&&identifiers.add(normalizedIdentifier)}identifiers.size!==0&&[...identifiers].some(identifier=>identifier===normalizedUnknown||identifier.includes(normalizedUnknown)||normalizedUnknown.includes(identifier))&&hints.push(descriptor.command)}return[...new Set(hints)].sort((left,right)=>left.localeCompare(right))}function collectKnownLongFlags(commandName,contractsOverride){const flags=new Set,contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName);for(const contract of contracts){contract.flag.startsWith("--")&&flags.add(normalizeLongFlag(contract.flag));for(const alias of contract.aliases??[])alias.startsWith("--")&&flags.add(normalizeLongFlag(alias))}return[...flags].sort((left,right)=>left.localeCompare(right))}function suggestNearestLongFlags(unknownOption,knownFlags){if(!unknownOption.startsWith("--"))return[];const unknownComparable=toComparableFlag(unknownOption);if(unknownComparable.length===0)return[];const maxDistance=unknownComparable.length>=8?2:1,candidates=[];for(const flag of knownFlags){const flagComparable=toComparableFlag(flag);if(flagComparable===unknownComparable)continue;if(unknownComparable.length>=3&&flagComparable.startsWith(unknownComparable)){candidates.push({flag,rank:0,distance:flagComparable.length-unknownComparable.length});continue}const distance=levenshteinDistanceWithinLimit(unknownComparable,flagComparable,maxDistance);distance===null||distance<=0||candidates.push({flag,rank:1,distance})}return candidates.sort((left,right)=>left.rank!==right.rank?left.rank-right.rank:left.distance!==right.distance?left.distance-right.distance:left.flag.localeCompare(right.flag)).map(entry=>entry.flag).slice(0,3)}let crossCommandFlagIndexCache;const CROSS_COMMAND_FLAG_EXCLUSIONS=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function getCrossCommandFlagIndex(){if(crossCommandFlagIndexCache)return crossCommandFlagIndexCache;const index=new Map;for(const command of PM_CORE_COMMAND_NAMES)if(!CROSS_COMMAND_FLAG_EXCLUSIONS.has(command))for(const flag of collectKnownLongFlags(command)){const commands=index.get(flag)??[];commands.push(command),index.set(flag,commands)}return crossCommandFlagIndexCache=index,crossCommandFlagIndexCache}function findOtherCommandsForFlag(unknownOption,currentCommand){if(!unknownOption.startsWith("--"))return[];const commands=getCrossCommandFlagIndex().get(normalizeLongFlag(unknownOption));if(!commands)return[];const normalizedCurrent=currentCommand?.trim().toLowerCase(),currentFlags=new Set(collectKnownLongFlags(normalizedCurrent));return[...new Set(commands.filter(command=>command!==normalizedCurrent).map(command=>({command,sharedFlagCount:collectKnownLongFlags(command).filter(flag=>currentFlags.has(flag)).length})).sort((left,right)=>left.sharedFlagCount!==right.sharedFlagCount?right.sharedFlagCount-left.sharedFlagCount:left.command.localeCompare(right.command)).map(({command})=>resolvePmCommandAlias(command)?.canonical??command))]}function rewriteUnknownOptionArgv(argv,unknownOption,replacementFlag){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(!token.startsWith("--"))continue;const equalsIndex=token.indexOf("="),key=equalsIndex>=0?token.slice(0,equalsIndex):token;if(normalizeLongFlag(key)!==normalizeLongFlag(unknownOption))continue;const next=[...argv];return next[index]=equalsIndex>=0?`${replacementFlag}${token.slice(equalsIndex)}`:replacementFlag,next}}function scoreRuntimeCommandCandidates(params){const commandPathSet=new Set(params.commandPaths),scoreAgainstUnknown=candidatePath=>Math.min(scoreCommandPathMatch(candidatePath,params.normalizedUnknown),params.primaryToken!==params.normalizedUnknown?scoreCommandPathMatch(candidatePath,params.primaryToken):Number.POSITIVE_INFINITY),scoresByCommandPath=new Map,recordCandidateScore=(commandPath,score)=>{if(!Number.isFinite(score)||!commandPathSet.has(commandPath))return;const existing=scoresByCommandPath.get(commandPath);(existing===void 0||score<existing)&&scoresByCommandPath.set(commandPath,score)};for(const commandPath of params.commandPaths)recordCandidateScore(commandPath,scoreAgainstUnknown(commandPath));for(const[aliasToken,canonicalPath]of Object.entries(EXECUTABLE_COMMAND_ALIASES))aliasToken!=="read"&&recordCandidateScore(canonicalPath,scoreAgainstUnknown(aliasToken));return[...scoresByCommandPath.entries()].sort(([leftPath,leftScore],[rightPath,rightScore])=>leftScore!==rightScore?leftScore-rightScore:leftPath.localeCompare(rightPath)).map(([commandPath])=>commandPath)}function resolveUnknownCommandCandidates(params){const exactAlias=resolvePmCommandAlias(params.normalizedUnknown),semanticCandidates=rankCommandPaths(params.commandPaths,params.primaryToken),rankedCandidates=scoreRuntimeCommandCandidates(params),installedPackageCandidates=collectInstalledPackageCommandPathHints(params.primaryToken,params.extensionDescriptors).filter(commandPath=>params.commandPaths.includes(commandPath));return canonicalizeCommandSuggestions([...exactAlias&&params.commandPaths.includes(exactAlias.canonical)?[exactAlias.canonical_argv.join(" ")]:[],...semanticCandidates,...rankedCandidates,...installedPackageCandidates],params.commandPaths,params.primaryToken).filter(path=>!params.normalizedUnknown.includes(" ")||path!==params.normalizedUnknown)}function resolveUnknownCommandFallbacks(commandPaths){return[...new Set(commandPaths.map(commandPath=>commandPath.split(" ")[0]).filter(segment=>segment.length>0))].sort((left,right)=>left.localeCompare(right))}function buildUnknownCommandExamples(suggestedPaths,hasConcreteCandidates){const suggestedExamples=suggestedPaths.map(path=>`pm ${path} --help`);return hasConcreteCandidates?[...new Set([...suggestedExamples,"pm --help --all"])]:[...new Set(["pm --help --all",...suggestedExamples])]}function resolveUnknownCommandPath(token,invocationArgv,commandPaths){let commandIndex=findBootstrapCommandTokenIndex([...invocationArgv]);const path=[];for(;commandIndex!==void 0;){if(path.push(invocationArgv[commandIndex]),invocationArgv[commandIndex]===token)return path.join(" ");if(!commandPaths.includes(path.join(" ")))return token;const offset=findBootstrapCommandTokenIndex(invocationArgv.slice(commandIndex+1));commandIndex=offset===void 0?void 0:commandIndex+1+offset}return token}function buildCanonicalHelpRetryArgs(canonicalPath,invocationArgv){if(!canonicalPath)return;const bootstrapGlobal=parseBootstrapGlobalOptions([...invocationArgv]);return[...bootstrapGlobal.path?["--pm-path",resolvePmRoot(process.cwd(),bootstrapGlobal.path)]:[],...bootstrapGlobal.noExtensions?["--no-extensions"]:[],...canonicalPath.split(" "),"--help"]}function buildUnknownCommandGuidanceFromRuntime(rawMessage,root,extensionDescriptors,invocationArgv=[]){const unknownCommandMatch=rawMessage.match(/unknown command '([^']+)'/i);if(!unknownCommandMatch||typeof unknownCommandMatch[1]!="string")return;const commandPaths=collectRuntimeCommandPaths(root,extensionDescriptors),unknownPath=resolveUnknownCommandPath(unknownCommandMatch[1],invocationArgv,commandPaths),normalizedUnknown=normalizeHelpCommandPath(unknownPath);if(normalizedUnknown.length===0||commandPaths.length===0)return;const optionalPackageHint=resolveOptionalPackageInstallHint(normalizedUnknown);if(optionalPackageHint&&!commandPaths.includes(optionalPackageHint.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[optionalPackageHint.installCommand,`pm ${optionalPackageHint.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${normalizedUnknown}" is provided by the "${optionalPackageHint.packageAlias}" package. Install it with: ${optionalPackageHint.installCommand}. Command after installation: pm ${optionalPackageHint.canonicalPath}.`],suggestedRetryCommand:optionalPackageHint.installCommand};const primaryToken=normalizedUnknown.split(" ")[0],combinedCandidates=resolveUnknownCommandCandidates({commandPaths,normalizedUnknown,primaryToken,extensionDescriptors}),fallbackTopLevel=resolveUnknownCommandFallbacks(commandPaths),misnestedPath=resolveMisnestedCommandPath(normalizedUnknown,commandPaths),retryArgs=buildCanonicalHelpRetryArgs(misnestedPath,invocationArgv),suggestedPaths=[...new Set([...misnestedPath?[misnestedPath]:[],...combinedCandidates.length>0?combinedCandidates:canonicalizeCommandSuggestions(fallbackTopLevel,commandPaths)])].slice(0,3),examples=buildUnknownCommandExamples(suggestedPaths,combinedCandidates.length>0),didYouMean=combinedCandidates.length>0?`Did you mean: ${suggestedPaths.join(", ")}?`:null;return{...retryArgs?{suggestedRetryCommand:renderPmCommand(retryArgs),suggestedRetryArgs:retryArgs}:{},unknownCommandExamples:retryArgs?[renderPmCommand(retryArgs),...examples.slice(1)]:examples,unknownCommandNextSteps:[...didYouMean?[didYouMean]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...didYouMean?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function dedupeStrings(values){return Array.from(new Set(values))}function firstWhitespaceSeparatedToken(input){let token="";for(const character of input){if(character===" "||character===" "||character===`
14
+ `||character==="\r"||character==="\f"||character==="\v")break;token+=character}return token}function trimTrailingPunctuationToken(token){let end=token.length;for(;end>0;){const character=token[end-1];if(character!==","&&character!==":"&&character!==";")break;end-=1}return token.slice(0,end)}function resolveChildCommandByToken(parent,token){const normalizedToken=token.trim().toLowerCase();return parent.commands.find(candidate=>candidate.name().trim().toLowerCase()===normalizedToken?!0:(typeof candidate.aliases=="function"?candidate.aliases():[]).some(alias=>alias.trim().toLowerCase()===normalizedToken))}function isKnownHelpCommandPath(root,commandPathTokens){if(commandPathTokens.length===0)return!0;let current=root;for(const[tokenIndex,token]of commandPathTokens.entries()){const next=resolveChildCommandByToken(current,token);if(!next){const declaredArguments=current.registeredArguments;return declaredArguments.length>0&&(current.commands.length===0||declaredArguments[0]?.required===!0)&&(declaredArguments.at(-1)?.variadic===!0||commandPathTokens.length-tokenIndex<=declaredArguments.length)}current=next}return!0}async function resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName){try{const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);if(!await pathExists(getSettingsPath(pmRoot)))return{allowedTypes:BUILTIN_TYPE_HELP_VALUES};const settings=await readSettings(pmRoot),extensionRegistrations=bootstrapGlobal.noExtensions?void 0:getActiveExtensionRegistrations(),typeRegistry=resolveItemTypeRegistry(settings,extensionRegistrations);let verifiedCollectionItemId;if(/too many arguments/i.test(message)&&["comments","docs","files","learnings","notes","test"].includes(commandName??"")){const commandIndex=invocationArgv.findIndex(token=>token===commandName),candidate=invocationArgv[commandIndex+2];if(invocationArgv[commandIndex+1]?.toLowerCase()==="add"&&candidate!==void 0&&!candidate.startsWith("-"))try{verifiedCollectionItemId=(await locateItem(pmRoot,candidate,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder))?.id}catch{}}return{allowedTypes:typeRegistry.types.length>0?typeRegistry.types.join("|"):BUILTIN_TYPE_HELP_VALUES,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,verifiedCollectionItemId}}catch{return{allowedTypes:BUILTIN_TYPE_HELP_VALUES}}}function resolveUnknownOptionSuggestions(message,commandName){const match=message.match(/unknown option '([^']+)'/i),suggestions=match&&commandName?dedupeStrings([...getSemanticUnknownOptionSuggestions(commandName,match[1]),...suggestNearestLongFlags(match[1],collectKnownLongFlags(commandName))]):void 0,otherCommands=match?findOtherCommandsForFlag(match[1],commandName):[],declaredOnPath=match!==null&&collectKnownLongFlags(commandName).includes(normalizeLongFlag(match[1]));return{match,suggestions,otherCommands,scope:declaredOnPath?"declared_on_path":otherCommands.length>0?"declared_elsewhere":"declared_nowhere"}}function resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOptionMatch,unknownOptionSuggestions){if(!unknownOptionMatch||!unknownOptionSuggestions||unknownOptionSuggestions.length===0)return;const rewritten=rewriteUnknownOptionArgv(invocationArgv,unknownOptionMatch[1],unknownOptionSuggestions[0]);return rewritten?renderAttemptedCommand(rewritten):void 0}function resolveSuggestedRetryForMissingOption(message,invocationArgv){const missingRequiredOption=message.match(/required option '([^']+)' not specified/i),requiredOptionToken=missingRequiredOption?.[1]?trimTrailingPunctuationToken(firstWhitespaceSeparatedToken(missingRequiredOption[1].trim())):void 0;if(!requiredOptionToken?.startsWith("--"))return;const commandName=parseBootstrapCommandName(invocationArgv);if(commandName)return renderMissingOptionRetry(invocationArgv,commandName,[requiredOptionToken])}function resolveSplitSchemaSubcommand(message,invocationArgv){if(!/too many arguments/i.test(message))return;const commandIndex=findBootstrapCommandTokenIndex(invocationArgv),namespaced=findPmNamespacedCommand(invocationArgv.slice(commandIndex));if(namespaced?.alias!=="schema")return;const schemaIndex=commandIndex+namespaced.canonical_argv.length-1,verb=invocationArgv[schemaIndex+1]?.trim().toLowerCase(),noun=invocationArgv[schemaIndex+2]?.trim().toLowerCase();if(!verb||!noun)return;const joined=`${verb}-${noun}`;if(!SCHEMA_SUBCOMMAND_VALUES.includes(joined))return;const rewritten=[...invocationArgv.slice(0,schemaIndex+1),joined,...invocationArgv.slice(schemaIndex+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${verb} ${noun}`,unknownSubcommandAllowedValues:[...SCHEMA_SUBCOMMAND_VALUES],suggestedRetryCommand:renderAttemptedCommand(rewritten)}}function resolveRecoveryCommandName(message,invocationArgv,rootProgram,extensionDescriptors){const commandIndex=findBootstrapCommandTokenIndex(invocationArgv),inferred=findPmNamespacedCommand(invocationArgv.slice(commandIndex))?.alias??parseBootstrapCommandName(invocationArgv);if(!/unknown option /i.test(message)||inferred===void 0)return inferred;const canonical=resolvePmCommandAlias(inferred)?.canonical??inferred;return PM_CORE_COMMAND_NAMES.some(name=>name===inferred)||collectRuntimeCommandPaths(rootProgram,extensionDescriptors).includes(canonical)?inferred:void 0}async function resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides={},invocationArgs=process.argv.slice(2)){const message=(typeof error=="object"&&error!==null?error.message:void 0)??"Invalid command usage",invocationArgv=normalizeBootstrapInvocation([...invocationArgs]).argv,bootstrapGlobal=parseBootstrapGlobalOptions(invocationArgv),commandName=resolveRecoveryCommandName(message,invocationArgv,rootProgram,extensionDescriptors),attemptedCommand=renderAttemptedCommand(invocationArgv),providedOptionFlags=extractProvidedOptionFlags(invocationArgv),workspaceUsage=await resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName),allowedTypes=workspaceUsage.allowedTypes,unknownCommandGuidance=buildUnknownCommandGuidanceFromRuntime(message,rootProgram,extensionDescriptors,invocationArgv),unknownOption=resolveUnknownOptionSuggestions(message,commandName),splitSchemaSubcommand=resolveSplitSchemaSubcommand(message,invocationArgv),suggestedRetryCommand=splitSchemaSubcommand?.suggestedRetryCommand??resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOption.match,unknownOption.suggestions)??resolveSuggestedRetryForMissingOption(message,invocationArgv);return{message,commandName,allowedTypes,attemptedCommand,normalizedInvocationArgs:[...invocationArgv],providedOptionFlags,unknownOptionSuggestions:unknownOption.suggestions,unknownOptionOtherCommands:unknownOption.otherCommands.length>0?unknownOption.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:unknownOption.otherCommands.length>0?unknownOption.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:unknownOption.otherCommands.length>12||void 0,unknownOptionScope:unknownOption.scope,suggestedRetryCommand,verifiedCollectionItemId:workspaceUsage.verifiedCollectionItemId,...splitSchemaSubcommand,...unknownCommandGuidance,...guidanceOverrides}}async function formatCommanderUsageMessage(error,rootProgram,extensionDescriptors,guidanceOverrides={},invocationArgs=process.argv.slice(2)){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides,invocationArgs),{message,commandName,allowedTypes,unknownCommandExamples,unknownCommandNextSteps,attemptedCommand,normalizedInvocationArgs,providedOptionFlags,unknownOptionSuggestions,unknownOptionOtherCommands,unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated,unknownOptionScope,unknownSubcommandPath,unknownSubcommandToken,unknownSubcommandAllowedValues,suggestedRetryCommand,suggestedRetryArgs,verifiedCollectionItemId,failedExtensions}=usageContext,formatted=formatCommanderErrorForDisplay(message,commandName,allowedTypes,{unknownCommandExamples,unknownCommandNextSteps,attemptedCommand,normalizedInvocationArgs,providedOptionFlags,unknownOptionSuggestions,unknownOptionOtherCommands,unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated,unknownOptionScope,unknownSubcommandPath,unknownSubcommandToken,unknownSubcommandAllowedValues,suggestedRetryCommand,suggestedRetryArgs,verifiedCollectionItemId,failedExtensions}),serviceOverride=await runActiveServiceOverride("help_format",{message:formatted,command:commandName,allowed_types:allowedTypes});return serviceOverride.handled&&typeof serviceOverride.result=="string"?serviceOverride.result:formatted}async function formatCommanderUsageJson(error,rootProgram,extensionDescriptors,lean=!1,guidanceOverrides={},invocationArgs=process.argv.slice(2)){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides,invocationArgs),envelope=formatCommanderErrorForJson(usageContext.message,usageContext.commandName,usageContext.allowedTypes,EXIT_CODE.USAGE,{unknownCommandExamples:usageContext.unknownCommandExamples,unknownCommandNextSteps:usageContext.unknownCommandNextSteps,attemptedCommand:usageContext.attemptedCommand,normalizedInvocationArgs:usageContext.normalizedInvocationArgs,providedOptionFlags:usageContext.providedOptionFlags,unknownOptionSuggestions:usageContext.unknownOptionSuggestions,unknownOptionOtherCommands:usageContext.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:usageContext.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:usageContext.unknownOptionOtherCommandsTruncated,unknownOptionScope:usageContext.unknownOptionScope,unknownSubcommandPath:usageContext.unknownSubcommandPath,unknownSubcommandToken:usageContext.unknownSubcommandToken,unknownSubcommandAllowedValues:usageContext.unknownSubcommandAllowedValues,suggestedRetryCommand:usageContext.suggestedRetryCommand,suggestedRetryArgs:usageContext.suggestedRetryArgs,verifiedCollectionItemId:usageContext.verifiedCollectionItemId,failedExtensions:usageContext.failedExtensions}),projected=lean?projectLeanErrorEnvelope(envelope):envelope,accountingRequested=parseBootstrapGlobalOptions(usageContext.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(accountingRequested?attachOutputTokenAccounting(projected,value=>`${JSON.stringify(value,null,2)}
15
15
  `):projected,null,2)}const _testOnly={collectKnownLongFlags,collectInstalledPackageCommandPathHints,resolveOptionalPackageInstallHint,resolveSuggestedRetryForMissingOption,suggestNearestLongFlags};export{BUILTIN_TYPE_HELP_VALUES,_testOnly,appendCommanderExtensionFailures,buildUnknownCommandGuidanceFromRuntime,collectRuntimeCommandPaths,formatCommanderUsageJson,formatCommanderUsageMessage,isKnownHelpCommandPath,resolveChildCommandByToken,resolveCommanderUsageContext,resolveUnknownCommanderToken,scoreCommandPathMatch};
16
16
  //# sourceMappingURL=commander-usage.js.map
@@ -157,6 +157,8 @@ export interface CommanderGuidanceContext {
157
157
  unknownSubcommandAllowedValues?: string[];
158
158
  /** Value that configures or reports suggested retry command for this contract. */
159
159
  suggestedRetryCommand?: string;
160
+ /** Tokenized inspection retry that preserves a refusal without executing the guessed operation. */
161
+ suggestedRetryArgs?: string[];
160
162
  /** Existing item id verified against the selected tracker for collection recovery. */
161
163
  verifiedCollectionItemId?: string;
162
164
  /** Installed extensions whose activation failed for this invocation. */
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="aaa2e9cf-ebf8-5776-a04e-4ea18e7489ee")}catch{}})();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){return!message.why||message.recovery?.recovery_mode==="compact"?!1:!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"},CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},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 KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){return entries.length===0?[]:[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values))return;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;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){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);parsedPositionals.length>0&&(normalized.parsed_positionals=parsedPositionals);return}const values=normalizeStringArray(value);values&&(normalized[key]=values)}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!="object")return;const normalized={};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),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),payload.candidate_commands_truncated===!0&&(normalized.candidate_commands_truncated=!0),(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),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);return fallbackCandidates&&(normalized.fallback_candidates=fallbackCandidates),assignRecoveryString(normalized,"next_best_command",payload.next_best_command),Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){value&&lines.push(` ${label}: ${value}`)}function appendRecoveryListLine(lines,label,values,separator){values&&values.length>0&&lines.push(` ${label}: ${values.join(separator)}`)}function renderRecoveryBundle(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized)return[];const lines=["Recovery bundle:"];if(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," "),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}`)}if(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,", "),typeof normalized.candidate_commands_total=="number"&&lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`),normalized.candidate_commands_truncated===!0&&lines.push(" candidate_commands_truncated: true"),normalized.option_scope!==void 0&&lines.push(` option_scope: ${normalized.option_scope}`),typeof normalized.retry_after_ms=="number"&&lines.push(` retry_after_ms: ${normalized.retry_after_ms}`),appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command),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}`];message.nextSteps&&message.nextSteps.length>0&&(lines.push(""),lines.push(...renderList("Next steps:",message.nextSteps))),lines.push("","What happened:",` ${message.happened}`),message.why&&(lines.push("","Why:"),lines.push(` ${message.why}`)),message.examples&&message.examples.length>0&&(lines.push(""),lines.push(...renderList("Examples:",message.examples))),message.verificationErrors&&message.verificationErrors.length>0&&(lines.push(""),lines.push(...renderList("Verification errors:",message.verificationErrors)));const recoveryLines=renderRecoveryBundle(message.recovery);return recoveryLines.length>0&&(lines.push(""),lines.push(...recoveryLines)),lines.join(`
2
- `)}function attachStructuredGuidanceDetails(payload,message){return message.transactionOperation!==void 0&&(payload.transaction_operation=message.transactionOperation),message.tombstone!==void 0&&(payload.tombstone=message.tombstone,payload.item_id=message.itemId),includeWhyInStructuredGuidance(message)&&(payload.why=message.why),message.examples&&message.examples.length>0&&(payload.examples=message.examples),message.nextSteps&&message.nextSteps.length>0&&(payload.next_steps=message.nextSteps),message.verificationErrors&&message.verificationErrors.length>0&&(payload.verification_errors=message.verificationErrors),message.flag!==void 0&&(payload.flag=message.flag),message.value!==void 0&&(payload.value=message.value),message.unmatchedSelectors!==void 0&&(payload.unmatched_selectors=message.unmatchedSelectors),message.availableDependencies!==void 0&&(payload.available_dependencies=message.availableDependencies),message.recovery&&(payload.recovery=message.recovery),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}=`))};return[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(message.flag===void 0&&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 normalizedArgs[candidateIndex+1]}}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??[]),namespaced=findPmNamespacedCommand(invocationArgs),normalizedArgs=namespaced?[namespaced.alias,...invocationArgs.slice(namespaced.canonical_argv.length)]:invocationArgs,candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs),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,hasActionableRecovery=!!recovery?.suggested_retry||!!recovery?.suggested_retry_args?.length||!!recovery?.allowed_values?.length||!!recovery?.candidate_commands?.length||!!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;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,result=[];for(const value of values)seen.has(value)||(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);return match?match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry)):[]}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args,fields=recovery?.provided_fields,replacement=allowedValues[0];if(!(!Array.isArray(args)||!Array.isArray(fields)||!replacement))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];return nextArgs[index+1]=replacement,renderPmCommand(nextArgs)}}}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length!==0)return firstLine.length<=120?firstLine:`${firstLine.slice(0,117)}...`}function normalizeContextValue(value,fallback){return typeof value=="string"&&value.trim().length>0?value.trim():fallback}function resolveErrorContextFlag(context,recovery){if(context.flag!==void 0)return context.flag;if(context.field===void 0)return;const flag=context.field.startsWith("--")?context.field:`--${context.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return recovery?.normalized_args?.some(argument=>argument===flag||argument.startsWith(`${flag}=`))?flag:void 0}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context)return guidance;const normalizedRawMessage=normalizeMessage(rawMessage),code=normalizeContextValue(context.code,guidance.code),type=normalizeContextValue(context.type,errorType(code)),examples=normalizeContextList(context.examples)??guidance.examples,nextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps,verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors,fallbackTitle=guidance.code==="command_failed"&&context.code?buildFallbackTitleFromMessage(normalizedRawMessage):void 0,contextRecovery=normalizeRecoveryPayload(context.recovery),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:resolveErrorContextFlag(context,recovery)??guidance.flag,value:context.value??guidance.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,transactionOperation:context.transaction_operation,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],nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);return applyPmCliErrorContext(makeGuidanceMessage(nearbyRoot?{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}.`]}:{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],isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId),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.`;return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",flag:"id",value:badId,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: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."]}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){return!message.includes("is assigned to")||!message.includes("Use --force to override")?null: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){return message.includes("is locked")?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):null}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /),missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions)return null;const plural=!!missingRequiredOptions,missingOptionFlag=plural?null:message.replace(/^Missing required option\s+/,"").trim(),missingOptionLabel=missingOptionFlag??"",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){return message.startsWith("No update flags provided")?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):null}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!message.startsWith("Invalid ")&&!message.includes(" must be ")&&!message.includes(" requires "))return null;const recovery=normalizeRecoveryPayload(context?.recovery),commandName=inferCommandNameFromRecovery(recovery),helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help",allowedValues=inferAllowedValuesFromMessage(message),enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues}),retryExample=buildAllowedValueRetryCommand(recovery,allowedValues),examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"],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);return(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))||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){return commandName==="create"&&optionFlag.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${allowedTypes.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:commandName==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();return normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??normalized}function renderPmCommandFromArgs(argv){if(!(!Array.isArray(argv)||argv.length===0))return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values))return;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),normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0,attemptedCommand=typeof context?.attemptedCommand=="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs),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){return!value||entries.includes(value)?entries:[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]),LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(Array.isArray(argv))for(const token of argv){if(!token.startsWith("--"))continue;const equalsIndex=token.indexOf("="),flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag))return flag}}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv))return;const commandIndex=argv.indexOf("test");if(commandIndex<0)return;const idToken=argv[commandIndex+1];if(!(typeof idToken!="string"||idToken.startsWith("-")))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;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;const merged=`${key}=${valueTokens.join(" ")}`,rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption)return null;const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]),isType=optionFlag.startsWith("--type"),retryCommand=context?.suggestedRetryCommand,providedFlags=normalizeOptionFlags(context?.providedOptionFlags),missing=[optionFlag],examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes),examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples,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.`],nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase,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),proseRemainder=candidateContext.candidateTotal-proseCommands.length,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(["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0]))return{};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("-")!==!0)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??{},optionName=unknownOption[1],suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[],{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc"))return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions);const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext),nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0])&&nextSteps.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");const examples=[retryCommand,commandName?`pm ${resolvePmCommandAlias(commandName)?.canonical??commandName} --help`:"pm --help --all"].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}`,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],runtimeExamples=normalizeContextList(context?.unknownCommandExamples),runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps),packageHint=resolveKnownPackageCommandHint(commandToken),baseExamples=runtimeExamples??["pm --help"],baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."],failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase())),hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))?buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context):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(),token=context?.unknownSubcommandToken?.trim(),allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed)return null;const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,value: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,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??[],commandIndex=argv.findIndex(token=>token===commandName),action=argv[commandIndex+1],parsedItemId=argv[commandIndex+2],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"]),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??[],commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token)),searchIndex=commandIndex===-1?1:commandIndex+1,match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=!1;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=!1;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(!token.startsWith("-")){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);return(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))||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);return(context?.code==="tracker_root_missing"||context?.code==="tracker_not_initialized")&&guidance.title==="Tracker is not initialized"&&guidance.recovery?.suggested_retry_args?[`Error: ${guidance.title}`,`Run: ${renderPmCommand(guidance.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="990ef8ec-9869-5902-b702-9db69230fd69")}catch{}})();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){return!message.why||message.recovery?.recovery_mode==="compact"?!1:!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"},CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},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 KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){return entries.length===0?[]:[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values))return;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;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){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);parsedPositionals.length>0&&(normalized.parsed_positionals=parsedPositionals);return}const values=normalizeStringArray(value);values&&(normalized[key]=values)}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!="object")return;const normalized={};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),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),payload.candidate_commands_truncated===!0&&(normalized.candidate_commands_truncated=!0),(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),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);return fallbackCandidates&&(normalized.fallback_candidates=fallbackCandidates),assignRecoveryString(normalized,"next_best_command",payload.next_best_command),Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){value&&lines.push(` ${label}: ${value}`)}function appendRecoveryListLine(lines,label,values,separator){values&&values.length>0&&lines.push(` ${label}: ${values.join(separator)}`)}function renderRecoveryBundle(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized)return[];const lines=["Recovery bundle:"];if(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," "),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}`)}if(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,", "),typeof normalized.candidate_commands_total=="number"&&lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`),normalized.candidate_commands_truncated===!0&&lines.push(" candidate_commands_truncated: true"),normalized.option_scope!==void 0&&lines.push(` option_scope: ${normalized.option_scope}`),typeof normalized.retry_after_ms=="number"&&lines.push(` retry_after_ms: ${normalized.retry_after_ms}`),appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command),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}`];message.nextSteps&&message.nextSteps.length>0&&(lines.push(""),lines.push(...renderList("Next steps:",message.nextSteps))),lines.push("","What happened:",` ${message.happened}`),message.why&&(lines.push("","Why:"),lines.push(` ${message.why}`)),message.examples&&message.examples.length>0&&(lines.push(""),lines.push(...renderList("Examples:",message.examples))),message.verificationErrors&&message.verificationErrors.length>0&&(lines.push(""),lines.push(...renderList("Verification errors:",message.verificationErrors)));const recoveryLines=renderRecoveryBundle(message.recovery);return recoveryLines.length>0&&(lines.push(""),lines.push(...recoveryLines)),lines.join(`
2
+ `)}function attachStructuredGuidanceDetails(payload,message){return message.transactionOperation!==void 0&&(payload.transaction_operation=message.transactionOperation),message.tombstone!==void 0&&(payload.tombstone=message.tombstone,payload.item_id=message.itemId),includeWhyInStructuredGuidance(message)&&(payload.why=message.why),message.examples&&message.examples.length>0&&(payload.examples=message.examples),message.nextSteps&&message.nextSteps.length>0&&(payload.next_steps=message.nextSteps),message.verificationErrors&&message.verificationErrors.length>0&&(payload.verification_errors=message.verificationErrors),message.flag!==void 0&&(payload.flag=message.flag),message.value!==void 0&&(payload.value=message.value),message.unmatchedSelectors!==void 0&&(payload.unmatched_selectors=message.unmatchedSelectors),message.availableDependencies!==void 0&&(payload.available_dependencies=message.availableDependencies),message.recovery&&(payload.recovery=message.recovery),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}=`))};return[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(message.flag===void 0&&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 normalizedArgs[candidateIndex+1]}}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??[]),namespaced=findPmNamespacedCommand(invocationArgs),normalizedArgs=namespaced?[namespaced.alias,...invocationArgs.slice(namespaced.canonical_argv.length)]:invocationArgs,candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs),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,hasActionableRecovery=!!recovery?.suggested_retry||!!recovery?.suggested_retry_args?.length||!!recovery?.allowed_values?.length||!!recovery?.candidate_commands?.length||!!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;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,result=[];for(const value of values)seen.has(value)||(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);return match?match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry)):[]}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args,fields=recovery?.provided_fields,replacement=allowedValues[0];if(!(!Array.isArray(args)||!Array.isArray(fields)||!replacement))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];return nextArgs[index+1]=replacement,renderPmCommand(nextArgs)}}}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length!==0)return firstLine.length<=120?firstLine:`${firstLine.slice(0,117)}...`}function normalizeContextValue(value,fallback){return typeof value=="string"&&value.trim().length>0?value.trim():fallback}function resolveErrorContextFlag(context,recovery){if(context.flag!==void 0)return context.flag;if(context.field===void 0)return;const flag=context.field.startsWith("--")?context.field:`--${context.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return recovery?.normalized_args?.some(argument=>argument===flag||argument.startsWith(`${flag}=`))?flag:void 0}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context)return guidance;const normalizedRawMessage=normalizeMessage(rawMessage),code=normalizeContextValue(context.code,guidance.code),type=normalizeContextValue(context.type,errorType(code)),examples=normalizeContextList(context.examples)??guidance.examples,nextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps,verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors,fallbackTitle=guidance.code==="command_failed"&&context.code?buildFallbackTitleFromMessage(normalizedRawMessage):void 0,contextRecovery=normalizeRecoveryPayload(context.recovery),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:resolveErrorContextFlag(context,recovery)??guidance.flag,value:context.value??guidance.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,transactionOperation:context.transaction_operation,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],nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);return applyPmCliErrorContext(makeGuidanceMessage(nearbyRoot?{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}.`]}:{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],isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId),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.`;return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",flag:"id",value:badId,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: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."]}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){return!message.includes("is assigned to")||!message.includes("Use --force to override")?null: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){return message.includes("is locked")?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):null}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /),missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions)return null;const plural=!!missingRequiredOptions,missingOptionFlag=plural?null:message.replace(/^Missing required option\s+/,"").trim(),missingOptionLabel=missingOptionFlag??"",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){return message.startsWith("No update flags provided")?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):null}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!message.startsWith("Invalid ")&&!message.includes(" must be ")&&!message.includes(" requires "))return null;const recovery=normalizeRecoveryPayload(context?.recovery),commandName=inferCommandNameFromRecovery(recovery),helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help",allowedValues=inferAllowedValuesFromMessage(message),enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues}),retryExample=buildAllowedValueRetryCommand(recovery,allowedValues),examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"],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);return(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))||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){return commandName==="create"&&optionFlag.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${allowedTypes.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:commandName==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();return normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??normalized}function renderPmCommandFromArgs(argv){if(!(!Array.isArray(argv)||argv.length===0))return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values))return;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),normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0,attemptedCommand=typeof context?.attemptedCommand=="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs),retryCommand=typeof context?.suggestedRetryCommand=="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,suggested_retry_args:context?.suggestedRetryArgs,...overrides})}function appendIfMissing(entries,value){return!value||entries.includes(value)?entries:[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]),LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(Array.isArray(argv))for(const token of argv){if(!token.startsWith("--"))continue;const equalsIndex=token.indexOf("="),flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag))return flag}}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv))return;const commandIndex=argv.indexOf("test");if(commandIndex<0)return;const idToken=argv[commandIndex+1];if(!(typeof idToken!="string"||idToken.startsWith("-")))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;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;const merged=`${key}=${valueTokens.join(" ")}`,rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption)return null;const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]),isType=optionFlag.startsWith("--type"),retryCommand=context?.suggestedRetryCommand,providedFlags=normalizeOptionFlags(context?.providedOptionFlags),missing=[optionFlag],examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes),examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples,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.`],nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase,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),proseRemainder=candidateContext.candidateTotal-proseCommands.length,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(["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0]))return{};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("-")!==!0)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??{},optionName=unknownOption[1],suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[],{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc"))return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions);const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext),nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0])&&nextSteps.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");const examples=[retryCommand,commandName?`pm ${resolvePmCommandAlias(commandName)?.canonical??commandName} --help`:"pm --help --all"].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}`,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],runtimeExamples=normalizeContextList(context?.unknownCommandExamples),runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps),packageHint=resolveKnownPackageCommandHint(commandToken),baseExamples=runtimeExamples??["pm --help"],baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."],failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase())),hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))?buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context):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(),token=context?.unknownSubcommandToken?.trim(),allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed)return null;const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,value: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,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??[],commandIndex=argv.findIndex(token=>token===commandName),action=argv[commandIndex+1],parsedItemId=argv[commandIndex+2],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"]),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??[],commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token)),searchIndex=commandIndex===-1?1:commandIndex+1,match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=!1;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=!1;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(!token.startsWith("-")){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);return(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))||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);return(context?.code==="tracker_root_missing"||context?.code==="tracker_not_initialized")&&guidance.title==="Tracker is not initialized"&&guidance.recovery?.suggested_retry_args?[`Error: ${guidance.title}`,`Run: ${renderPmCommand(guidance.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
3
3
  `):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);return isModuleResolutionErrorMessage(message)?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."]}):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};
4
4
  //# sourceMappingURL=error-guidance.js.map
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6bca8bb8-c8f8-5bf5-bd3a-1e3089571238")}catch{}})();import{hasSubcommandFlagContractsForCommand,PM_COMMAND_ALIAS_CONTRACTS,PM_CORE_COMMAND_NAMES,resolvePmCommandAlias,resolvePmCommandOperation}from"../sdk/cli-contracts.js";import{commandOptionFlagLabel,resolveCommandOptionPolicyState,resolveTypeDefinition,EXIT_CODE,writeStderr,writeStdout}from"../sdk/runtime-primitives.js";import{buildDynamicExtensionHelpOptionSummaries,mergeHelpOptionSummaries,findCommandByPath,findDirectChildCommand,commandAliases}from"./extension-command-help.js";import{getPmCommandHelpVisibilityTier,isFullHelpDiscovery,normalizeHelpCommandPath,resolveHelpBundleForPath,resolveHelpDetailMode,resolveHelpNarrative,ROOT_HELP_BUNDLE}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapCommandName,parseBootstrapTypeValue}from"./bootstrap-args.js";import{extractProvidedOptionFlags,renderPmCommand}from"./argv-utils.js";import{formatCommanderErrorForJson}from"./error-guidance.js";import{BUILTIN_TYPE_HELP_VALUES,buildUnknownCommandGuidanceFromRuntime,isKnownHelpCommandPath}from"./commander-usage.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{resolveCreateExplicitEmptyFlag}from"../sdk/agent/create-option-policy.js";import{formatPmPositionalActionFlagTip,PM_POSITIONAL_ACTION_CONTRACTS,resolvePmPositionalActionContract}from"../sdk/cli-contracts/grammar-contracts.js";import{resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"../sdk/agent-capability-contracts.js";const EXTENSION_TIER_ORDER={core:0,standard:1,full:2,internal:3};function resolveExtensionCommandSurface(commandPath,descriptors,allowDescendants=!0){const exact=descriptors.get(resolvePmCommandOperation(commandPath));if(exact)return exact;if(!allowDescendants)return;const descendants=[...descriptors.entries()].filter(([path])=>path.startsWith(`${commandPath} `)).map(([,descriptor])=>descriptor);if(descendants.length===0)return;const tier=descendants.reduce((selected,descriptor)=>EXTENSION_TIER_ORDER[descriptor.tier]<EXTENSION_TIER_ORDER[selected]?descriptor.tier:selected,"internal"),families=new Set(descendants.map(({family})=>family));return{tier,family:families.size===1?descendants[0].family:"extensions"}}function resolveCommandFromPathTokens(root,pathTokens){if(pathTokens.length===0)return root;const exactCommand=findCommandByPath(root,pathTokens);if(exactCommand)return exactCommand;const requestedPath=pathTokens.join(" ");if(resolvePmCommandOperation(requestedPath)!==requestedPath||!PM_CORE_COMMAND_NAMES.some(commandName=>commandName===requestedPath)&&!hasSubcommandFlagContractsForCommand(requestedPath)&&!resolvePmPositionalActionContract(requestedPath)&&!isKnownHelpCommandPath(root,pathTokens))return null;for(let length=pathTokens.length-1;length>0;length-=1){const positionalParent=findCommandByPath(root,pathTokens.slice(0,length));if(positionalParent)return positionalParent}return pathTokens.length===1?root:null}function extractOptionValueName(flags){const match=flags.match(/[<[]([^>\]]+)[>\]]/);if(!match)return null;const value=match[1]?.trim();return value&&value.length>0?value:null}function readOptionAttributeName(option){const optionRecord=option;if(typeof optionRecord.attributeName=="function"){const value=optionRecord.attributeName();return typeof value=="string"&&value.trim().length>0?value.trim():null}return typeof optionRecord.attributeName=="string"&&optionRecord.attributeName.trim().length>0?optionRecord.attributeName.trim():null}function buildOptionAliasMap(options){const aliasMap=new Map;for(const option of options){const optionRecord=option,attributeName=readOptionAttributeName(option);if(!attributeName||typeof optionRecord.long!="string"||optionRecord.long.trim().length===0)continue;const existing=aliasMap.get(attributeName)??[];existing.push(optionRecord.long.trim()),aliasMap.set(attributeName,existing)}for(const[attributeName,values]of aliasMap.entries())aliasMap.set(attributeName,[...new Set(values.map(value=>value.trim()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right)));return aliasMap}function renderAttemptedCommand(argv){return renderPmCommand(argv)}function buildHelpOptionSummaries(command){const options=command.options??[],optionAliasMap=buildOptionAliasMap(options);return options.map(option=>{const optionRecord=option,flags=typeof optionRecord.flags=="string"?optionRecord.flags.trim():"",description=typeof optionRecord.description=="string"?optionRecord.description.trim():"",attributeName=readOptionAttributeName(option),aliases=(attributeName?optionAliasMap.get(attributeName)??[]:[]).filter(entry=>entry!==optionRecord.long).map(entry=>entry.trim()).filter(entry=>entry.length>0),aliasForMatch=description.match(/^Alias for ([^ ]+)/i),aliasFor=aliasForMatch&&aliasForMatch[1]?aliasForMatch[1].trim():null,required=optionRecord.mandatory===!0||description.includes("[required]")||description.toLowerCase().includes("required;"),valueRequired=flags.includes("<"),takesValue=valueRequired||flags.includes("["),summary={flags,long:typeof optionRecord.long=="string"?optionRecord.long:null,short:typeof optionRecord.short=="string"?optionRecord.short:null,description,takes_value:takesValue,value_required:valueRequired,value_name:extractOptionValueName(flags),variadic:optionRecord.variadic===!0,required,aliases,alias_for:aliasFor};return optionRecord.defaultValue!==void 0&&(summary.default_value=optionRecord.defaultValue),summary})}function compactHelpOptionAliases(options){const canonicalByLong=new Map,aliasOptions=[];for(const option of options){if(option.alias_for&&option.long){aliasOptions.push(option);continue}option.long&&canonicalByLong.set(option.long,option)}for(const aliasOption of aliasOptions){const aliasFor=aliasOption.alias_for,canonical=canonicalByLong.get(aliasFor);if(!canonical)continue;const aliasLong=aliasOption.long,aliases=new Set([...canonical.aliases??[],aliasLong]);canonical.aliases=[...aliases].sort((left,right)=>left.localeCompare(right))}return options.filter(option=>!option.alias_for||!option.long?!0:!canonicalByLong.has(option.alias_for))}function buildHelpArgumentSummaries(command){const commandRecord=command;return(Array.isArray(commandRecord.registeredArguments)?commandRecord.registeredArguments:Array.isArray(commandRecord._args)?commandRecord._args:[]).map(argument=>{const rawName=typeof argument.name=="function"?argument.name():typeof argument.name=="string"?argument.name:"argument",description=typeof argument.description=="string"&&argument.description.trim().length>0?argument.description.trim():null;return{name:rawName.trim(),required:argument.required===!0||description?.toLowerCase().startsWith("required;")===!0,variadic:argument.variadic===!0,description}})}function buildHelpSubcommandSummaries(command,extensionDescriptors=new Map,includeAll=!1){const visible=command.createHelp().visibleCommands(command);return(includeAll?[...new Set([...visible,...command.commands])]:visible).filter(entry=>entry.name()!=="help"||command.parent===null).filter(entry=>!includeAll||(getPmCommandHelpVisibilityTier(entry)??resolvePmCommandVisibilityTier(entry.name()))!=="internal").map(entry=>{const commandPath=normalizeHelpCommandPath(getCommandPath(entry)),rootCommand=commandPath,declaredTier=getPmCommandHelpVisibilityTier(entry),extensionDescriptor=resolveExtensionCommandSurface(commandPath,extensionDescriptors,declaredTier!==void 0),aliasContract=PM_COMMAND_ALIAS_CONTRACTS.find(({alias})=>alias===commandPath);return{name:entry.name().trim(),aliases:commandAliases(entry),description:entry.description().trim(),tier:extensionDescriptor?.tier??declaredTier??resolvePmCommandVisibilityTier(rootCommand),family:extensionDescriptor?.family??resolvePmCommandCapabilityFamily(rootCommand),...aliasContract?{alias_for:aliasContract.canonical,alias_lifecycle:aliasContract.lifecycle,...aliasContract.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((left,right)=>left.name.localeCompare(right.name))}function buildJsonHelpNarrative(detailMode,fallbackNarrative,extensionDescriptor){if(!extensionDescriptor)return fallbackNarrative;const extensionExamples=extensionDescriptor.examples??[],extensionFailureHints=extensionDescriptor.failure_hints??[];return{intent:extensionDescriptor.intent??extensionDescriptor.description??fallbackNarrative.intent,examples:detailMode==="detailed"?extensionExamples.length>0?[...extensionExamples]:[...fallbackNarrative.examples]:extensionExamples.length>0?[extensionExamples[0]]:[...fallbackNarrative.examples],tips:detailMode==="detailed"?extensionFailureHints.length>0?[...extensionFailureHints]:[...fallbackNarrative.tips]:[],detail_mode:detailMode}}function resolveJsonHelpNarrative(commandPath,commandDescription,detailMode,extensionDescriptor,hasPositionalAction){const isRootFallback=commandPath!==void 0&&resolveHelpBundleForPath(commandPath)===ROOT_HELP_BUNDLE,fallback=isRootFallback?{intent:commandDescription,examples:[`pm ${commandPath} --help`],tips:[],detail_mode:detailMode}:resolveHelpNarrative(commandPath,detailMode),intentSource=hasPositionalAction?"positional_action":extensionDescriptor?.intent||extensionDescriptor?.description?"extension":isRootFallback?commandDescription?"command_description":"unavailable":commandPath?"help_bundle":"root_help_bundle";return{narrative:buildJsonHelpNarrative(detailMode,fallback,extensionDescriptor),intentSource}}function resolveJsonHelpVisibilityTier(rootCommandPath,extensionDescriptor){return rootCommandPath===void 0?null:extensionDescriptor?.tier??resolvePmCommandVisibilityTier(rootCommandPath)}function resolveJsonHelpCapabilityFamily(rootCommandPath,extensionDescriptor){return rootCommandPath===void 0?null:extensionDescriptor?.family??resolvePmCommandCapabilityFamily(rootCommandPath)}function projectFullCommandAliases(rootProgram,targetCommand,fullDiscovery){if(!(targetCommand!==rootProgram||!fullDiscovery))return PM_COMMAND_ALIAS_CONTRACTS.map(contract=>({alias:contract.alias,canonical:contract.canonical,canonical_argv:[...contract.canonical_argv],available:resolveCommandFromPathTokens(rootProgram,contract.canonical.split(" "))!==null,lifecycle:contract.lifecycle,hidden:contract.hidden,deprecated:contract.lifecycle==="deprecated"}))}function buildPositionalActionHelpProjection(action,targetCommand,resolvedPath,allOptions,extensionDescriptors=new Map,includeAll=!1){if(!action){const argumentsList=buildHelpArgumentSummaries(targetCommand),registeredSubcommands=buildHelpSubcommandSummaries(targetCommand,extensionDescriptors,includeAll),registeredSubcommandNames=new Set(registeredSubcommands.map(({name})=>name));return{arguments:argumentsList,options:allOptions,subcommands:[...registeredSubcommands,...PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent,action:name})=>parent===resolvedPath&&!registeredSubcommandNames.has(name)).map(({action:name,description})=>({name,aliases:[],description,tier:resolvePmCommandVisibilityTier(resolvedPath.split(" ")[0]),family:resolvePmCommandCapabilityFamily(resolvedPath.split(" ")[0])}))].sort((left,right)=>left.name.localeCompare(right.name)),usage:[resolvedPath,argumentsList.reduce((usage,argument)=>argument.required?usage.replace(`[${argument.name}${argument.variadic?"...":""}]`,`<${argument.name}${argument.variadic?"...":""}>`):usage,targetCommand.usage())].filter(token=>token.length>0).join(" ")}}const acceptedFlags=new Set(action.accepted_flags);return{arguments:action.slots.map(({name,required,variadic,value_kind:valueKind,polymorphic})=>({name,required,variadic,description:polymorphic?`Polymorphic ${valueKind} value; inspect the action contract before mutation.`:`${valueKind.replaceAll("_"," ")} value.`})),options:allOptions.filter(({long,aliases})=>long!==null&&acceptedFlags.has(long)||aliases.some(alias=>acceptedFlags.has(alias))),subcommands:[],usage:[action.command,...action.slots.map(({name,required,variadic})=>{const token=variadic?`${name}...`:name;return required?`<${token}>`:`[${token}]`})].join(" ")}}function buildJsonHelpPayload(rootProgram,targetCommand,argv,requestedPath,extensionDescriptors){const detailMode=resolveHelpDetailMode(argv),fullDiscovery=isFullHelpDiscovery(argv),commanderPath=normalizeHelpCommandPath(getCommandPath(targetCommand)),requestedCommandPath=normalizeHelpCommandPath(requestedPath.join(" ")),resolvedPath=requestedCommandPath.length>commanderPath.length?requestedCommandPath:commanderPath,positionalAction=resolvePmPositionalActionContract(resolvedPath),projectedPath=positionalAction?.command??commanderPath,commandPath=projectedPath.length>0?projectedPath:void 0,rootCommandPath=commandPath,extensionDescriptor=commandPath?extensionDescriptors.get(resolvePmCommandOperation(commandPath)):void 0,extensionSurface=commandPath?resolveExtensionCommandSurface(commandPath,extensionDescriptors,getPmCommandHelpVisibilityTier(targetCommand)!==void 0):void 0,{narrative,intentSource}=resolveJsonHelpNarrative(commandPath,targetCommand.description().trim(),detailMode,extensionDescriptor,positionalAction!==void 0),allOptionSummaries=compactHelpOptionAliases(mergeHelpOptionSummaries(buildHelpOptionSummaries(targetCommand),buildDynamicExtensionHelpOptionSummaries(extensionDescriptor))),projection=buildPositionalActionHelpProjection(positionalAction,targetCommand,projectedPath,allOptionSummaries,extensionDescriptors,fullDiscovery),fullCommandAliases=projectFullCommandAliases(rootProgram,targetCommand,fullDiscovery);return{format:"pm_help_v1",detail_mode:detailMode,root_command:rootProgram.name(),requested_path:requestedPath,resolved_path:projectedPath.length>0?projectedPath:rootProgram.name(),visibility_tier:resolveJsonHelpVisibilityTier(rootCommandPath,extensionSurface),capability_family:resolveJsonHelpCapabilityFamily(rootCommandPath,extensionSurface),description:positionalAction?.description??targetCommand.description(),usage:projection.usage,intent:positionalAction?.description??narrative.intent,intent_source:intentSource,examples:positionalAction?[positionalAction.example]:narrative.examples,tips:positionalAction?[formatPmPositionalActionFlagTip(positionalAction.accepted_flags)]:narrative.tips,arguments:projection.arguments,options:projection.options,subcommands:projection.subcommands,has_subcommands:projection.subcommands.length>0,...fullCommandAliases===void 0?{}:{command_aliases:fullCommandAliases}}}async function maybeRenderBootstrapJsonHelp(rootProgram,argv,extensionDescriptors,requestedArgv=argv){const bootstrapGlobal=parseBootstrapGlobalOptions(argv);if(!bootstrapGlobal.json)return!1;const helpRequest=parseBootstrapHelpRequest(argv);if(!helpRequest.requested)return!1;const targetCommand=resolveCommandFromPathTokens(rootProgram,helpRequest.commandPathTokens);if(!targetCommand){if(!bootstrapGlobal.quiet){const unknownMessage=`unknown command '${resolvePmCommandOperation(helpRequest.commandPathTokens.join(" "))}'`,runtimeContext=buildUnknownCommandGuidanceFromRuntime(unknownMessage,rootProgram,extensionDescriptors),envelope=formatCommanderErrorForJson(unknownMessage,"help",BUILTIN_TYPE_HELP_VALUES,EXIT_CODE.USAGE,{...runtimeContext,attemptedCommand:renderAttemptedCommand(argv),normalizedInvocationArgs:[...argv],providedOptionFlags:extractProvidedOptionFlags(argv)}),output=bootstrapGlobal.tokenAccounting?attachOutputTokenAccounting(envelope,value=>`${JSON.stringify(value,null,2)}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3f896a8d-2c03-5f9c-9909-4684a187870d")}catch{}})();import{hasSubcommandFlagContractsForCommand,PM_COMMAND_ALIAS_CONTRACTS,PM_CORE_COMMAND_NAMES,resolvePmCommandAlias,resolvePmCommandOperation}from"../sdk/cli-contracts.js";import{commandOptionFlagLabel,resolveCommandOptionPolicyState,resolveTypeDefinition,EXIT_CODE,writeStderr,writeStdout}from"../sdk/runtime-primitives.js";import{buildDynamicExtensionHelpOptionSummaries,mergeHelpOptionSummaries,findCommandByPath,findDirectChildCommand,commandAliases}from"./extension-command-help.js";import{getPmCommandHelpVisibilityTier,isFullHelpDiscovery,normalizeHelpCommandPath,resolveHelpBundleForPath,resolveHelpDetailMode,resolveHelpNarrative,ROOT_HELP_BUNDLE}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapCommandName,parseBootstrapTypeValue}from"./bootstrap-args.js";import{extractProvidedOptionFlags,renderPmCommand}from"./argv-utils.js";import{formatCommanderErrorForJson}from"./error-guidance.js";import{BUILTIN_TYPE_HELP_VALUES,buildUnknownCommandGuidanceFromRuntime,isKnownHelpCommandPath}from"./commander-usage.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{resolveCreateExplicitEmptyFlag}from"../sdk/agent/create-option-policy.js";import{formatPmPositionalActionFlagTip,PM_POSITIONAL_ACTION_CONTRACTS,resolvePmPositionalActionContract}from"../sdk/cli-contracts/grammar-contracts.js";import{resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"../sdk/agent-capability-contracts.js";const EXTENSION_TIER_ORDER={core:0,standard:1,full:2,internal:3};function resolveExtensionCommandSurface(commandPath,descriptors,allowDescendants=!0){const exact=descriptors.get(resolvePmCommandOperation(commandPath));if(exact)return exact;if(!allowDescendants)return;const descendants=[...descriptors.entries()].filter(([path])=>path.startsWith(`${commandPath} `)).map(([,descriptor])=>descriptor);if(descendants.length===0)return;const tier=descendants.reduce((selected,descriptor)=>EXTENSION_TIER_ORDER[descriptor.tier]<EXTENSION_TIER_ORDER[selected]?descriptor.tier:selected,"internal"),families=new Set(descendants.map(({family})=>family));return{tier,family:families.size===1?descendants[0].family:"extensions"}}function resolveCommandFromPathTokens(root,pathTokens){if(pathTokens.length===0)return root;const exactCommand=findCommandByPath(root,pathTokens);if(exactCommand)return exactCommand;const requestedPath=pathTokens.join(" ");if(resolvePmCommandOperation(requestedPath)!==requestedPath||!PM_CORE_COMMAND_NAMES.some(commandName=>commandName===requestedPath)&&!hasSubcommandFlagContractsForCommand(requestedPath)&&!resolvePmPositionalActionContract(requestedPath)&&!isKnownHelpCommandPath(root,pathTokens))return null;for(let length=pathTokens.length-1;length>0;length-=1){const positionalParent=findCommandByPath(root,pathTokens.slice(0,length));if(positionalParent)return positionalParent}return pathTokens.length===1?root:null}function extractOptionValueName(flags){const match=flags.match(/[<[]([^>\]]+)[>\]]/);if(!match)return null;const value=match[1]?.trim();return value&&value.length>0?value:null}function readOptionAttributeName(option){const optionRecord=option;if(typeof optionRecord.attributeName=="function"){const value=optionRecord.attributeName();return typeof value=="string"&&value.trim().length>0?value.trim():null}return typeof optionRecord.attributeName=="string"&&optionRecord.attributeName.trim().length>0?optionRecord.attributeName.trim():null}function buildOptionAliasMap(options){const aliasMap=new Map;for(const option of options){const optionRecord=option,attributeName=readOptionAttributeName(option);if(!attributeName||typeof optionRecord.long!="string"||optionRecord.long.trim().length===0)continue;const existing=aliasMap.get(attributeName)??[];existing.push(optionRecord.long.trim()),aliasMap.set(attributeName,existing)}for(const[attributeName,values]of aliasMap.entries())aliasMap.set(attributeName,[...new Set(values.map(value=>value.trim()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right)));return aliasMap}function renderAttemptedCommand(argv){return renderPmCommand(argv)}function buildHelpOptionSummaries(command){const options=command.options??[],optionAliasMap=buildOptionAliasMap(options);return options.map(option=>{const optionRecord=option,flags=typeof optionRecord.flags=="string"?optionRecord.flags.trim():"",description=typeof optionRecord.description=="string"?optionRecord.description.trim():"",attributeName=readOptionAttributeName(option),aliases=(attributeName?optionAliasMap.get(attributeName)??[]:[]).filter(entry=>entry!==optionRecord.long).map(entry=>entry.trim()).filter(entry=>entry.length>0),aliasForMatch=description.match(/^Alias for ([^ ]+)/i),aliasFor=aliasForMatch&&aliasForMatch[1]?aliasForMatch[1].trim():null,required=optionRecord.mandatory===!0||description.includes("[required]")||description.toLowerCase().includes("required;"),valueRequired=flags.includes("<"),takesValue=valueRequired||flags.includes("["),summary={flags,long:typeof optionRecord.long=="string"?optionRecord.long:null,short:typeof optionRecord.short=="string"?optionRecord.short:null,description,takes_value:takesValue,value_required:valueRequired,value_name:extractOptionValueName(flags),variadic:optionRecord.variadic===!0,required,aliases,alias_for:aliasFor};return optionRecord.defaultValue!==void 0&&(summary.default_value=optionRecord.defaultValue),summary})}function compactHelpOptionAliases(options){const canonicalByLong=new Map,aliasOptions=[];for(const option of options){if(option.alias_for&&option.long){aliasOptions.push(option);continue}option.long&&canonicalByLong.set(option.long,option)}for(const aliasOption of aliasOptions){const aliasFor=aliasOption.alias_for,canonical=canonicalByLong.get(aliasFor);if(!canonical)continue;const aliasLong=aliasOption.long,aliases=new Set([...canonical.aliases??[],aliasLong]);canonical.aliases=[...aliases].sort((left,right)=>left.localeCompare(right))}return options.filter(option=>!option.alias_for||!option.long?!0:!canonicalByLong.has(option.alias_for))}function buildHelpArgumentSummaries(command){const commandRecord=command;return(Array.isArray(commandRecord.registeredArguments)?commandRecord.registeredArguments:Array.isArray(commandRecord._args)?commandRecord._args:[]).map(argument=>{const rawName=typeof argument.name=="function"?argument.name():typeof argument.name=="string"?argument.name:"argument",description=typeof argument.description=="string"&&argument.description.trim().length>0?argument.description.trim():null;return{name:rawName.trim(),required:argument.required===!0||description?.toLowerCase().startsWith("required;")===!0,variadic:argument.variadic===!0,description}})}function buildHelpSubcommandSummaries(command,extensionDescriptors=new Map,includeAll=!1){const visible=command.createHelp().visibleCommands(command);return(includeAll?[...new Set([...visible,...command.commands])]:visible).filter(entry=>entry.name()!=="help"||command.parent===null).filter(entry=>!includeAll||(getPmCommandHelpVisibilityTier(entry)??resolvePmCommandVisibilityTier(entry.name()))!=="internal").map(entry=>{const commandPath=normalizeHelpCommandPath(getCommandPath(entry)),rootCommand=commandPath,declaredTier=getPmCommandHelpVisibilityTier(entry),extensionDescriptor=resolveExtensionCommandSurface(commandPath,extensionDescriptors,declaredTier!==void 0),aliasContract=PM_COMMAND_ALIAS_CONTRACTS.find(({alias})=>alias===commandPath);return{name:entry.name().trim(),aliases:commandAliases(entry),description:entry.description().trim(),tier:extensionDescriptor?.tier??declaredTier??resolvePmCommandVisibilityTier(rootCommand),family:extensionDescriptor?.family??resolvePmCommandCapabilityFamily(rootCommand),...aliasContract?{alias_for:aliasContract.canonical,alias_lifecycle:aliasContract.lifecycle,...aliasContract.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((left,right)=>left.name.localeCompare(right.name))}function buildJsonHelpNarrative(detailMode,fallbackNarrative,extensionDescriptor){if(!extensionDescriptor)return fallbackNarrative;const extensionExamples=extensionDescriptor.examples??[],extensionFailureHints=extensionDescriptor.failure_hints??[];return{intent:extensionDescriptor.intent??extensionDescriptor.description??fallbackNarrative.intent,examples:detailMode==="detailed"?extensionExamples.length>0?[...extensionExamples]:[...fallbackNarrative.examples]:extensionExamples.length>0?[extensionExamples[0]]:[...fallbackNarrative.examples],tips:detailMode==="detailed"?extensionFailureHints.length>0?[...extensionFailureHints]:[...fallbackNarrative.tips]:[],detail_mode:detailMode}}function resolveJsonHelpNarrative(commandPath,commandDescription,detailMode,extensionDescriptor,hasPositionalAction){const isRootFallback=commandPath!==void 0&&resolveHelpBundleForPath(commandPath)===ROOT_HELP_BUNDLE,fallback=isRootFallback?{intent:commandDescription,examples:[`pm ${commandPath} --help`],tips:[],detail_mode:detailMode}:resolveHelpNarrative(commandPath,detailMode),intentSource=hasPositionalAction?"positional_action":extensionDescriptor?.intent||extensionDescriptor?.description?"extension":isRootFallback?commandDescription?"command_description":"unavailable":commandPath?"help_bundle":"root_help_bundle";return{narrative:buildJsonHelpNarrative(detailMode,fallback,extensionDescriptor),intentSource}}function resolveJsonHelpVisibilityTier(rootCommandPath,extensionDescriptor){return rootCommandPath===void 0?null:extensionDescriptor?.tier??resolvePmCommandVisibilityTier(rootCommandPath)}function resolveJsonHelpCapabilityFamily(rootCommandPath,extensionDescriptor){return rootCommandPath===void 0?null:extensionDescriptor?.family??resolvePmCommandCapabilityFamily(rootCommandPath)}function projectFullCommandAliases(rootProgram,targetCommand,fullDiscovery){if(!(targetCommand!==rootProgram||!fullDiscovery))return PM_COMMAND_ALIAS_CONTRACTS.map(contract=>({alias:contract.alias,canonical:contract.canonical,canonical_argv:[...contract.canonical_argv],available:resolveCommandFromPathTokens(rootProgram,contract.canonical.split(" "))!==null,lifecycle:contract.lifecycle,hidden:contract.hidden,deprecated:contract.lifecycle==="deprecated"}))}function buildPositionalActionHelpProjection(action,targetCommand,resolvedPath,allOptions,extensionDescriptors=new Map,includeAll=!1){if(!action){const argumentsList=buildHelpArgumentSummaries(targetCommand),registeredSubcommands=buildHelpSubcommandSummaries(targetCommand,extensionDescriptors,includeAll),registeredSubcommandNames=new Set(registeredSubcommands.map(({name})=>name));return{arguments:argumentsList,options:allOptions,subcommands:[...registeredSubcommands,...PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent,action:name})=>parent===resolvedPath&&!registeredSubcommandNames.has(name)).map(({action:name,description})=>({name,aliases:[],description,tier:resolvePmCommandVisibilityTier(resolvedPath.split(" ")[0]),family:resolvePmCommandCapabilityFamily(resolvedPath.split(" ")[0])}))].sort((left,right)=>left.name.localeCompare(right.name)),usage:[resolvedPath,argumentsList.reduce((usage,argument)=>argument.required?usage.replace(`[${argument.name}${argument.variadic?"...":""}]`,`<${argument.name}${argument.variadic?"...":""}>`):usage,targetCommand.usage())].filter(token=>token.length>0).join(" ")}}const acceptedFlags=new Set(action.accepted_flags);return{arguments:action.slots.map(({name,required,variadic,value_kind:valueKind,polymorphic})=>({name,required,variadic,description:polymorphic?`Polymorphic ${valueKind} value; inspect the action contract before mutation.`:`${valueKind.replaceAll("_"," ")} value.`})),options:allOptions.filter(({long,aliases})=>long!==null&&acceptedFlags.has(long)||aliases.some(alias=>acceptedFlags.has(alias))),subcommands:[],usage:[action.command,...action.slots.map(({name,required,variadic})=>{const token=variadic?`${name}...`:name;return required?`<${token}>`:`[${token}]`})].join(" ")}}function buildJsonHelpPayload(rootProgram,targetCommand,argv,requestedPath,extensionDescriptors){const detailMode=resolveHelpDetailMode(argv),fullDiscovery=isFullHelpDiscovery(argv),commanderPath=normalizeHelpCommandPath(getCommandPath(targetCommand)),requestedCommandPath=normalizeHelpCommandPath(requestedPath.join(" ")),resolvedPath=requestedCommandPath.length>commanderPath.length?requestedCommandPath:commanderPath,positionalAction=resolvePmPositionalActionContract(resolvedPath),projectedPath=positionalAction?.command??commanderPath,commandPath=projectedPath.length>0?projectedPath:void 0,rootCommandPath=commandPath,extensionDescriptor=commandPath?extensionDescriptors.get(resolvePmCommandOperation(commandPath)):void 0,extensionSurface=commandPath?resolveExtensionCommandSurface(commandPath,extensionDescriptors,getPmCommandHelpVisibilityTier(targetCommand)!==void 0):void 0,{narrative,intentSource}=resolveJsonHelpNarrative(commandPath,targetCommand.description().trim(),detailMode,extensionDescriptor,positionalAction!==void 0),allOptionSummaries=compactHelpOptionAliases(mergeHelpOptionSummaries(buildHelpOptionSummaries(targetCommand),buildDynamicExtensionHelpOptionSummaries(extensionDescriptor))),projection=buildPositionalActionHelpProjection(positionalAction,targetCommand,projectedPath,allOptionSummaries,extensionDescriptors,fullDiscovery),fullCommandAliases=projectFullCommandAliases(rootProgram,targetCommand,fullDiscovery);return{format:"pm_help_v1",detail_mode:detailMode,root_command:rootProgram.name(),requested_path:requestedPath,resolved_path:projectedPath.length>0?projectedPath:rootProgram.name(),visibility_tier:resolveJsonHelpVisibilityTier(rootCommandPath,extensionSurface),capability_family:resolveJsonHelpCapabilityFamily(rootCommandPath,extensionSurface),description:positionalAction?.description??targetCommand.description(),usage:projection.usage,intent:positionalAction?.description??narrative.intent,intent_source:intentSource,examples:positionalAction?[positionalAction.example]:narrative.examples,tips:positionalAction?[formatPmPositionalActionFlagTip(positionalAction.accepted_flags)]:narrative.tips,arguments:projection.arguments,options:projection.options,subcommands:projection.subcommands,has_subcommands:projection.subcommands.length>0,...fullCommandAliases===void 0?{}:{command_aliases:fullCommandAliases}}}async function maybeRenderBootstrapJsonHelp(rootProgram,argv,extensionDescriptors,requestedArgv=argv){const bootstrapGlobal=parseBootstrapGlobalOptions(argv);if(!bootstrapGlobal.json)return!1;const helpRequest=parseBootstrapHelpRequest(argv);if(!helpRequest.requested)return!1;const targetCommand=resolveCommandFromPathTokens(rootProgram,helpRequest.commandPathTokens);if(!targetCommand){if(!bootstrapGlobal.quiet){const unknownMessage=`unknown command '${helpRequest.commandPathTokens.join(" ")}'`,runtimeContext=buildUnknownCommandGuidanceFromRuntime(unknownMessage,rootProgram,extensionDescriptors,argv),envelope=formatCommanderErrorForJson(unknownMessage,"help",BUILTIN_TYPE_HELP_VALUES,EXIT_CODE.USAGE,{...runtimeContext,attemptedCommand:renderAttemptedCommand(argv),normalizedInvocationArgs:[...argv],providedOptionFlags:extractProvidedOptionFlags(argv)}),output=bootstrapGlobal.tokenAccounting?attachOutputTokenAccounting(envelope,value=>`${JSON.stringify(value,null,2)}
2
2
  `):envelope;writeStderr(`${JSON.stringify(output,null,2)}
3
3
  `)}return process.exitCode=EXIT_CODE.USAGE,!0}if(!bootstrapGlobal.quiet){const payload=buildJsonHelpPayload(rootProgram,targetCommand,argv,helpRequest.commandPathTokens,extensionDescriptors),originalPath=parseBootstrapHelpRequest(requestedArgv).commandPathTokens;payload.requested_path=originalPath;const alias=resolvePmCommandAlias(originalPath.join(" "));alias&&(payload.resolved_path=alias.canonical),targetCommand===rootProgram&&!isFullHelpDiscovery(argv)&&(payload.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),writeStdout(`${JSON.stringify(payload,null,2)}
4
4
  `)}return process.exitCode=EXIT_CODE.SUCCESS,!0}function buildCreateUpdatePolicyIntro(commandName,typeRegistry){const lines=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${typeRegistry.types.join("|")}`];return commandName==="create"&&lines.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),lines.join(`
@@ -107,6 +107,7 @@ declare function maybeLoadRuntimeExtensions(command: Command): Promise<{
107
107
  registrations: ReturnType<typeof createEmptyExtensionRegistrationRegistry>;
108
108
  pmRoot: string;
109
109
  } | null>;
110
+ /** Load the complete installed registry for recovery without registering guessed command handlers. */
110
111
  declare function loadRuntimeExtensionCommandDescriptorsForRecovery(pmRoot: string): Promise<Map<string, ExtensionCommandHelpDescriptor>>;
111
112
  declare function executeRegisteredRuntimeMigrations(migrations: RegisteredExtensionSchemaMigrationDefinition[], pmRoot: string): Promise<string[]>;
112
113
  declare function runRequiredExtensionCommand(command: Command, options: Record<string, unknown>, globalOptions: GlobalOptions, extensionFlagDefinitions?: LooseCommandFlagDefinition[]): Promise<unknown>;