@unbrained/pm-cli 2026.10.22 → 2026.10.23

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 (149) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +17 -0
  3. package/dist/cli/error-guidance.d.ts +12 -0
  4. package/dist/cli/error-guidance.js +2 -2
  5. package/dist/cli/register-setup.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/{chunk-5LSN7K4N.js → chunk-2LTGJ5DL.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-E3JC3WQL.js → chunk-2UX2TAN2.js} +15 -15
  9. package/dist/cli-bundle/chunks/{chunk-2B5HAZFK.js → chunk-3S5FLCG7.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-J444ZX23.js → chunk-5DKCD4KV.js} +39 -39
  11. package/dist/cli-bundle/chunks/{chunk-LIC5EUQS.js → chunk-5V4HU6GK.js} +48 -48
  12. package/dist/cli-bundle/chunks/{chunk-UYYTV2TX.js → chunk-AAX7CNL7.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-AOAQDCXX.js → chunk-AXGFNNI3.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-F76ZUP73.js +113 -0
  15. package/dist/cli-bundle/chunks/chunk-HDKY2YX3.js +3 -0
  16. package/dist/cli-bundle/chunks/{chunk-7OTYULIJ.js → chunk-KY34HTT2.js} +29 -29
  17. package/dist/cli-bundle/chunks/{chunk-TNU3XVPC.js → chunk-MMVX5L32.js} +3 -3
  18. package/dist/cli-bundle/chunks/{chunk-PCPOTFJP.js → chunk-MTRYEVZR.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-O67N62DT.js → chunk-QSY55FTA.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-GWIGZDRS.js → chunk-R7KWBFM2.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-HC2DCGFA.js → chunk-REXCO5AG.js} +2 -2
  22. package/dist/cli-bundle/chunks/chunk-ZDVTXLA6.js +9 -0
  23. package/dist/cli-bundle/chunks/{chunk-MV3KYY2A.js → chunk-ZEI3DC5E.js} +3 -3
  24. package/dist/cli-bundle/chunks/{chunk-URV4VHQ4.js → chunk-ZMJF5HQW.js} +2 -2
  25. package/dist/cli-bundle/chunks/chunk-ZNDYAZZ6.js +6 -0
  26. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-L3BOTMZN.js → indexed-receipt-blobs-XANVELIV.js} +2 -2
  27. package/dist/cli-bundle/chunks/{mutation-admission-TATOFEXF.js → mutation-admission-P6LOBNLO.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-list-query-GULR2IYO.js → register-list-query-JOB65KDN.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-mutation-HLSQ4WVW.js → register-mutation-QMNIN3RJ.js} +2 -2
  30. package/dist/cli-bundle/chunks/{register-operations-FE3GGA7O.js → register-operations-Z4VET3I7.js} +2 -2
  31. package/dist/cli-bundle/chunks/register-setup-GNKWL3VL.js +2 -0
  32. package/dist/cli-bundle/chunks/{settlement-hook-UVFYSBMU.js → settlement-hook-YUVCO65H.js} +2 -2
  33. package/dist/cli-bundle/chunks/{stage-QCPZBZRC.js → stage-FW5OXCCR.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-EHPRSWJE.js → chunk-4MNUQCGR.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-CB7TSZ7P.js → chunk-6GTZ24YV.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-2GFTVXKZ.js → chunk-BM652VCB.js} +3 -3
  37. package/dist/cli-bundle/focused-chunks/{chunk-3LWH2RJC.js → chunk-BUZ2Z4P3.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-QGDKWULS.js → chunk-CGL36F6I.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-TMN3RAXZ.js → chunk-DWQMYLFM.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-SXVJRLLP.js → chunk-EDXTOAXP.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-FO4U3FIP.js +91 -0
  42. package/dist/cli-bundle/focused-chunks/chunk-GXKP56W7.js +2 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-46HBJC6J.js → chunk-I2USTQNQ.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-XX5JQCLF.js → chunk-JDN34LEZ.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-GVKYTDOH.js → chunk-KI5YFKNN.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-UQ5JPBY2.js → chunk-LEHGCPZ6.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-KM77WU5U.js → chunk-MLET6I3I.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-25NQRZ7J.js → chunk-NSMZY6IK.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-OMXMYTEX.js +26 -0
  50. package/dist/cli-bundle/focused-chunks/{chunk-VYAZND5Q.js → chunk-P7DPS5M4.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/chunk-R536272H.js +9 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-CX5FNEFC.js → chunk-UNTCCJPL.js} +3 -3
  53. package/dist/cli-bundle/focused-chunks/{chunk-A52W6GLA.js → chunk-XIZYJDYW.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-25L3L2PF.js → chunk-Z5LDTMZ3.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-ZHMF34DT.js +65 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-GC4VMLXL.js → chunk-ZR6ZKQUK.js} +3 -3
  57. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-AAQOKO5B.js → indexed-receipt-blobs-FVOA3XMI.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{mutation-admission-TBKR4KRM.js → mutation-admission-HTFAIHJL.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{settlement-hook-MNCHFCAX.js → settlement-hook-2VXEB6PP.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{stage-RM6MJIMT.js → stage-X3BUGEJT.js} +2 -2
  61. package/dist/cli-bundle/main.js +21 -21
  62. package/dist/cli-bundle/sdk-authoring.js +1 -1
  63. package/dist/cli-bundle/sdk-contracts.js +5 -2
  64. package/dist/cli-bundle/sdk-core.js +33 -33
  65. package/dist/cli-bundle/sdk-governance.js +1 -1
  66. package/dist/cli-bundle/sdk-graph.js +1 -1
  67. package/dist/cli-bundle/sdk-merge.js +58 -58
  68. package/dist/cli-bundle/sdk-query.js +1 -1
  69. package/dist/cli-bundle/sdk-runtime.js +1 -1
  70. package/dist/cli-bundle/sdk-testing.js +1 -1
  71. package/dist/cli-bundle/sdk.js +12 -9
  72. package/dist/core/config/nested-settings.js +1 -1
  73. package/dist/core/extensions/loader.js +1 -1
  74. package/dist/core/extensions/version-diagnostics.d.ts +2 -0
  75. package/dist/core/extensions/version-diagnostics.js +2 -0
  76. package/dist/core/lock/lock.d.ts +40 -6
  77. package/dist/core/lock/lock.js +3 -3
  78. package/dist/core/shared/errors.d.ts +28 -0
  79. package/dist/core/shared/errors.js +1 -1
  80. package/dist/core/store/item-store.js +1 -1
  81. package/dist/mcp/http-server.js +2 -2
  82. package/dist/mcp/server.js +2 -2
  83. package/dist/sdk/cli-contracts/agent-output-contracts.js +1 -1
  84. package/dist/sdk/contracts.d.ts +1 -0
  85. package/dist/sdk/contracts.js +1 -1
  86. package/dist/sdk/extension/doctor.js +1 -1
  87. package/dist/sdk/extension/install-receipts.js +1 -1
  88. package/dist/sdk/extension/install-snapshot.d.ts +11 -0
  89. package/dist/sdk/extension/install-snapshot.js +1 -1
  90. package/dist/sdk/extension.d.ts +12 -0
  91. package/dist/sdk/extension.js +1 -1
  92. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  93. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  94. package/dist/sdk/governance/health.d.ts +1 -0
  95. package/dist/sdk/governance/health.js +2 -2
  96. package/dist/sdk/index.d.ts +3 -2
  97. package/dist/sdk/index.js +1 -1
  98. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  99. package/dist/sdk/lifecycle/restore.js +1 -1
  100. package/dist/sdk/mcp/executable.d.ts +13 -0
  101. package/dist/sdk/mcp/executable.js +5 -0
  102. package/dist/sdk/public-surface.json +1 -1
  103. package/dist/sdk/runtime-primitives.d.ts +1 -1
  104. package/dist/sdk/runtime-primitives.js +1 -1
  105. package/dist/sdk/runtime.d.ts +1 -1
  106. package/dist/sdk/runtime.js +1 -1
  107. package/dist/sdk/workspace-snapshot.d.ts +5 -1
  108. package/dist/sdk/workspace-snapshot.js +3 -3
  109. package/dist/sdk/workspace.js +2 -2
  110. package/docs/CONFIGURATION.md +19 -3
  111. package/docs/EXTENSION_AUTHOR_CONTRACTS.md +2 -1
  112. package/docs/EXTENSION_LIFECYCLE.md +47 -0
  113. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +16 -1
  114. package/docs/RELEASING.md +9 -0
  115. package/docs/SDK.md +39 -5
  116. package/docs/SDK_STORAGE_LIFECYCLE.md +2 -1
  117. package/docs/TESTING.md +11 -7
  118. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  119. package/marketplace.json +1 -1
  120. package/package.json +1 -1
  121. package/packages/pm-beads/package.json +1 -1
  122. package/packages/pm-calendar/package.json +1 -1
  123. package/packages/pm-command-kit/package.json +1 -1
  124. package/packages/pm-digital-twin/package.json +1 -1
  125. package/packages/pm-governance-audit/package.json +1 -1
  126. package/packages/pm-guide-shell/package.json +1 -1
  127. package/packages/pm-kanban/package.json +1 -1
  128. package/packages/pm-lifecycle-hooks/package.json +1 -1
  129. package/packages/pm-linked-test-adapters/package.json +1 -1
  130. package/packages/pm-search-advanced/package.json +1 -1
  131. package/packages/pm-templates/package.json +1 -1
  132. package/packages/pm-todos/package.json +1 -1
  133. package/packages/pm-vcs/package.json +1 -1
  134. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  135. package/plugins/pm-claude/package.json +1 -1
  136. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  137. package/plugins/pm-codex/package.json +1 -1
  138. package/plugins/pm-codex/plugin.json +1 -1
  139. package/runtime-dependencies.json +1 -1
  140. package/dist/cli-bundle/chunks/chunk-35ISFIPC.js +0 -113
  141. package/dist/cli-bundle/chunks/chunk-BAIVTLJM.js +0 -6
  142. package/dist/cli-bundle/chunks/chunk-C37RDYZI.js +0 -3
  143. package/dist/cli-bundle/chunks/chunk-VO3KDIU7.js +0 -9
  144. package/dist/cli-bundle/chunks/register-setup-XUIKAIZA.js +0 -2
  145. package/dist/cli-bundle/focused-chunks/chunk-DVNUHTVK.js +0 -9
  146. package/dist/cli-bundle/focused-chunks/chunk-QWKCQ5PW.js +0 -91
  147. package/dist/cli-bundle/focused-chunks/chunk-SOVXHW6Z.js +0 -2
  148. package/dist/cli-bundle/focused-chunks/chunk-UUPJ6OZL.js +0 -26
  149. package/dist/cli-bundle/focused-chunks/chunk-W2CND3BD.js +0 -65
@@ -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.22","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.22","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.23","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.23","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,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026.10.23 - 2026-10-23
4
+
5
+ ### Fixed
6
+
7
+ - GH-1516: queued writers fail at a fixed lock deadline even while the lock is changing hands ([pm-iop1pg](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-iop1pg.toon))
8
+ - GH-1549: fence item commits after an expired mutation lease is taken over ([pm-gh1549](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1549.toon))
9
+ - PR1548: preserve rollback diagnostic provenance and reject non-directory ancestry ([pm-4vymxc](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-4vymxc.toon))
10
+ - Bound complete nightly validation and exact coverage within existing job deadlines ([pm-gxq0dt](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gxq0dt.toon))
11
+ - Resolve aliased workspace paths before publishing tracker cache exclusions ([pm-p8s5k7e6lhda](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-p8s5k7e6lhda.toon))
12
+ - GH-1546: keep disabled package compatibility findings advisory ([pm-5xn8we1wue0m](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-5xn8we1wue0m.toon))
13
+ - GH-1545: preserve working package replacements through activation verification ([pm-c9wz5ef4ulnv](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-c9wz5ef4ulnv.toon))
14
+ - GH-1540: MCP binaries ignore help and version probes before transport startup ([pm-gh1540](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1540.toon))
15
+
16
+ ### Other
17
+
18
+ - Retain original dependency advisory receipts on release workflow failures ([pm-z20n3s](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-z20n3s.toon))
19
+
3
20
  ## 2026.10.22 - 2026-10-22
4
21
 
5
22
  ### Fixed
@@ -9,6 +9,10 @@ transactionOperation?:PmCliErrorContext["transaction_operation"];
9
9
  /** Bounded tracker-relative preview refusal coordinate. */
10
10
  previewStorage?:PmCliErrorContext["preview_storage"];
11
11
  tombstone?:PmCliErrorContext["tombstone"];
12
+ /** Lease a refused lock_lost commit held. */
13
+ lease?:PmCliErrorContext["lease"];
14
+ /** Lock generation observed at a refused lock_lost commit. */
15
+ currentOwner?:PmCliErrorContext["current_owner"];
12
16
  code:string;
13
17
  type:string;
14
18
  title:string;
@@ -53,6 +57,10 @@ preview_storage?:PmCliErrorContext["preview_storage"];
53
57
  item_id?:string;
54
58
  /** Verified retained deletion and its recoverable version. */
55
59
  tombstone?:PmCliErrorContext["tombstone"];
60
+ /** Lease a refused lock_lost commit held. */
61
+ lease?:PmCliErrorContext["lease"];
62
+ /** Lock generation observed at a refused lock_lost commit, or null when none exists. */
63
+ current_owner?:PmCliErrorContext["current_owner"];
56
64
  /** Schema type that determines the shape and validation rules for this value. */
57
65
  type:string;
58
66
  /** Value that configures or reports code for this contract. */
@@ -104,6 +112,10 @@ preview_storage?:PmCliErrorContext["preview_storage"];
104
112
  item_id?:string;
105
113
  /** Verified retained deletion and its recoverable version. */
106
114
  tombstone?:PmCliErrorContext["tombstone"];
115
+ /** Lease a refused lock_lost commit held. */
116
+ lease?:PmCliErrorContext["lease"];
117
+ /** Lock generation observed at a refused lock_lost commit, or null when none exists. */
118
+ current_owner?:PmCliErrorContext["current_owner"];
107
119
  /** Schema type that determines the shape and validation rules for this value. */
108
120
  type:string;
109
121
  /** Value that configures or reports code for this contract. */
@@ -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]="653eac45-8b2b-5b9e-944f-6a6f9efe45a1")}catch{}})();import{isReadProjectionRecoveryFlag,resolveReadOptionRetryArgs}from"../sdk/agent/command-recovery.js";import{isPmTokenBudgetRecovery}from"../sdk/errors.js";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 normalizeRecoveryArgs(value){return Array.isArray(value)&&value.length>0&&value.every(entry=>typeof entry=="string")?[...value]:void 0}function assignRecoveryCollection(normalized,key,value){if(key==="normalized_args"||key==="suggested_retry_args"){const args=normalizeRecoveryArgs(value);args&&(normalized[key]=args);return}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 assignRecoveryTokenBudget(target,value){if(!isPmTokenBudgetRecovery(value))return;const{requested_tokens,feasible_tokens,minimum_feasible_tokens,minimum_status,basis,reason}=value;target.token_budget={requested_tokens,feasible_tokens,minimum_feasible_tokens,minimum_status,basis,reason}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!="object")return;const normalized={};assignRecoveryTokenBudget(normalized,payload.token_budget),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(normalized.token_budget){const budget=normalized.token_budget;lines.push(` requested_token_budget: ${budget.requested_tokens}`,` feasible_token_budget: ${budget.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${budget.minimum_feasible_tokens??"not established"}`)}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.previewStorage!==void 0&&(payload.preview_storage=message.previewStorage),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.changed===!1?{changed:!1}:{}},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.changed===!1?{changed:!1}:{}},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,changed:context.changed,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,previewStorage:context.preview_storage,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){if(!message.includes("is locked"))return null;const args=normalizeRecoveryArgs(context?.recovery?.normalized_args),retry=args?renderPmCommand(args):void 0,guidance=applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:retry?[retry]:["pm gc --scope locks --dry-run"]}),rawMessage,context);return args&&(guidance.recovery={...guidance.recovery,suggested_retry:retry,suggested_retry_args:[...args]}),guidance}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 resolveReadIntentRetry(context,optionName,commandName){const retry=resolveReadOptionRetryArgs(commandName??"",context.normalizedInvocationArgs??[],optionName);return retry?{retryCommand:renderPmCommand(retry),suggestedRetryArgs:retry}:["--full","--depth","--toon"].includes(optionName.split("=",1)[0])?{}:void 0}function resolveUnknownOptionRetry(context,optionName,commandName){if(["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0]))return{};const readRetry=resolveReadIntentRetry(context,optionName,commandName);if(readRetry)return readRetry;if(context.suggestedRetryCommand!==void 0)return{retryCommand:context.suggestedRetryCommand};if(isReadProjectionRecoveryFlag(optionName))return{};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,commandName);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]="66e52448-b814-50c5-894e-42e54244a442")}catch{}})();import{isReadProjectionRecoveryFlag,resolveReadOptionRetryArgs}from"../sdk/agent/command-recovery.js";import{isPmTokenBudgetRecovery}from"../sdk/errors.js";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 normalizeRecoveryArgs(value){return Array.isArray(value)&&value.length>0&&value.every(entry=>typeof entry=="string")?[...value]:void 0}function assignRecoveryCollection(normalized,key,value){if(key==="normalized_args"||key==="suggested_retry_args"){const args=normalizeRecoveryArgs(value);args&&(normalized[key]=args);return}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 assignRecoveryTokenBudget(target,value){if(!isPmTokenBudgetRecovery(value))return;const{requested_tokens,feasible_tokens,minimum_feasible_tokens,minimum_status,basis,reason}=value;target.token_budget={requested_tokens,feasible_tokens,minimum_feasible_tokens,minimum_status,basis,reason}}const RECOVERY_COUNTER_KEYS=["retry_after_ms","waited_ms","owner_handoffs"];function appendRecoveryCounterLines(lines,normalized){for(const key of RECOVERY_COUNTER_KEYS)typeof normalized[key]=="number"&&lines.push(` ${key}: ${normalized[key]}`)}function assignRecoveryCounters(normalized,payload){for(const key of RECOVERY_COUNTER_KEYS){const value=payload[key];typeof value=="number"&&Number.isSafeInteger(value)&&value>=0&&(normalized[key]=value)}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!="object")return;const normalized={};assignRecoveryTokenBudget(normalized,payload.token_budget),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),assignRecoveryCounters(normalized,payload);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(normalized.token_budget){const budget=normalized.token_budget;lines.push(` requested_token_budget: ${budget.requested_tokens}`,` feasible_token_budget: ${budget.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${budget.minimum_feasible_tokens??"not established"}`)}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}`),appendRecoveryCounterLines(lines,normalized),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 attachItemDiagnostics(payload,message){message.tombstone!==void 0&&(payload.tombstone=message.tombstone,payload.item_id=message.itemId),message.lease!==void 0&&(payload.lease=message.lease,payload.current_owner=message.currentOwner??null,payload.item_id=message.itemId)}function attachStructuredGuidanceDetails(payload,message){return message.previewStorage!==void 0&&(payload.preview_storage=message.previewStorage),message.transactionOperation!==void 0&&(payload.transaction_operation=message.transactionOperation),attachItemDiagnostics(payload,message),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.changed===!1?{changed:!1}:{}},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.changed===!1?{changed:!1}:{}},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,changed:context.changed,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,previewStorage:context.preview_storage,tombstone:context.tombstone,lease:context.lease,currentOwner:context.current_owner,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){if(!message.includes("is locked"))return null;const args=normalizeRecoveryArgs(context?.recovery?.normalized_args),retry=args?renderPmCommand(args):void 0,guidance=applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:retry?[retry]:["pm gc --scope locks --dry-run"]}),rawMessage,context);return args&&(guidance.recovery={...guidance.recovery,suggested_retry:retry,suggested_retry_args:[...args]}),guidance}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 resolveReadIntentRetry(context,optionName,commandName){const retry=resolveReadOptionRetryArgs(commandName??"",context.normalizedInvocationArgs??[],optionName);return retry?{retryCommand:renderPmCommand(retry),suggestedRetryArgs:retry}:["--full","--depth","--toon"].includes(optionName.split("=",1)[0])?{}:void 0}function resolveUnknownOptionRetry(context,optionName,commandName){if(["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0]))return{};const readRetry=resolveReadIntentRetry(context,optionName,commandName);if(readRetry)return readRetry;if(context.suggestedRetryCommand!==void 0)return{retryCommand:context.suggestedRetryCommand};if(isReadProjectionRecoveryFlag(optionName))return{};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,commandName);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,2 +1,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]="c70e67b1-fa46-518f-8630-b9e002c12936")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,PmCliError,readSettings,resolvePmRoot}from"../sdk/runtime-primitives.js";import{renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"../sdk/cli-contracts.js";import{collect,getGlobalOptions,printError,printResult,writeStdout}from"./registration-helpers.js";import{runExtension}from"./commands/extension/extension.js";import{SCAFFOLD_CAPABILITIES}from"./commands/extension/scaffold.js";import{renderExtensionDescribeMarkdown}from"./commands/extension/describe.js";import{runConfig}from"./commands/workspace/config.js";import{runInit,summarizeInitResult}from"./commands/workspace/init.js";import{runUpgrade}from"./commands/workspace/upgrade.js";import{inspectStaticExtensionInventory}from"../sdk/extension/static-inventory.js";const LIFECYCLE_DEPRECATION_ALIASES={extension:"extension",package:void 0};async function emitDeprecatedAliasHint(alias,command){if(!alias)return;const aliasContract=resolvePmCommandAlias(alias),globalOptions=getGlobalOptions(command);await readSettings(resolvePmRoot(process.cwd(),globalOptions.path)).then(settings=>settings.ux.deprecation_hints)&&printError(renderPmCommandAliasMigrationHint(aliasContract))}const EXTENSION_ACTION_OPTION_KEYS={init:"init",install:"install",uninstall:"uninstall",explore:"explore",manage:"manage",describe:"describe",reload:"reload",doctor:"doctor",catalog:"catalog",adopt:"adopt","adopt-all":"adoptAll",activate:"activate",deactivate:"deactivate",migrate:"migrate"};function resolveScaffoldCapability(options){const rawCapability=options.capability,values=typeof rawCapability=="string"?[rawCapability]:Array.isArray(rawCapability)?rawCapability.filter(entry=>typeof entry=="string"):[],capabilities=[...new Set(values.map(capability=>capability.trim().toLowerCase()).filter(capability=>capability.length>0))];if(capabilities.length>1)throw new PmCliError(`Multiple scaffold capabilities cannot be combined yet: ${capabilities.join(", ")}. Choose one capability per scaffold.`,EXIT_CODE.USAGE);return capabilities[0]}function normalizeExtensionOptions(options,forcedAction,vocabulary="extension"){const normalizedOptions={...options};forcedAction!==void 0&&(normalizedOptions[EXTENSION_ACTION_OPTION_KEYS[forcedAction]]=!0);const readBoolean=(...keys)=>keys.some(key=>normalizedOptions[key]===!0),readString=(...keys)=>{for(const key of keys)if(typeof normalizedOptions[key]=="string")return normalizedOptions[key]};return{init:readBoolean("init"),scaffold:readBoolean("scaffold"),install:readBoolean("install"),uninstall:readBoolean("uninstall"),explore:readBoolean("explore","list"),manage:readBoolean("manage"),describe:readBoolean("describe"),markdown:readBoolean("markdown"),reload:readBoolean("reload"),doctor:readBoolean("doctor"),catalog:readBoolean("catalog"),adopt:readBoolean("adopt"),adoptAll:readBoolean("adoptAll","adopt_all","adopt-all"),activate:readBoolean("activate"),deactivate:readBoolean("deactivate"),migrate:readBoolean("migrate"),project:readBoolean("project"),local:readBoolean("local"),global:readBoolean("global"),gh:readString("gh"),github:readString("github"),ref:readString("ref"),capability:resolveScaffoldCapability(options),declarative:readBoolean("declarative"),fields:readString("fields"),detail:readString("detail"),output:readString("output"),trace:readBoolean("trace"),watch:readBoolean("watch"),runtimeProbe:readBoolean("runtimeProbe","runtime_probe","runtime-probe"),offline:readBoolean("offline"),fixManagedState:readBoolean("fixManagedState","fix_managed_state","fix-managed-state"),isolated:readBoolean("isolated"),ignoreGlobal:readBoolean("ignoreGlobal","ignore_global","ignore-global"),strictExit:readBoolean("strictExit","strict_exit","strict-exit"),failOnWarn:readBoolean("failOnWarn","fail_on_warn","fail-on-warn"),dryRun:readBoolean("dryRun","dry_run","dry-run"),vocabulary}}async function looksLikeShellExpandedWildcard(targets){const visibleEntries=(await fs.readdir(process.cwd())).filter(entry=>!entry.startsWith(".")).sort((left,right)=>left.localeCompare(right)),normalizedTargets=[...targets].sort((left,right)=>left.localeCompare(right));return visibleEntries.length===normalizedTargets.length&&visibleEntries.every((entry,index)=>entry===normalizedTargets[index])}async function normalizeInstallTargets(targets){const normalizedTargets=(targets??[]).map(target=>target.trim()).filter(target=>target.length>0);return normalizedTargets.length<=1?normalizedTargets.length===0?void 0:normalizedTargets:await looksLikeShellExpandedWildcard(normalizedTargets)?["*"]:normalizedTargets}function validateExtensionMarkdownOptions(normalizedOptions,globalOptions,outputPath){const wantsMarkdown=normalizedOptions.markdown===!0;if(outputPath!==void 0&&outputPath==="")throw new PmCliError("--output requires a non-empty file path.",EXIT_CODE.USAGE);if(outputPath!==void 0&&!wantsMarkdown)throw new PmCliError("--output is only supported with --markdown describe output.",EXIT_CODE.USAGE);if(wantsMarkdown){if(globalOptions.json)throw new PmCliError("Cannot combine --json with --markdown.",EXIT_CODE.USAGE);if(normalizedOptions.describe!==!0)throw new PmCliError("--markdown is only supported by the describe action.",EXIT_CODE.USAGE)}}async function emitExtensionMarkdownResult(params){const markdown=renderExtensionDescribeMarkdown(params.result.details,params.vocabulary);if(params.outputPath!==void 0){const resolvedOutputPath=path.resolve(params.outputPath);await fs.mkdir(path.dirname(resolvedOutputPath),{recursive:!0}),await fs.writeFile(resolvedOutputPath,markdown,"utf8")}if(!params.globalOptions.quiet){for(const warning of params.result.warnings)printError(`warning: ${warning}`);params.outputPath===void 0&&writeStdout(markdown)}}function applyExtensionDoctorStrictExit(result,normalizedOptions){const strictExit=!!normalizedOptions.strictExit||!!normalizedOptions.failOnWarn;if(result.action!=="doctor"||!strictExit)return;const detailsRecord=result.details!==null&&typeof result.details=="object"?result.details:{},summary=detailsRecord.summary!==null&&typeof detailsRecord.summary=="object"?detailsRecord.summary:null,summaryStatus=summary&&typeof summary.status=="string"?summary.status:void 0;(result.warnings.length>0||summaryStatus!==void 0&&summaryStatus!=="ok")&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}async function executeExtensionCommand(target,options,command,forcedAction,vocabulary="extension"){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),effectiveVocabulary=vocabulary==="extension"?"package":vocabulary;await emitDeprecatedAliasHint(LIFECYCLE_DEPRECATION_ALIASES[vocabulary],command);const normalizedOptions=normalizeExtensionOptions(options,forcedAction,effectiveVocabulary),outputPath=(typeof normalizedOptions.output=="string"?normalizedOptions.output:void 0)?.trim();validateExtensionMarkdownOptions(normalizedOptions,globalOptions,outputPath);const result=await runExtension(target,normalizedOptions,globalOptions);normalizedOptions.markdown===!0?await emitExtensionMarkdownResult({result,vocabulary:effectiveVocabulary,outputPath,globalOptions}):printResult(result,globalOptions),applyExtensionDoctorStrictExit(result,normalizedOptions),result.ok===!1&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE),globalOptions.profile&&printError(`profile:command=extension took_ms=${Date.now()-startedAt}`)}function extractExtensionInstallDetails(result){return result.details!==null&&typeof result.details=="object"?result.details:{}}function serializeExtensionInstallError(error){return error instanceof PmCliError?{message:error.message,exit_code:error.exitCode,...error.context}:{message:error instanceof Error?error.message:String(error),exit_code:EXIT_CODE.GENERIC_FAILURE}}async function runMultiTargetExtensionInstalls(targets,options,globalOptions){const rows=[],warnings=[];let failureExitCode=EXIT_CODE.GENERIC_FAILURE;for(const target of targets)try{const result=await runExtension(target,options,globalOptions),details=extractExtensionInstallDetails(result),targetWarnings=Array.isArray(result.warnings)?result.warnings:[];warnings.push(...targetWarnings);const targetOk=result.ok===!0;rows.push({target,ok:targetOk,extension:details.extension,source:details.source,install_plan:details.install_plan,dry_run:details.dry_run,destination_path:details.destination_path,activated:details.activated,settings_changed:details.settings_changed,command_paths:details.command_paths,action_paths:details.action_paths,runtime_activation_status:details.runtime_activation_status,activation_diagnostics:details.activation_diagnostics,command_discovery:details.command_discovery,verification:details.verification,warnings:targetWarnings,...targetOk?{}:{error:{message:"Extension install returned ok=false without throwing an error.",exit_code:EXIT_CODE.GENERIC_FAILURE,code:"extension_install_soft_failed"}}})}catch(error){const serializedError=serializeExtensionInstallError(error),exitCode=serializedError.exit_code;typeof exitCode=="number"&&failureExitCode===EXIT_CODE.GENERIC_FAILURE&&exitCode!==EXIT_CODE.GENERIC_FAILURE&&(failureExitCode=exitCode),rows.push({target,ok:!1,error:serializedError})}return{rows,warnings,failureExitCode}}async function executeExtensionInstallCommand(targets,options,command,vocabulary){const effectiveVocabulary=vocabulary==="extension"?"package":vocabulary;await emitDeprecatedAliasHint(LIFECYCLE_DEPRECATION_ALIASES[vocabulary],command);const normalizedTargets=await normalizeInstallTargets(targets);if(normalizedTargets===void 0||normalizedTargets.length<=1){await executeExtensionCommand(normalizedTargets?.[0],options,command,"install",effectiveVocabulary);return}const globalOptions=getGlobalOptions(command),startedAt=Date.now(),normalizedOptions=normalizeExtensionOptions(options,"install",effectiveVocabulary);if(validateExtensionMarkdownOptions(normalizedOptions,globalOptions,void 0),[normalizedOptions.gh,normalizedOptions.github].some(value=>typeof value=="string"&&value.trim().length>0))throw new PmCliError("Multiple install targets cannot be combined with --gh/--github. Install one GitHub source per command, or pass multiple explicit local, bundled, or npm: targets.",EXIT_CODE.USAGE,{code:"multi_target_github_install_ambiguous",required:"Use exactly one positional target with --gh/--github, or omit --gh/--github when installing multiple targets.",examples:["pm package install --gh owner/repo","pm package install npm:pm-guide-shell pm-todos"]});const{rows,warnings,failureExitCode}=await runMultiTargetExtensionInstalls(normalizedTargets,normalizedOptions,globalOptions),failedCount=rows.filter(row=>row.ok!==!0).length,result={ok:failedCount===0,action:"install",scope:normalizedOptions.global===!0?"global":"project",installed_count:normalizedOptions.dryRun===!0?0:rows.length-failedCount,...normalizedOptions.dryRun===!0?{dry_run:!0,planned_count:rows.length-failedCount}:{},failed_count:failedCount,targets:rows,warnings:[...new Set(warnings)].sort((left,right)=>left.localeCompare(right))};printResult(result,globalOptions),failedCount>0&&(process.exitCode=failureExitCode),globalOptions.profile&&printError(`profile:command=extension took_ms=${Date.now()-startedAt}`)}function addExtensionScopeOptions(command){return command.option("--project","Use project extension scope (default)").option("--local","Alias for --project").option("--global","Use global extension scope")}function addPackageScopeOptions(command){return command.option("--project","Use project package scope (default)").option("--local","Alias for --project").option("--global","Use global package scope")}function addLifecycleScopeOptions(command,vocabulary){return vocabulary==="package"?addPackageScopeOptions(command):addExtensionScopeOptions(command)}function addUpgradeOptions(command){return command.option("--dry-run","Plan CLI/package upgrades without running npm or reinstalling packages").option("--cli-only","Upgrade only the pm CLI/SDK npm package").option("--packages-only","Upgrade only managed pm packages").option("--repair","Force npm global reinstall when upgrading the pm CLI/SDK").option("--tag <value>","npm dist-tag/version for CLI and registry package upgrades").option("--package-name <value>","Override the CLI package name for self-upgrade testing")}async function executeUpgradeCommand(target,command,legacyAlias){const globalOptions=getGlobalOptions(command),startedAt=Date.now();legacyAlias&&await emitDeprecatedAliasHint("upgrade",command);const result=await runUpgrade(target,command.optsWithGlobals(),globalOptions);printResult(result,globalOptions),result.ok||(process.exitCode=EXIT_CODE.GENERIC_FAILURE),globalOptions.profile&&printError(`profile:command=package-upgrade took_ms=${Date.now()-startedAt}`)}function registerLifecycleCommand(program,vocabulary){const noun=vocabulary==="package"?"package":"extension",plural=vocabulary==="package"?"packages":"extensions",commandName=vocabulary,lifecycleCommand=program.command(commandName,{hidden:vocabulary==="extension"}).argument("[target]",`${noun[0].toUpperCase()}${noun.slice(1)} source, name, or scaffold path`).option("--init",`Generate a starter ${noun} scaffold at target path`).option("--scaffold","Alias for --init").option("--capability <kind>","Starter capability for --init (default: commands)",collect).option("--install",`Install a ${noun} source`).option("--dry-run","Preview install without writes or activation").option("--uninstall",`Uninstall an installed ${noun}`).option("--explore",`List discovered ${plural} in selected scope`).option("--list","Alias for --explore").option("--manage",`List managed ${plural} and updates`).option("--offline","Skip remote freshness checks during manage").option("--describe",`Show surfaces registered by a loaded ${noun}`).option("--markdown","Render describe as Markdown").option("--output <path>","Write Markdown to a file").option("--reload",`Reload ${plural} without import cache`).option("--watch","Use watch mode with --reload").option("--doctor",`Run ${noun} diagnostics`).option("--catalog",`List bundled first-party ${noun} catalog metadata`).option("--adopt",`Adopt unmanaged ${noun}`).option("--adopt-all",`Adopt all unmanaged ${plural}`).option("--activate",`Activate a ${noun} in selected scope settings`).option("--deactivate",`Deactivate a ${noun} in selected scope settings`).option("--project",`Use project ${noun} scope (default)`).option("--local","Alias for --project").option("--global",`Use global ${noun} scope`).option("--gh <github-source>","Install from GitHub shorthand source (owner/repo[/path])").option("--github <github-source>","Alias for --gh").option("--ref <ref>","Git ref/branch/tag for GitHub install sources").option("--detail <mode>",`${noun[0].toUpperCase()}${noun.slice(1)} diagnostics detail mode (summary|deep)`).option("--trace","Include actionable registration traces in doctor deep diagnostics").option("--runtime-probe","Opt-in runtime activation probe for manage output parity").option("--fix-managed-state",`Adopt unmanaged ${plural} before diagnostics/update checks`).option("--isolated",`Run doctor against project-scope ${plural} only, ignoring global registrations`).option("--ignore-global","Alias for --isolated").option("--strict-exit","Return non-zero exit when doctor warnings are present (ok=false)").option("--fail-on-warn","Alias for --strict-exit (doctor)").description(vocabulary==="package"?"Manage package lifecycle in project or global scope.":"Manage extension lifecycle in project or global scope.").action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,void 0,vocabulary)});vocabulary==="package"&&(lifecycleCommand.alias("packages"),lifecycleCommand.option("--declarative","Scaffold the composeExtension blueprint starter (any capability)"));const initCommand=lifecycleCommand.command("init").alias("scaffold").argument("<target>","Scaffold target directory path").option("--capability <kind>",`Capability the starter targets (${SCAFFOLD_CAPABILITIES.join("|")}; default commands)`,collect).description(vocabulary==="package"?"Generate a starter package scaffold with package metadata, manifest, and entrypoint.":"Generate a starter extension scaffold with manifest and entrypoint.");vocabulary==="package"&&initCommand.option("--declarative","Scaffold the composeExtension blueprint starter (any capability)"),addLifecycleScopeOptions(initCommand,vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"init",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("install").option("--dry-run","Resolve sources and estimate copying without destination writes or activation").argument("[targets...]",`${noun[0].toUpperCase()}${noun.slice(1)} source (local path, bundled alias, npm: source, wildcard, or GitHub source)`).option("--gh <github-source>","Install from GitHub shorthand source (owner/repo[/path])").option("--github <github-source>","Alias for --gh").option("--ref <ref>","Git ref/branch/tag for GitHub install sources").description(`Install ${noun} from local path, bundled alias, npm: source, wildcard, or GitHub source.`),vocabulary).action(async(targets,_options,command)=>{await executeExtensionInstallCommand(targets,command.optsWithGlobals(),command,vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("uninstall").argument("<target>",`${noun[0].toUpperCase()}${noun.slice(1)} name`).description(`Uninstall an installed ${noun}.`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"uninstall",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("explore").description(`List discovered ${plural} in selected scope.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"explore",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("inventory").argument("[name]",`${noun[0].toUpperCase()}${noun.slice(1)} name or directory to inspect`).description(`Read configured ${noun} install and enablement state without activating extension code.`),vocabulary).action(async(name,_options,command)=>{const globalOptions=getGlobalOptions(command),options=command.optsWithGlobals();if(options.global===!0&&(options.project===!0||options.local===!0))throw new PmCliError("--global and --project/--local are mutually exclusive.",EXIT_CODE.USAGE);const result=await inspectStaticExtensionInventory({pmRoot:resolvePmRoot(process.cwd(),globalOptions.path),scope:options.global===!0?"global":"project",name});printResult(result,globalOptions),result.complete||(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}),addLifecycleScopeOptions(lifecycleCommand.command("manage").option("--offline","Skip remote freshness checks and report unknown update availability").option("--runtime-probe","Opt-in runtime activation probe for manage output parity").option("--fix-managed-state",`Adopt unmanaged ${plural} before diagnostics/update checks`).description(`List managed ${plural} with update-check metadata.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"manage",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("describe").argument("[target]",`${noun[0].toUpperCase()}${noun.slice(1)} name to describe (omit for every loaded ${noun})`).option("--markdown","Render the surface map as a Markdown reference document instead of toon/json").option("--output <path>","Write Markdown output to a file (requires --markdown)").description(`Map every surface a loaded ${noun} registers (commands, hooks, item types, providers, overrides, ...).`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"describe",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("reload").option("--watch","Use watch mode for repeated reload checks").description(`Reload ${plural} with cache-busted module imports.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"reload",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("doctor").option("--detail <mode>",`Detail mode for ${noun} diagnostics (summary|deep)`).option("--trace","Include actionable registration traces in doctor deep diagnostics").option("--fix-managed-state",`Adopt unmanaged ${plural} before diagnostics/update checks`).option("--isolated",`Run doctor against project-scope ${plural} only, ignoring global registrations`).option("--ignore-global","Alias for --isolated").option("--strict-exit","Return non-zero exit when doctor warnings are present (ok=false)").option("--fail-on-warn","Alias for --strict-exit (doctor)").description(`Run consolidated ${noun} diagnostics (summary/deep modes).`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"doctor",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("catalog").alias("list").option("--fields <value>","Render compact comma-separated catalog fields, for example: alias,installed,install_command").description(`List bundled first-party ${noun} catalog metadata.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"catalog",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("adopt").argument("<target>",`${noun[0].toUpperCase()}${noun.slice(1)} name`).option("--gh <owner/repo[/path]>",`GitHub provenance shorthand for adopted ${noun}`).option("--github <owner/repo[/path]>","Alias for --gh").option("--ref <ref>","Git ref/branch/tag for GitHub shorthand source").description(`Adopt an existing unmanaged ${noun} into managed metadata.`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"adopt",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("adopt-all").description(`Adopt all unmanaged ${plural} into managed metadata.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"adopt-all",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("migrate").option("--dry-run","Plan active migrations without invoking extension code").description(`Plan or apply active ${noun} migrations with durable receipts.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"migrate",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("activate").argument("<target>",`${noun[0].toUpperCase()}${noun.slice(1)} name`).description(`Activate a ${noun} in selected scope settings.`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"activate",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("deactivate").argument("<target>",`${noun[0].toUpperCase()}${noun.slice(1)} name`).description(`Deactivate a ${noun} in selected scope settings.`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"deactivate",vocabulary)}),vocabulary==="package"&&addUpgradeOptions(addPackageScopeOptions(lifecycleCommand.command("upgrade").argument("[target]","Optional managed package name/source to upgrade; omit to upgrade pm CLI and all managed packages").description("Upgrade the pm CLI/SDK and refresh managed installable pm packages."))).action(async(target,_options,command)=>{await executeUpgradeCommand(target,command,!1)})}async function runInitCommandAction(prefix,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runInit(prefix,globalOptions,{idPrefix:typeof options.idPrefix=="string"?options.idPrefix:void 0,preset:typeof options.preset=="string"?options.preset:void 0,defaults:options.defaults===!0||options.yes===!0,author:typeof options.author=="string"?options.author:void 0,agentGuidance:typeof options.agentGuidance=="string"?options.agentGuidance:void 0,typePreset:typeof options.typePreset=="string"?options.typePreset:void 0,withPackages:options.withPackages===!0,mergeFence:options.mergeFence!==!1,force:options.force===!0,workspace:typeof options.workspace=="string"?options.workspace:void 0}),emitFullTree=options.verbose===!0||globalOptions.json===!0;printResult(emitFullTree?result:summarizeInitResult(result,!0),globalOptions),globalOptions.profile&&printError(`profile:command=init took_ms=${Date.now()-startedAt}`)}function resolveConfigPositionals(scope,action,key,value){const scopeShorthand=scope!==void 0&&new Set(["get","set","list","export"]).has(scope);return{resolvedScope:scopeShorthand?"project":scope??"project",resolvedAction:scopeShorthand?scope:action??"list",resolvedKey:scopeShorthand?action:key,resolvedValue:scopeShorthand?key:value}}function buildConfigOptions(options){return{criterion:Array.isArray(options.criterion)?options.criterion:[],format:typeof options.format=="string"?options.format:void 0,policy:typeof options.policy=="string"?options.policy:void 0,value:typeof options.value=="string"?options.value:void 0,clearCriteria:options.clearCriteria===!0,defaultDepth:typeof options.defaultDepth=="string"?options.defaultDepth:void 0,activityLimit:typeof options.activityLimit=="string"?options.activityLimit:void 0,staleThresholdDays:typeof options.staleThresholdDays=="string"?options.staleThresholdDays:void 0,sectionHierarchy:typeof options.sectionHierarchy=="string"?options.sectionHierarchy:void 0,sectionActivity:typeof options.sectionActivity=="string"?options.sectionActivity:void 0,sectionProgress:typeof options.sectionProgress=="string"?options.sectionProgress:void 0,sectionBlockers:typeof options.sectionBlockers=="string"?options.sectionBlockers:void 0,sectionFiles:typeof options.sectionFiles=="string"?options.sectionFiles:void 0,sectionWorkload:typeof options.sectionWorkload=="string"?options.sectionWorkload:void 0,sectionStaleness:typeof options.sectionStaleness=="string"?options.sectionStaleness:void 0,sectionTests:typeof options.sectionTests=="string"?options.sectionTests:void 0}}async function runConfigCommandAction(scope,action,key,value,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),{resolvedScope,resolvedAction,resolvedKey,resolvedValue}=resolveConfigPositionals(scope,action,key,value),result=await runConfig(resolvedScope,resolvedAction,resolvedKey,buildConfigOptions(options),globalOptions,typeof resolvedValue=="string"?resolvedValue:void 0);printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=config took_ms=${Date.now()-startedAt}`)}const _testOnlyRegisterSetup={normalizeExtensionOptions};function registerSetupCommands(program){program.command("init").argument("[prefix-or-path]","Optional id prefix, or path-like tracker target such as ./pm-sandbox").option("--prefix, --id-prefix <value>","Set the item ID prefix (alias for the positional prefix)").option("--preset <value>","Governance preset for new setups: minimal|default|strict").option("--defaults","Use non-interactive setup defaults without opening the wizard").option("-y, --yes","Alias for --defaults (non-interactive setup)").option("--author <value>","Set the default mutation author for this project").option("--agent-guidance <mode>","Agent guidance mode: ask|add|skip|status").option("--type-preset <name>","Register domain item types during init: agile|ops|research").option("--with-packages","Install all bundled first-party packages during initialization").option("--no-merge-fence","Skip automatic merge-driver installation for a fresh Git-backed tracker").option("--workspace <dir>","Initialize repository-local tracker storage at <dir>/.agents/pm").option("--force","Allow initializing tracker files directly in a directory that looks like a workspace root").option("--verbose","Include the full resolved settings tree in the output (default output is a concise summary)").description("Initialize pm storage and defaults for the current workspace or a path-like tracker target.").action(async(prefix,options,command)=>{await runInitCommandAction(prefix,options,command)}),program.command("config").argument("[scope]","Config scope: project|global, or action shorthand list|export|get|set for project scope").argument("[action]","Config action: get|set|list|export").argument("[key]","Config key for get|set; use `pm config project list` for the complete typed inventory, including mutation-guard-* policies").argument("[value]",'Optional value for set: routed to the right typed flag by key (e.g. config set telemetry-tracking off, config set item-format toon, config set definition-of-done "Tests pass"). Equivalent to --policy/--format/--criterion. context keys still require --default-depth/--section-* flags.').option("--criterion <text>","Criteria value for definition-of-done, metadata-required-fields, or lifecycle pattern keys (repeatable for set)",collect).option("--clear-criteria","Clear criteria-list keys for config set operations").option("--format <value>","Item format for item-format key: toon").option("--policy <value>","Policy key values: history-missing-stream-policy=auto_create|strict_error; sprint-release-format-policy=warn|strict_error; parent-reference-policy=warn|strict_error; governance-preset=minimal|default|strict|custom; governance-ownership-enforcement=none|warn|strict; governance-create-mode-default=progressive|strict; governance-close-validation-default=off|warn|strict; governance-require-close-reason=enabled|disabled; governance-parent-reference-policy=warn|strict_error; governance-metadata-validation-profile=core|strict|custom; governance-force-required-for-stale-lock=enabled|disabled; governance-duplicate-detection-mode=off|advisory|strict; test-result-tracking=enabled|disabled; untrusted-linked-test-execution=enabled|disabled; telemetry-tracking=enabled|disabled").option("--value <value>","Typed nested setting value. Mutation guards: require-attributed-author=true|false, secret-guard=off|advise|block, stale-in-progress-hours=integer>=1. Kebab-case is preferred; underscore aliases remain accepted.").option("--default-depth <value>","Context default depth: brief|standard|deep").option("--activity-limit <n>","Context default activity limit").option("--stale-threshold-days <n>","Context staleness cutoff in days").option("--section-hierarchy <value>","Enable/disable context hierarchy section (true|false)").option("--section-activity <value>","Enable/disable context activity section (true|false)").option("--section-progress <value>","Enable/disable context progress section (true|false)").option("--section-blockers <value>","Enable/disable context blockers section (true|false)").option("--section-files <value>","Enable/disable context files section (true|false)").option("--section-workload <value>","Enable/disable context workload section (true|false)").option("--section-staleness <value>","Enable/disable context staleness section (true|false)").option("--section-tests <value>","Enable/disable context tests section (true|false)").description("Read or update pm settings for the current workspace or global profile.").action(async(scope,action,key,value,options,command)=>{await runConfigCommandAction(scope,action,key,value,options,command)}),registerLifecycleCommand(program,"extension"),registerLifecycleCommand(program,"package"),addPackageScopeOptions(program.command("install",{hidden:!0}).option("--dry-run","Resolve sources and estimate copying without destination writes or activation").argument("[targets...]","Package source (local path, bundled alias, npm: source, wildcard, or GitHub source)").option("--gh <github-source>","Install from GitHub shorthand source (owner/repo[/path])").option("--github <github-source>","Alias for --gh").option("--ref <ref>","Git ref/branch/tag for GitHub install sources").description("Install a pm package into the project package scope by default.")).action(async(targets,_options,command)=>{await emitDeprecatedAliasHint("install",command),await executeExtensionInstallCommand(targets,command.optsWithGlobals(),command,"package")}),addUpgradeOptions(addPackageScopeOptions(program.command("upgrade",{hidden:!0}).argument("[target]","Optional managed package name/source to upgrade; omit to upgrade pm CLI and all managed packages").description("Upgrade the pm CLI/SDK and refresh managed installable pm packages."))).action(async(target,_options,command)=>{await executeUpgradeCommand(target,command,!0)})}export{_testOnlyRegisterSetup,registerSetupCommands};
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]="d41d82cb-8b54-5b72-936e-217cde14c4b5")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,PmCliError,readSettings,resolvePmRoot}from"../sdk/runtime-primitives.js";import{renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"../sdk/cli-contracts.js";import{collect,getGlobalOptions,printError,printResult,writeStdout}from"./registration-helpers.js";import{runExtension}from"./commands/extension/extension.js";import{SCAFFOLD_CAPABILITIES}from"./commands/extension/scaffold.js";import{renderExtensionDescribeMarkdown}from"./commands/extension/describe.js";import{runConfig}from"./commands/workspace/config.js";import{runInit,summarizeInitResult}from"./commands/workspace/init.js";import{runUpgrade}from"./commands/workspace/upgrade.js";import{inspectStaticExtensionInventory}from"../sdk/extension/static-inventory.js";const LIFECYCLE_DEPRECATION_ALIASES={extension:"extension",package:void 0};async function emitDeprecatedAliasHint(alias,command){if(!alias)return;const aliasContract=resolvePmCommandAlias(alias),globalOptions=getGlobalOptions(command);await readSettings(resolvePmRoot(process.cwd(),globalOptions.path)).then(settings=>settings.ux.deprecation_hints)&&printError(renderPmCommandAliasMigrationHint(aliasContract))}const EXTENSION_ACTION_OPTION_KEYS={init:"init",install:"install",uninstall:"uninstall",explore:"explore",manage:"manage",describe:"describe",reload:"reload",doctor:"doctor",catalog:"catalog",adopt:"adopt","adopt-all":"adoptAll",activate:"activate",deactivate:"deactivate",migrate:"migrate"};function resolveScaffoldCapability(options){const rawCapability=options.capability,values=typeof rawCapability=="string"?[rawCapability]:Array.isArray(rawCapability)?rawCapability.filter(entry=>typeof entry=="string"):[],capabilities=[...new Set(values.map(capability=>capability.trim().toLowerCase()).filter(capability=>capability.length>0))];if(capabilities.length>1)throw new PmCliError(`Multiple scaffold capabilities cannot be combined yet: ${capabilities.join(", ")}. Choose one capability per scaffold.`,EXIT_CODE.USAGE);return capabilities[0]}function normalizeExtensionOptions(options,forcedAction,vocabulary="extension"){const normalizedOptions={...options};forcedAction!==void 0&&(normalizedOptions[EXTENSION_ACTION_OPTION_KEYS[forcedAction]]=!0);const readBoolean=(...keys)=>keys.some(key=>normalizedOptions[key]===!0),readString=(...keys)=>{for(const key of keys)if(typeof normalizedOptions[key]=="string")return normalizedOptions[key]};return{init:readBoolean("init"),scaffold:readBoolean("scaffold"),install:readBoolean("install"),uninstall:readBoolean("uninstall"),explore:readBoolean("explore","list"),manage:readBoolean("manage"),describe:readBoolean("describe"),markdown:readBoolean("markdown"),reload:readBoolean("reload"),doctor:readBoolean("doctor"),catalog:readBoolean("catalog"),adopt:readBoolean("adopt"),adoptAll:readBoolean("adoptAll","adopt_all","adopt-all"),activate:readBoolean("activate"),deactivate:readBoolean("deactivate"),migrate:readBoolean("migrate"),project:readBoolean("project"),local:readBoolean("local"),global:readBoolean("global"),gh:readString("gh"),github:readString("github"),ref:readString("ref"),capability:resolveScaffoldCapability(options),declarative:readBoolean("declarative"),fields:readString("fields"),detail:readString("detail"),output:readString("output"),trace:readBoolean("trace"),watch:readBoolean("watch"),runtimeProbe:readBoolean("runtimeProbe","runtime_probe","runtime-probe"),offline:readBoolean("offline"),fixManagedState:readBoolean("fixManagedState","fix_managed_state","fix-managed-state"),isolated:readBoolean("isolated"),ignoreGlobal:readBoolean("ignoreGlobal","ignore_global","ignore-global"),strictExit:readBoolean("strictExit","strict_exit","strict-exit"),failOnWarn:readBoolean("failOnWarn","fail_on_warn","fail-on-warn"),dryRun:readBoolean("dryRun","dry_run","dry-run"),vocabulary}}async function looksLikeShellExpandedWildcard(targets){const visibleEntries=(await fs.readdir(process.cwd())).filter(entry=>!entry.startsWith(".")).sort((left,right)=>left.localeCompare(right)),normalizedTargets=[...targets].sort((left,right)=>left.localeCompare(right));return visibleEntries.length===normalizedTargets.length&&visibleEntries.every((entry,index)=>entry===normalizedTargets[index])}async function normalizeInstallTargets(targets){const normalizedTargets=(targets??[]).map(target=>target.trim()).filter(target=>target.length>0);return normalizedTargets.length<=1?normalizedTargets.length===0?void 0:normalizedTargets:await looksLikeShellExpandedWildcard(normalizedTargets)?["*"]:normalizedTargets}function validateExtensionMarkdownOptions(normalizedOptions,globalOptions,outputPath){const wantsMarkdown=normalizedOptions.markdown===!0;if(outputPath!==void 0&&outputPath==="")throw new PmCliError("--output requires a non-empty file path.",EXIT_CODE.USAGE);if(outputPath!==void 0&&!wantsMarkdown)throw new PmCliError("--output is only supported with --markdown describe output.",EXIT_CODE.USAGE);if(wantsMarkdown){if(globalOptions.json)throw new PmCliError("Cannot combine --json with --markdown.",EXIT_CODE.USAGE);if(normalizedOptions.describe!==!0)throw new PmCliError("--markdown is only supported by the describe action.",EXIT_CODE.USAGE)}}async function emitExtensionMarkdownResult(params){const markdown=renderExtensionDescribeMarkdown(params.result.details,params.vocabulary);if(params.outputPath!==void 0){const resolvedOutputPath=path.resolve(params.outputPath);await fs.mkdir(path.dirname(resolvedOutputPath),{recursive:!0}),await fs.writeFile(resolvedOutputPath,markdown,"utf8")}if(!params.globalOptions.quiet){for(const warning of params.result.warnings)printError(`warning: ${warning}`);params.outputPath===void 0&&writeStdout(markdown)}}function applyExtensionDoctorStrictExit(result,normalizedOptions){const strictExit=!!normalizedOptions.strictExit||!!normalizedOptions.failOnWarn;if(result.action!=="doctor"||!strictExit)return;const detailsRecord=result.details!==null&&typeof result.details=="object"?result.details:{},summary=detailsRecord.summary!==null&&typeof detailsRecord.summary=="object"?detailsRecord.summary:null,summaryStatus=summary&&typeof summary.status=="string"?summary.status:void 0;(result.warnings.length>0||summaryStatus!==void 0&&summaryStatus!=="ok")&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}async function executeExtensionCommand(target,options,command,forcedAction,vocabulary="extension"){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),effectiveVocabulary=vocabulary==="extension"?"package":vocabulary;await emitDeprecatedAliasHint(LIFECYCLE_DEPRECATION_ALIASES[vocabulary],command);const normalizedOptions=normalizeExtensionOptions(options,forcedAction,effectiveVocabulary),outputPath=(typeof normalizedOptions.output=="string"?normalizedOptions.output:void 0)?.trim();validateExtensionMarkdownOptions(normalizedOptions,globalOptions,outputPath);const result=await runExtension(target,normalizedOptions,globalOptions);normalizedOptions.markdown===!0?await emitExtensionMarkdownResult({result,vocabulary:effectiveVocabulary,outputPath,globalOptions}):printResult(result,globalOptions),applyExtensionDoctorStrictExit(result,normalizedOptions),result.ok===!1&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE),globalOptions.profile&&printError(`profile:command=extension took_ms=${Date.now()-startedAt}`)}function extractExtensionInstallDetails(result){return result.details!==null&&typeof result.details=="object"?result.details:{}}function serializeExtensionInstallError(error){return error instanceof PmCliError?{message:error.message,exit_code:error.exitCode,...error.context}:{message:error instanceof Error?error.message:String(error),exit_code:EXIT_CODE.GENERIC_FAILURE}}async function runMultiTargetExtensionInstalls(targets,options,globalOptions){const rows=[],warnings=[];let failureExitCode=EXIT_CODE.GENERIC_FAILURE;for(const target of targets)try{const result=await runExtension(target,options,globalOptions),details=extractExtensionInstallDetails(result),targetWarnings=Array.isArray(result.warnings)?result.warnings:[];warnings.push(...targetWarnings);const targetOk=result.ok===!0;rows.push({target,ok:targetOk,extension:details.extension,source:details.source,install_plan:details.install_plan,dry_run:details.dry_run,destination_path:details.destination_path,activated:details.activated,settings_changed:details.settings_changed,previous_state_preserved:details.previous_state_preserved,rollback:details.rollback,command_paths:details.command_paths,action_paths:details.action_paths,runtime_activation_status:details.runtime_activation_status,activation_diagnostics:details.activation_diagnostics,command_discovery:details.command_discovery,verification:details.verification,warnings:targetWarnings,...targetOk?{}:{error:{message:"Extension install returned ok=false without throwing an error.",exit_code:EXIT_CODE.GENERIC_FAILURE,code:"extension_install_soft_failed"}}})}catch(error){const serializedError=serializeExtensionInstallError(error),exitCode=serializedError.exit_code;typeof exitCode=="number"&&failureExitCode===EXIT_CODE.GENERIC_FAILURE&&exitCode!==EXIT_CODE.GENERIC_FAILURE&&(failureExitCode=exitCode),rows.push({target,ok:!1,error:serializedError})}return{rows,warnings,failureExitCode}}async function executeExtensionInstallCommand(targets,options,command,vocabulary){const effectiveVocabulary=vocabulary==="extension"?"package":vocabulary;await emitDeprecatedAliasHint(LIFECYCLE_DEPRECATION_ALIASES[vocabulary],command);const normalizedTargets=await normalizeInstallTargets(targets);if(normalizedTargets===void 0||normalizedTargets.length<=1){await executeExtensionCommand(normalizedTargets?.[0],options,command,"install",effectiveVocabulary);return}const globalOptions=getGlobalOptions(command),startedAt=Date.now(),normalizedOptions=normalizeExtensionOptions(options,"install",effectiveVocabulary);if(validateExtensionMarkdownOptions(normalizedOptions,globalOptions,void 0),[normalizedOptions.gh,normalizedOptions.github].some(value=>typeof value=="string"&&value.trim().length>0))throw new PmCliError("Multiple install targets cannot be combined with --gh/--github. Install one GitHub source per command, or pass multiple explicit local, bundled, or npm: targets.",EXIT_CODE.USAGE,{code:"multi_target_github_install_ambiguous",required:"Use exactly one positional target with --gh/--github, or omit --gh/--github when installing multiple targets.",examples:["pm package install --gh owner/repo","pm package install npm:pm-guide-shell pm-todos"]});const{rows,warnings,failureExitCode}=await runMultiTargetExtensionInstalls(normalizedTargets,normalizedOptions,globalOptions),failedCount=rows.filter(row=>row.ok!==!0).length,result={ok:failedCount===0,action:"install",scope:normalizedOptions.global===!0?"global":"project",installed_count:normalizedOptions.dryRun===!0?0:rows.length-failedCount,...normalizedOptions.dryRun===!0?{dry_run:!0,planned_count:rows.length-failedCount}:{},failed_count:failedCount,targets:rows,warnings:[...new Set(warnings)].sort((left,right)=>left.localeCompare(right))};printResult(result,globalOptions),failedCount>0&&(process.exitCode=failureExitCode),globalOptions.profile&&printError(`profile:command=extension took_ms=${Date.now()-startedAt}`)}function addExtensionScopeOptions(command){return command.option("--project","Use project extension scope (default)").option("--local","Alias for --project").option("--global","Use global extension scope")}function addPackageScopeOptions(command){return command.option("--project","Use project package scope (default)").option("--local","Alias for --project").option("--global","Use global package scope")}function addLifecycleScopeOptions(command,vocabulary){return vocabulary==="package"?addPackageScopeOptions(command):addExtensionScopeOptions(command)}function addUpgradeOptions(command){return command.option("--dry-run","Plan CLI/package upgrades without running npm or reinstalling packages").option("--cli-only","Upgrade only the pm CLI/SDK npm package").option("--packages-only","Upgrade only managed pm packages").option("--repair","Force npm global reinstall when upgrading the pm CLI/SDK").option("--tag <value>","npm dist-tag/version for CLI and registry package upgrades").option("--package-name <value>","Override the CLI package name for self-upgrade testing")}async function executeUpgradeCommand(target,command,legacyAlias){const globalOptions=getGlobalOptions(command),startedAt=Date.now();legacyAlias&&await emitDeprecatedAliasHint("upgrade",command);const result=await runUpgrade(target,command.optsWithGlobals(),globalOptions);printResult(result,globalOptions),result.ok||(process.exitCode=EXIT_CODE.GENERIC_FAILURE),globalOptions.profile&&printError(`profile:command=package-upgrade took_ms=${Date.now()-startedAt}`)}function registerLifecycleCommand(program,vocabulary){const noun=vocabulary==="package"?"package":"extension",plural=vocabulary==="package"?"packages":"extensions",commandName=vocabulary,lifecycleCommand=program.command(commandName,{hidden:vocabulary==="extension"}).argument("[target]",`${noun[0].toUpperCase()}${noun.slice(1)} source, name, or scaffold path`).option("--init",`Generate a starter ${noun} scaffold at target path`).option("--scaffold","Alias for --init").option("--capability <kind>","Starter capability for --init (default: commands)",collect).option("--install",`Install a ${noun} source`).option("--dry-run","Preview install without writes or activation").option("--uninstall",`Uninstall an installed ${noun}`).option("--explore",`List discovered ${plural} in selected scope`).option("--list","Alias for --explore").option("--manage",`List managed ${plural} and updates`).option("--offline","Skip remote freshness checks during manage").option("--describe",`Show surfaces registered by a loaded ${noun}`).option("--markdown","Render describe as Markdown").option("--output <path>","Write Markdown to a file").option("--reload",`Reload ${plural} without import cache`).option("--watch","Use watch mode with --reload").option("--doctor",`Run ${noun} diagnostics`).option("--catalog",`List bundled first-party ${noun} catalog metadata`).option("--adopt",`Adopt unmanaged ${noun}`).option("--adopt-all",`Adopt all unmanaged ${plural}`).option("--activate",`Activate a ${noun} in selected scope settings`).option("--deactivate",`Deactivate a ${noun} in selected scope settings`).option("--project",`Use project ${noun} scope (default)`).option("--local","Alias for --project").option("--global",`Use global ${noun} scope`).option("--gh <github-source>","Install from GitHub shorthand source (owner/repo[/path])").option("--github <github-source>","Alias for --gh").option("--ref <ref>","Git ref/branch/tag for GitHub install sources").option("--detail <mode>",`${noun[0].toUpperCase()}${noun.slice(1)} diagnostics detail mode (summary|deep)`).option("--trace","Include actionable registration traces in doctor deep diagnostics").option("--runtime-probe","Opt-in runtime activation probe for manage output parity").option("--fix-managed-state",`Adopt unmanaged ${plural} before diagnostics/update checks`).option("--isolated",`Run doctor against project-scope ${plural} only, ignoring global registrations`).option("--ignore-global","Alias for --isolated").option("--strict-exit","Return non-zero exit when doctor warnings are present (ok=false)").option("--fail-on-warn","Alias for --strict-exit (doctor)").description(vocabulary==="package"?"Manage package lifecycle in project or global scope.":"Manage extension lifecycle in project or global scope.").action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,void 0,vocabulary)});vocabulary==="package"&&(lifecycleCommand.alias("packages"),lifecycleCommand.option("--declarative","Scaffold the composeExtension blueprint starter (any capability)"));const initCommand=lifecycleCommand.command("init").alias("scaffold").argument("<target>","Scaffold target directory path").option("--capability <kind>",`Capability the starter targets (${SCAFFOLD_CAPABILITIES.join("|")}; default commands)`,collect).description(vocabulary==="package"?"Generate a starter package scaffold with package metadata, manifest, and entrypoint.":"Generate a starter extension scaffold with manifest and entrypoint.");vocabulary==="package"&&initCommand.option("--declarative","Scaffold the composeExtension blueprint starter (any capability)"),addLifecycleScopeOptions(initCommand,vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"init",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("install").option("--dry-run","Resolve sources and estimate copying without destination writes or activation").argument("[targets...]",`${noun[0].toUpperCase()}${noun.slice(1)} source (local path, bundled alias, npm: source, wildcard, or GitHub source)`).option("--gh <github-source>","Install from GitHub shorthand source (owner/repo[/path])").option("--github <github-source>","Alias for --gh").option("--ref <ref>","Git ref/branch/tag for GitHub install sources").description(`Install ${noun} from local path, bundled alias, npm: source, wildcard, or GitHub source.`),vocabulary).action(async(targets,_options,command)=>{await executeExtensionInstallCommand(targets,command.optsWithGlobals(),command,vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("uninstall").argument("<target>",`${noun[0].toUpperCase()}${noun.slice(1)} name`).description(`Uninstall an installed ${noun}.`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"uninstall",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("explore").description(`List discovered ${plural} in selected scope.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"explore",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("inventory").argument("[name]",`${noun[0].toUpperCase()}${noun.slice(1)} name or directory to inspect`).description(`Read configured ${noun} install and enablement state without activating extension code.`),vocabulary).action(async(name,_options,command)=>{const globalOptions=getGlobalOptions(command),options=command.optsWithGlobals();if(options.global===!0&&(options.project===!0||options.local===!0))throw new PmCliError("--global and --project/--local are mutually exclusive.",EXIT_CODE.USAGE);const result=await inspectStaticExtensionInventory({pmRoot:resolvePmRoot(process.cwd(),globalOptions.path),scope:options.global===!0?"global":"project",name});printResult(result,globalOptions),result.complete||(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}),addLifecycleScopeOptions(lifecycleCommand.command("manage").option("--offline","Skip remote freshness checks and report unknown update availability").option("--runtime-probe","Opt-in runtime activation probe for manage output parity").option("--fix-managed-state",`Adopt unmanaged ${plural} before diagnostics/update checks`).description(`List managed ${plural} with update-check metadata.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"manage",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("describe").argument("[target]",`${noun[0].toUpperCase()}${noun.slice(1)} name to describe (omit for every loaded ${noun})`).option("--markdown","Render the surface map as a Markdown reference document instead of toon/json").option("--output <path>","Write Markdown output to a file (requires --markdown)").description(`Map every surface a loaded ${noun} registers (commands, hooks, item types, providers, overrides, ...).`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"describe",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("reload").option("--watch","Use watch mode for repeated reload checks").description(`Reload ${plural} with cache-busted module imports.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"reload",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("doctor").option("--detail <mode>",`Detail mode for ${noun} diagnostics (summary|deep)`).option("--trace","Include actionable registration traces in doctor deep diagnostics").option("--fix-managed-state",`Adopt unmanaged ${plural} before diagnostics/update checks`).option("--isolated",`Run doctor against project-scope ${plural} only, ignoring global registrations`).option("--ignore-global","Alias for --isolated").option("--strict-exit","Return non-zero exit when doctor warnings are present (ok=false)").option("--fail-on-warn","Alias for --strict-exit (doctor)").description(`Run consolidated ${noun} diagnostics (summary/deep modes).`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"doctor",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("catalog").alias("list").option("--fields <value>","Render compact comma-separated catalog fields, for example: alias,installed,install_command").description(`List bundled first-party ${noun} catalog metadata.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"catalog",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("adopt").argument("<target>",`${noun[0].toUpperCase()}${noun.slice(1)} name`).option("--gh <owner/repo[/path]>",`GitHub provenance shorthand for adopted ${noun}`).option("--github <owner/repo[/path]>","Alias for --gh").option("--ref <ref>","Git ref/branch/tag for GitHub shorthand source").description(`Adopt an existing unmanaged ${noun} into managed metadata.`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"adopt",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("adopt-all").description(`Adopt all unmanaged ${plural} into managed metadata.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"adopt-all",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("migrate").option("--dry-run","Plan active migrations without invoking extension code").description(`Plan or apply active ${noun} migrations with durable receipts.`),vocabulary).action(async(_options,command)=>{await executeExtensionCommand(void 0,command.optsWithGlobals(),command,"migrate",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("activate").argument("<target>",`${noun[0].toUpperCase()}${noun.slice(1)} name`).description(`Activate a ${noun} in selected scope settings.`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"activate",vocabulary)}),addLifecycleScopeOptions(lifecycleCommand.command("deactivate").argument("<target>",`${noun[0].toUpperCase()}${noun.slice(1)} name`).description(`Deactivate a ${noun} in selected scope settings.`),vocabulary).action(async(target,_options,command)=>{await executeExtensionCommand(target,command.optsWithGlobals(),command,"deactivate",vocabulary)}),vocabulary==="package"&&addUpgradeOptions(addPackageScopeOptions(lifecycleCommand.command("upgrade").argument("[target]","Optional managed package name/source to upgrade; omit to upgrade pm CLI and all managed packages").description("Upgrade the pm CLI/SDK and refresh managed installable pm packages."))).action(async(target,_options,command)=>{await executeUpgradeCommand(target,command,!1)})}async function runInitCommandAction(prefix,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runInit(prefix,globalOptions,{idPrefix:typeof options.idPrefix=="string"?options.idPrefix:void 0,preset:typeof options.preset=="string"?options.preset:void 0,defaults:options.defaults===!0||options.yes===!0,author:typeof options.author=="string"?options.author:void 0,agentGuidance:typeof options.agentGuidance=="string"?options.agentGuidance:void 0,typePreset:typeof options.typePreset=="string"?options.typePreset:void 0,withPackages:options.withPackages===!0,mergeFence:options.mergeFence!==!1,force:options.force===!0,workspace:typeof options.workspace=="string"?options.workspace:void 0}),emitFullTree=options.verbose===!0||globalOptions.json===!0;printResult(emitFullTree?result:summarizeInitResult(result,!0),globalOptions),globalOptions.profile&&printError(`profile:command=init took_ms=${Date.now()-startedAt}`)}function resolveConfigPositionals(scope,action,key,value){const scopeShorthand=scope!==void 0&&new Set(["get","set","list","export"]).has(scope);return{resolvedScope:scopeShorthand?"project":scope??"project",resolvedAction:scopeShorthand?scope:action??"list",resolvedKey:scopeShorthand?action:key,resolvedValue:scopeShorthand?key:value}}function buildConfigOptions(options){return{criterion:Array.isArray(options.criterion)?options.criterion:[],format:typeof options.format=="string"?options.format:void 0,policy:typeof options.policy=="string"?options.policy:void 0,value:typeof options.value=="string"?options.value:void 0,clearCriteria:options.clearCriteria===!0,defaultDepth:typeof options.defaultDepth=="string"?options.defaultDepth:void 0,activityLimit:typeof options.activityLimit=="string"?options.activityLimit:void 0,staleThresholdDays:typeof options.staleThresholdDays=="string"?options.staleThresholdDays:void 0,sectionHierarchy:typeof options.sectionHierarchy=="string"?options.sectionHierarchy:void 0,sectionActivity:typeof options.sectionActivity=="string"?options.sectionActivity:void 0,sectionProgress:typeof options.sectionProgress=="string"?options.sectionProgress:void 0,sectionBlockers:typeof options.sectionBlockers=="string"?options.sectionBlockers:void 0,sectionFiles:typeof options.sectionFiles=="string"?options.sectionFiles:void 0,sectionWorkload:typeof options.sectionWorkload=="string"?options.sectionWorkload:void 0,sectionStaleness:typeof options.sectionStaleness=="string"?options.sectionStaleness:void 0,sectionTests:typeof options.sectionTests=="string"?options.sectionTests:void 0}}async function runConfigCommandAction(scope,action,key,value,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),{resolvedScope,resolvedAction,resolvedKey,resolvedValue}=resolveConfigPositionals(scope,action,key,value),result=await runConfig(resolvedScope,resolvedAction,resolvedKey,buildConfigOptions(options),globalOptions,typeof resolvedValue=="string"?resolvedValue:void 0);printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=config took_ms=${Date.now()-startedAt}`)}const _testOnlyRegisterSetup={normalizeExtensionOptions};function registerSetupCommands(program){program.command("init").argument("[prefix-or-path]","Optional id prefix, or path-like tracker target such as ./pm-sandbox").option("--prefix, --id-prefix <value>","Set the item ID prefix (alias for the positional prefix)").option("--preset <value>","Governance preset for new setups: minimal|default|strict").option("--defaults","Use non-interactive setup defaults without opening the wizard").option("-y, --yes","Alias for --defaults (non-interactive setup)").option("--author <value>","Set the default mutation author for this project").option("--agent-guidance <mode>","Agent guidance mode: ask|add|skip|status").option("--type-preset <name>","Register domain item types during init: agile|ops|research").option("--with-packages","Install all bundled first-party packages during initialization").option("--no-merge-fence","Skip automatic merge-driver installation for a fresh Git-backed tracker").option("--workspace <dir>","Initialize repository-local tracker storage at <dir>/.agents/pm").option("--force","Allow initializing tracker files directly in a directory that looks like a workspace root").option("--verbose","Include the full resolved settings tree in the output (default output is a concise summary)").description("Initialize pm storage and defaults for the current workspace or a path-like tracker target.").action(async(prefix,options,command)=>{await runInitCommandAction(prefix,options,command)}),program.command("config").argument("[scope]","Config scope: project|global, or action shorthand list|export|get|set for project scope").argument("[action]","Config action: get|set|list|export").argument("[key]","Config key for get|set; use `pm config project list` for the complete typed inventory, including mutation-guard-* policies").argument("[value]",'Optional value for set: routed to the right typed flag by key (e.g. config set telemetry-tracking off, config set item-format toon, config set definition-of-done "Tests pass"). Equivalent to --policy/--format/--criterion. context keys still require --default-depth/--section-* flags.').option("--criterion <text>","Criteria value for definition-of-done, metadata-required-fields, or lifecycle pattern keys (repeatable for set)",collect).option("--clear-criteria","Clear criteria-list keys for config set operations").option("--format <value>","Item format for item-format key: toon").option("--policy <value>","Policy key values: history-missing-stream-policy=auto_create|strict_error; sprint-release-format-policy=warn|strict_error; parent-reference-policy=warn|strict_error; governance-preset=minimal|default|strict|custom; governance-ownership-enforcement=none|warn|strict; governance-create-mode-default=progressive|strict; governance-close-validation-default=off|warn|strict; governance-require-close-reason=enabled|disabled; governance-parent-reference-policy=warn|strict_error; governance-metadata-validation-profile=core|strict|custom; governance-force-required-for-stale-lock=enabled|disabled; governance-duplicate-detection-mode=off|advisory|strict; test-result-tracking=enabled|disabled; untrusted-linked-test-execution=enabled|disabled; telemetry-tracking=enabled|disabled").option("--value <value>","Typed nested setting value. Mutation guards: require-attributed-author=true|false, secret-guard=off|advise|block, stale-in-progress-hours=integer>=1. Kebab-case is preferred; underscore aliases remain accepted.").option("--default-depth <value>","Context default depth: brief|standard|deep").option("--activity-limit <n>","Context default activity limit").option("--stale-threshold-days <n>","Context staleness cutoff in days").option("--section-hierarchy <value>","Enable/disable context hierarchy section (true|false)").option("--section-activity <value>","Enable/disable context activity section (true|false)").option("--section-progress <value>","Enable/disable context progress section (true|false)").option("--section-blockers <value>","Enable/disable context blockers section (true|false)").option("--section-files <value>","Enable/disable context files section (true|false)").option("--section-workload <value>","Enable/disable context workload section (true|false)").option("--section-staleness <value>","Enable/disable context staleness section (true|false)").option("--section-tests <value>","Enable/disable context tests section (true|false)").description("Read or update pm settings for the current workspace or global profile.").action(async(scope,action,key,value,options,command)=>{await runConfigCommandAction(scope,action,key,value,options,command)}),registerLifecycleCommand(program,"extension"),registerLifecycleCommand(program,"package"),addPackageScopeOptions(program.command("install",{hidden:!0}).option("--dry-run","Resolve sources and estimate copying without destination writes or activation").argument("[targets...]","Package source (local path, bundled alias, npm: source, wildcard, or GitHub source)").option("--gh <github-source>","Install from GitHub shorthand source (owner/repo[/path])").option("--github <github-source>","Alias for --gh").option("--ref <ref>","Git ref/branch/tag for GitHub install sources").description("Install a pm package into the project package scope by default.")).action(async(targets,_options,command)=>{await emitDeprecatedAliasHint("install",command),await executeExtensionInstallCommand(targets,command.optsWithGlobals(),command,"package")}),addUpgradeOptions(addPackageScopeOptions(program.command("upgrade",{hidden:!0}).argument("[target]","Optional managed package name/source to upgrade; omit to upgrade pm CLI and all managed packages").description("Upgrade the pm CLI/SDK and refresh managed installable pm packages."))).action(async(target,_options,command)=>{await executeUpgradeCommand(target,command,!0)})}export{_testOnlyRegisterSetup,registerSetupCommands};
2
2
  //# sourceMappingURL=register-setup.js.map