@unbrained/pm-cli 2026.10.30 → 2026.10.31

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 (235) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/dist/cli/commander-usage.js +2 -2
  4. package/dist/cli/error-guidance.d.ts +45 -5
  5. package/dist/cli/error-guidance.js +5 -3
  6. package/dist/cli/extension-command-help.d.ts +1 -0
  7. package/dist/cli/extension-command-help.js +2 -2
  8. package/dist/cli/main.d.ts +1 -5
  9. package/dist/cli/main.js +5 -5
  10. package/dist/cli/migration-gates.d.ts +1 -1
  11. package/dist/cli/migration-gates.js +1 -1
  12. package/dist/cli/preflight-warnings.d.ts +11 -0
  13. package/dist/cli/preflight-warnings.js +4 -0
  14. package/dist/cli/register-mutation.js +2 -2
  15. package/dist/cli-bundle/bundle-manifest.json +1 -1
  16. package/dist/cli-bundle/chunks/chunk-24J6TNYE.js +8 -0
  17. package/dist/cli-bundle/chunks/{chunk-EHBGHX55.js → chunk-2AHSPMKJ.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-MVL27TAH.js → chunk-35Q2B2GJ.js} +2 -2
  19. package/dist/cli-bundle/chunks/chunk-43R7UTWV.js +2 -0
  20. package/dist/cli-bundle/chunks/chunk-6PSDQ7T7.js +8 -0
  21. package/dist/cli-bundle/chunks/{chunk-UUQX3PFD.js → chunk-BS2KXT24.js} +70 -70
  22. package/dist/cli-bundle/chunks/{chunk-Y6NC3X3E.js → chunk-GMBDZID5.js} +3 -3
  23. package/dist/cli-bundle/chunks/chunk-HSBTITO4.js +3 -0
  24. package/dist/cli-bundle/chunks/{chunk-LWW4F4G2.js → chunk-MRUA2Z43.js} +2 -2
  25. package/dist/cli-bundle/chunks/chunk-P3LNMWL2.js +2 -0
  26. package/dist/cli-bundle/chunks/{chunk-S2U7ECUJ.js → chunk-PT7TS6E7.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-TH5KPAN4.js → chunk-SBVX5CMV.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-4BQD5SW2.js → chunk-TL3O5GZA.js} +30 -30
  29. package/dist/cli-bundle/chunks/chunk-U7JXZMU5.js +6 -0
  30. package/dist/cli-bundle/chunks/{chunk-GRABKNFL.js → chunk-V6EWBTNH.js} +2 -2
  31. package/dist/cli-bundle/chunks/chunk-VC7TA67O.js +20 -0
  32. package/dist/cli-bundle/chunks/chunk-WNF6FOL7.js +31 -0
  33. package/dist/cli-bundle/chunks/chunk-WRXQAW7Q.js +114 -0
  34. package/dist/cli-bundle/chunks/{chunk-RZQNFHXO.js → chunk-WX25MU4N.js} +3 -3
  35. package/dist/cli-bundle/chunks/chunk-XDDPSWIW.js +2 -0
  36. package/dist/cli-bundle/chunks/chunk-YT5D5HNG.js +2 -0
  37. package/dist/cli-bundle/chunks/chunk-ZTJVOBDU.js +128 -0
  38. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-LHLE7PSG.js → indexed-receipt-blobs-KGMJVFH2.js} +2 -2
  39. package/dist/cli-bundle/chunks/item-transaction-UWV6UNSV.js +2 -0
  40. package/dist/cli-bundle/chunks/{mutation-admission-TRGAVS7N.js → mutation-admission-I4RHIT3Q.js} +2 -2
  41. package/dist/cli-bundle/chunks/{register-list-query-BH4F6M7Z.js → register-list-query-MVDL5EXG.js} +3 -3
  42. package/dist/cli-bundle/chunks/register-mutation-GAF7LXRB.js +20 -0
  43. package/dist/cli-bundle/chunks/register-operations-JLFRL36Q.js +2 -0
  44. package/dist/cli-bundle/chunks/{register-setup-QPWSVHFZ.js → register-setup-MZN6ONB3.js} +2 -2
  45. package/dist/cli-bundle/chunks/{settlement-hook-MN3Y7LVX.js → settlement-hook-YWSWFOZY.js} +2 -2
  46. package/dist/cli-bundle/chunks/{stage-RTB6RAAO.js → stage-2ZORTOF6.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-S23ZUASN.js → chunk-2J7T2UCH.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/chunk-4QPGJO2G.js +26 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-YU7QOYYV.js → chunk-57HPXGOQ.js} +3 -3
  50. package/dist/cli-bundle/focused-chunks/chunk-5MCGYBOQ.js +91 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-6F6APBCX.js +3 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-AFVN2KCP.js +44 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-RKPUQDWF.js → chunk-DFUTCKUF.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-EA65HVBO.js +12 -0
  55. package/dist/cli-bundle/focused-chunks/chunk-GP2WU43K.js +26 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-YQUZL2CK.js → chunk-HPWT3RBG.js} +3 -3
  57. package/dist/cli-bundle/focused-chunks/chunk-HSAEEWSI.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/{chunk-BPE6JTKL.js → chunk-JLXGRDTG.js} +3 -3
  59. package/dist/cli-bundle/focused-chunks/{chunk-FRFNGMAK.js → chunk-JNKRUCVZ.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-BCIUAEWX.js → chunk-KH5QJXY7.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/chunk-KKRIFBSL.js +2 -0
  62. package/dist/cli-bundle/focused-chunks/{chunk-RGQEJFXO.js → chunk-MW77Q3AQ.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/chunk-NOKG4RFN.js +22 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-POJPJX64.js → chunk-NRBUMDLF.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-3SRX77ES.js → chunk-PC3R5CJV.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/{chunk-RYEZSZJ7.js → chunk-PFBQOZPK.js} +2 -2
  67. package/dist/cli-bundle/focused-chunks/{chunk-SAT7IAEB.js → chunk-QFMJGQGO.js} +3 -3
  68. package/dist/cli-bundle/focused-chunks/{chunk-VFWCSQAG.js → chunk-SFQKCA5K.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-WHIE2C6Q.js +2 -0
  70. package/dist/cli-bundle/focused-chunks/chunk-Y6UYRMVG.js +6 -0
  71. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-VK2363JB.js → indexed-receipt-blobs-KHWT44EK.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/item-transaction-LU75EG7D.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/{mutation-admission-7VUODEPJ.js → mutation-admission-KDJ7SCPA.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{settlement-hook-OK6A7PG2.js → settlement-hook-SJV52ZTV.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/{stage-S5RP5SZH.js → stage-R4KEBO37.js} +2 -2
  76. package/dist/cli-bundle/main.js +26 -22
  77. package/dist/cli-bundle/sdk-authoring.js +1 -1
  78. package/dist/cli-bundle/sdk-contracts.js +4 -4
  79. package/dist/cli-bundle/sdk-core.js +1 -1
  80. package/dist/cli-bundle/sdk-governance.js +1 -1
  81. package/dist/cli-bundle/sdk-graph.js +1 -1
  82. package/dist/cli-bundle/sdk-merge.js +57 -57
  83. package/dist/cli-bundle/sdk-query.js +1 -1
  84. package/dist/cli-bundle/sdk-runtime.js +1 -1
  85. package/dist/cli-bundle/sdk-testing.js +1 -1
  86. package/dist/cli-bundle/sdk.js +11 -11
  87. package/dist/core/config/nested-settings.js +1 -1
  88. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  89. package/dist/core/extensions/extension-types.d.ts +4 -0
  90. package/dist/core/extensions/extension-types.js +1 -1
  91. package/dist/core/extensions/loader.js +1 -1
  92. package/dist/core/lock/lock.js +4 -4
  93. package/dist/core/output/output.js +2 -2
  94. package/dist/core/schema/fields-file.js +1 -1
  95. package/dist/core/sentry/helpers.d.ts +6 -0
  96. package/dist/core/sentry/helpers.js +1 -1
  97. package/dist/core/sentry/instrument.d.ts +1 -1
  98. package/dist/core/sentry/instrument.js +1 -1
  99. package/dist/core/shared/constants.js +1 -1
  100. package/dist/core/shared/errors.d.ts +6 -0
  101. package/dist/core/shared/errors.js +1 -1
  102. package/dist/core/shared/output-unicode.d.ts +10 -0
  103. package/dist/core/shared/output-unicode.js +2 -0
  104. package/dist/core/store/settings-validator.d.ts +1 -0
  105. package/dist/core/store/settings-validator.js +1 -1
  106. package/dist/core/store/settings.js +1 -1
  107. package/dist/core/telemetry/policy.d.ts +8 -0
  108. package/dist/core/telemetry/policy.js +1 -1
  109. package/dist/core/telemetry/runtime.js +3 -3
  110. package/dist/sdk/agent/command-recovery.d.ts +15 -0
  111. package/dist/sdk/agent/command-recovery.js +1 -1
  112. package/dist/sdk/cli-bootstrap.js +1 -1
  113. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +28 -0
  114. package/dist/sdk/cli-contracts/agent-output-contracts.js +2 -2
  115. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  116. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  117. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  118. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  119. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  120. package/dist/sdk/cli-contracts.d.ts +1 -1
  121. package/dist/sdk/cli-contracts.js +1 -1
  122. package/dist/sdk/completion/fish.js +4 -4
  123. package/dist/sdk/completion/zsh.js +3 -3
  124. package/dist/sdk/config.d.ts +1 -0
  125. package/dist/sdk/config.js +1 -1
  126. package/dist/sdk/core.d.ts +1 -0
  127. package/dist/sdk/core.js +1 -1
  128. package/dist/sdk/error-runtime.d.ts +9 -0
  129. package/dist/sdk/error-runtime.js +1 -1
  130. package/dist/sdk/errors.js +1 -1
  131. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  132. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  133. package/dist/sdk/index.d.ts +2 -2
  134. package/dist/sdk/index.js +1 -1
  135. package/dist/sdk/lifecycle/claim.js +1 -1
  136. package/dist/sdk/lifecycle/close.js +1 -1
  137. package/dist/sdk/lifecycle/create.js +1 -1
  138. package/dist/sdk/lifecycle/plan.d.ts +2 -3
  139. package/dist/sdk/lifecycle/plan.js +1 -1
  140. package/dist/sdk/lifecycle/repeated-terminal-state.d.ts +45 -0
  141. package/dist/sdk/lifecycle/repeated-terminal-state.js +2 -0
  142. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +9 -0
  143. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  144. package/dist/sdk/lifecycle/update-many.d.ts +0 -1
  145. package/dist/sdk/lifecycle/update-many.js +1 -1
  146. package/dist/sdk/lifecycle/update.d.ts +29 -1
  147. package/dist/sdk/lifecycle/update.js +2 -2
  148. package/dist/sdk/output/table-rows.d.ts +7 -1
  149. package/dist/sdk/output/table-rows.js +1 -1
  150. package/dist/sdk/output.d.ts +1 -0
  151. package/dist/sdk/output.js +2 -2
  152. package/dist/sdk/ownership-source.d.ts +18 -0
  153. package/dist/sdk/ownership-source.js +1 -1
  154. package/dist/sdk/public-surface.json +1 -1
  155. package/dist/sdk/query/get.d.ts +1 -1
  156. package/dist/sdk/query/get.js +1 -1
  157. package/dist/sdk/query/next-ranking-policy.d.ts +35 -0
  158. package/dist/sdk/query/next-ranking-policy.js +2 -0
  159. package/dist/sdk/query/next.d.ts +12 -2
  160. package/dist/sdk/query/next.js +2 -2
  161. package/dist/sdk/query/projection-contracts.d.ts +4 -0
  162. package/dist/sdk/query/projection-contracts.js +1 -1
  163. package/dist/sdk/read-output/surfaces.d.ts +27 -0
  164. package/dist/sdk/read-output/surfaces.js +2 -0
  165. package/dist/sdk/read-output-contracts.js +1 -1
  166. package/dist/sdk/runtime-primitives.d.ts +1 -0
  167. package/dist/sdk/runtime-primitives.js +1 -1
  168. package/dist/sdk/runtime.js +1 -1
  169. package/dist/sdk/test/execution-receipts.d.ts +25 -0
  170. package/dist/sdk/test/execution-receipts.js +2 -2
  171. package/dist/sdk/test/execution.d.ts +5 -0
  172. package/dist/sdk/test/execution.js +2 -2
  173. package/dist/types.d.ts +2 -0
  174. package/dist/types.js +1 -1
  175. package/docs/AGENT_GUIDE.md +1 -1
  176. package/docs/AGENT_OUTPUT_ENCODINGS.md +12 -0
  177. package/docs/AGENT_UX_CONTRACTS.md +2 -1
  178. package/docs/COMMANDS.md +58 -5
  179. package/docs/CONFIGURATION.md +48 -1
  180. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -0
  181. package/docs/PACKED_FIRST_RUN.md +2 -1
  182. package/docs/READ_OUTPUT_CONTRACTS.md +24 -6
  183. package/docs/SDK.md +73 -2
  184. package/docs/TESTING.md +38 -2
  185. package/docs/agent-task-token-baseline.json +1 -1
  186. package/marketplace.json +1 -1
  187. package/package.json +1 -1
  188. package/packages/pm-beads/package.json +1 -1
  189. package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
  190. package/packages/pm-calendar/package.json +1 -1
  191. package/packages/pm-command-kit/package.json +1 -1
  192. package/packages/pm-digital-twin/package.json +1 -1
  193. package/packages/pm-governance-audit/package.json +1 -1
  194. package/packages/pm-guide-shell/package.json +1 -1
  195. package/packages/pm-kanban/package.json +1 -1
  196. package/packages/pm-lifecycle-hooks/package.json +1 -1
  197. package/packages/pm-linked-test-adapters/package.json +1 -1
  198. package/packages/pm-search-advanced/package.json +1 -1
  199. package/packages/pm-templates/package.json +1 -1
  200. package/packages/pm-todos/package.json +1 -1
  201. package/packages/pm-vcs/package.json +1 -1
  202. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  203. package/plugins/pm-claude/package.json +1 -1
  204. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  205. package/plugins/pm-codex/package.json +1 -1
  206. package/plugins/pm-codex/plugin.json +1 -1
  207. package/runtime-dependencies.json +1 -1
  208. package/dist/cli-bundle/chunks/chunk-34MP7WKK.js +0 -6
  209. package/dist/cli-bundle/chunks/chunk-3KMYHYJV.js +0 -2
  210. package/dist/cli-bundle/chunks/chunk-42BHHNTL.js +0 -128
  211. package/dist/cli-bundle/chunks/chunk-I5O3XZOA.js +0 -2
  212. package/dist/cli-bundle/chunks/chunk-LEIVUGDH.js +0 -8
  213. package/dist/cli-bundle/chunks/chunk-OH7WPD42.js +0 -114
  214. package/dist/cli-bundle/chunks/chunk-OOD2A7AF.js +0 -20
  215. package/dist/cli-bundle/chunks/chunk-Q5V7P6NM.js +0 -2
  216. package/dist/cli-bundle/chunks/chunk-QLPFYBXN.js +0 -2
  217. package/dist/cli-bundle/chunks/chunk-SA5NYLPE.js +0 -8
  218. package/dist/cli-bundle/chunks/chunk-VHLAVTJN.js +0 -31
  219. package/dist/cli-bundle/chunks/chunk-XAOVJG52.js +0 -3
  220. package/dist/cli-bundle/chunks/chunk-XPQ4RTSF.js +0 -2
  221. package/dist/cli-bundle/chunks/item-transaction-WIOBZW4E.js +0 -2
  222. package/dist/cli-bundle/chunks/register-mutation-5V2NANIS.js +0 -20
  223. package/dist/cli-bundle/chunks/register-operations-XSFRMUFX.js +0 -2
  224. package/dist/cli-bundle/focused-chunks/chunk-2V6NMNYN.js +0 -26
  225. package/dist/cli-bundle/focused-chunks/chunk-ASHGXMX4.js +0 -3
  226. package/dist/cli-bundle/focused-chunks/chunk-CKBN2D42.js +0 -12
  227. package/dist/cli-bundle/focused-chunks/chunk-I642DXOT.js +0 -22
  228. package/dist/cli-bundle/focused-chunks/chunk-K7DKG5HM.js +0 -91
  229. package/dist/cli-bundle/focused-chunks/chunk-NMQBXU7N.js +0 -44
  230. package/dist/cli-bundle/focused-chunks/chunk-PGM3ENGZ.js +0 -2
  231. package/dist/cli-bundle/focused-chunks/chunk-QFNV4JTA.js +0 -6
  232. package/dist/cli-bundle/focused-chunks/chunk-QVJCQMZY.js +0 -26
  233. package/dist/cli-bundle/focused-chunks/chunk-R2TPPPVU.js +0 -2
  234. package/dist/cli-bundle/focused-chunks/chunk-VJVJ2ZX2.js +0 -2
  235. package/dist/cli-bundle/focused-chunks/item-transaction-ZFDKJIP7.js +0 -2
@@ -1 +1 @@
1
- {"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.10.30","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.30","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.31","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.31","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,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026.10.31 - 2026-10-31
4
+
5
+ ### Changed
6
+
7
+ - Update Sentry CLI to 3.8.2 after seven-day cooldown ([pm-sentry-cli-382](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-sentry-cli-382.toon))
8
+
9
+ ### Fixed
10
+
11
+ - Successful linked-test receipts carry non-actionable execution_context and all-zero failure_categories, even under --lean ([pm-covpax](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-covpax.toon))
12
+ - Unknown-option recovery drops a dash-leading prose value: the advertised replay closes, comments or creates without the user's text ([pm-stq61b](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-stq61b.toon))
13
+ - GH-1633: accept comma-separated --unset field lists with per-field validation ([pm-gh1633](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1633.toon))
14
+ - GH-1630: bound selective linked-test receipts to the selected collection ([pm-gh1630](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1630.toon))
15
+ - GH-1626: offer same-command replay corrections for brief completeness spellings ([pm-gh1626](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1626.toon))
16
+ - GH-1609: recover killed commit owners and bound lock waits with a monotonic clock ([pm-gh1609](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1609.toon))
17
+ - GH-1624: define typed Unicode handling for extension output across JSON and TOON ([pm-gh1624](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1624.toon))
18
+ - GH-1625: align extension-refusal Sentry capture with declared contracts and telemetry source context ([pm-gh1625](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1625.toon))
19
+ - GH-1602: keep preflight warnings inside JSON error envelopes ([pm-gh1602](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1602.toon))
20
+ - Bound independent native receipt regression cases ([pm-native-index-proof](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-native-index-proof.toon))
21
+ - GH-1558: Settle Windows generation-fixture rename rejections without weakening lock assertions ([pm-gh1558](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1558.toon))
22
+ - pm close clears the assignee but leaves claim_principal, so closed claimed items keep an active owner ([pm-8xgg7i](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8xgg7i.toon))
23
+ - GH-1618: prevent automated comment churn from misleading next-work priority ([pm-gh1618](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1618.toon))
24
+ - GH-1610: compact lean refusals and expose structured claim context ([pm-gh1610](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1610.toon))
25
+ - GH-1627: bound the entire next response and compact optional TOON sections losslessly ([pm-gh1627](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1627.toon))
26
+ - GH-1628: preserve terminal timestamps for identical forced SDK updates ([pm-gh1628](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1628.toon))
27
+ - Pull-request CI requests 33 hosted-runner jobs per push against the account's 20-job concurrency cap, so required checks wait hours before they start ([pm-m6ig79](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-m6ig79.toon))
28
+ - Text refusals drop the specific What happened detail when an echoed argv overflows the diagnostic ceiling ([pm-4oc353](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-4oc353.toon))
29
+ - GH-1622: investigate pm-presets SDK-loading fault blocking daily release ([pm-gh1622](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1622.toon))
30
+
31
+ ### Security
32
+
33
+ - Registry advisories GHSA-mrwp-f3q8-3g9p (follow-redirects 1.16.1, high) and GHSA-g3hv-75wg-m249 (minimatch 10.2.6, moderate) block the static gate on main and every PR ([pm-irviv0](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-irviv0.toon))
34
+
3
35
  ## 2026.10.30 - 2026-10-30
4
36
 
5
37
  ### Added
@@ -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]="f07b9b70-b22d-5a5b-aec4-e1011286fb77")}catch{}})();import{pathExists,resolveItemTypeRegistry,EXIT_CODE,getSettingsPath,resolvePmRoot,readSettings,getActiveExtensionRegistrations,locateItem,runActiveServiceOverride,levenshteinDistanceWithinLimit}from"../sdk/runtime-primitives.js";import{BUILTIN_ITEM_TYPE_VALUES}from"../types/index.js";import{PM_CORE_COMMAND_NAMES,resolveSubcommandFlagContractsForCommand}from"../sdk/cli-contracts.js";import{formatCommanderErrorForDisplay,formatCommanderErrorForJson,projectLeanErrorEnvelope}from"./error-guidance.js";import{normalizeHelpCommandPath}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{EXECUTABLE_COMMAND_ALIASES,findBootstrapCommandTokenIndex,normalizeBootstrapInvocation,parseBootstrapHelpRequest,parseBootstrapGlobalOptions,parseBootstrapCommandName}from"./bootstrap-args.js";import{extractProvidedOptionFlags,normalizeLongFlag,renderPmCommand}from"./argv-utils.js";import{normalizeExtensionNameForMatch}from"./commands/extension/shared.js";import{canonicalizeCommandSuggestions,rankCommandPaths,resolveMisnestedCommandPath}from"../sdk/agent/command-suggestions.js";import{isCompatibleRecoveryFlag,renderMissingOptionRetry,resolveLifecycleVerbRecovery}from"../sdk/agent/command-recovery.js";import{resolvePmCommandScopeArgs}from"../sdk/command-line.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{findPmNamespacedCommand,resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";const BUILTIN_TYPE_HELP_VALUES=BUILTIN_ITEM_TYPE_VALUES.join("|"),OPTIONAL_PACKAGE_INSTALL_HINTS={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}},SCHEMA_SUBCOMMAND_VALUES=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function getSemanticUnknownOptionSuggestions(commandName,unknownOption){const commandSuggestions=SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS[commandName];if(!commandSuggestions)return[];const normalizedUnknown=normalizeLongFlag(unknownOption);for(const[flag,suggestions]of Object.entries(commandSuggestions))if(normalizeLongFlag(flag)===normalizedUnknown)return suggestions;return[]}function appendCommanderExtensionFailures(renderedUsage,json,failures){if(failures.length===0)return renderedUsage;if(json){const primaryFailure2=failures.find(entry=>entry.declared_command_match===!0),{token_accounting:priorAccounting,...usage}=JSON.parse(renderedUsage),enriched={...usage,...primaryFailure2?{extension_command_failure:{code:"extension_command_activation_failed",extension:primaryFailure2.name,layer:primaryFailure2.layer,error:primaryFailure2.error,recovery_commands:primaryFailure2.recovery_commands??[]}}:{},failed_extensions:failures};return JSON.stringify(priorAccounting===void 0?enriched:attachOutputTokenAccounting(enriched,value=>`${JSON.stringify(value,null,2)}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e860a827-39e1-5d6c-b76e-0d77365ba202")}catch{}})();import{pathExists,resolveItemTypeRegistry,EXIT_CODE,getSettingsPath,resolvePmRoot,readSettings,getActiveExtensionRegistrations,locateItem,runActiveServiceOverride,levenshteinDistanceWithinLimit}from"../sdk/runtime-primitives.js";import{BUILTIN_ITEM_TYPE_VALUES}from"../types/index.js";import{PM_CORE_COMMAND_NAMES,resolveSubcommandFlagContractsForCommand}from"../sdk/cli-contracts.js";import{formatCommanderErrorForDisplay,formatCommanderErrorForJson,projectLeanErrorEnvelope}from"./error-guidance.js";import{normalizeHelpCommandPath}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{EXECUTABLE_COMMAND_ALIASES,findBootstrapCommandTokenIndex,normalizeBootstrapInvocation,parseBootstrapHelpRequest,parseBootstrapGlobalOptions,parseBootstrapCommandName}from"./bootstrap-args.js";import{extractProvidedOptionFlags,normalizeLongFlag,renderPmCommand}from"./argv-utils.js";import{normalizeExtensionNameForMatch}from"./commands/extension/shared.js";import{canonicalizeCommandSuggestions,rankCommandPaths,resolveMisnestedCommandPath}from"../sdk/agent/command-suggestions.js";import{isCompatibleRecoveryFlag,renderMissingOptionRetry,resolveLifecycleVerbRecovery}from"../sdk/agent/command-recovery.js";import{resolvePmCommandScopeArgs}from"../sdk/command-line.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{findPmNamespacedCommand,resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";const BUILTIN_TYPE_HELP_VALUES=BUILTIN_ITEM_TYPE_VALUES.join("|"),OPTIONAL_PACKAGE_INSTALL_HINTS={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}},SCHEMA_SUBCOMMAND_VALUES=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function getSemanticUnknownOptionSuggestions(commandName,unknownOption){const commandSuggestions=SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS[commandName];if(!commandSuggestions)return[];const normalizedUnknown=normalizeLongFlag(unknownOption);for(const[flag,suggestions]of Object.entries(commandSuggestions))if(normalizeLongFlag(flag)===normalizedUnknown)return suggestions;return[]}function appendCommanderExtensionFailures(renderedUsage,json,failures){if(failures.length===0)return renderedUsage;if(json){const primaryFailure2=failures.find(entry=>entry.declared_command_match===!0),{token_accounting:priorAccounting,...usage}=JSON.parse(renderedUsage),enriched={...usage,...primaryFailure2?{extension_command_failure:{code:"extension_command_activation_failed",extension:primaryFailure2.name,layer:primaryFailure2.layer,error:primaryFailure2.error,recovery_commands:primaryFailure2.recovery_commands??[]}}:{},failed_extensions:failures};return JSON.stringify(priorAccounting===void 0?enriched:attachOutputTokenAccounting(enriched,value=>`${JSON.stringify(value,null,2)}
2
2
  `),null,2)}const details=failures.map(entry=>`- ${entry.layer}:${entry.name}: ${entry.error}`).join(`
3
3
  `),primaryFailure=failures.find(entry=>entry.declared_command_match===!0);if(!primaryFailure)return`${renderedUsage}
4
4
  Extension activation failures:
@@ -11,6 +11,6 @@ ${recovery}`:""}
11
11
  ${renderedUsage}
12
12
  Extension activation failures:
13
13
  ${details}`}function resolveUnknownCommanderToken(invocationArgv){return parseBootstrapHelpRequest(invocationArgv).commandPathTokens[0]??parseBootstrapCommandName(invocationArgv)??"<command>"}function collectRuntimeCommandPaths(root,extensionDescriptors){const commandPaths=new Set,queue=[...root.commands];for(;queue.length>0;){const current=queue.shift();if(!current)continue;const normalizedPath=normalizeHelpCommandPath(getCommandPath(current)),hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));normalizedPath.length>0&&!hasInternalSegment&&commandPaths.add(normalizedPath),queue.push(...current.commands)}for(const descriptorPath of extensionDescriptors.keys()){const normalizedPath=normalizeHelpCommandPath(descriptorPath),hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));normalizedPath.length>0&&!hasInternalSegment&&commandPaths.add(normalizedPath)}return[...commandPaths].sort((left,right)=>left.localeCompare(right))}function scoreCommandPathMatch(commandPath,queryToken){const normalizedPath=commandPath.trim().toLowerCase(),normalizedToken=queryToken.trim().toLowerCase();if(normalizedToken.length===0)return Number.POSITIVE_INFINITY;const pathSegments=normalizedPath.split(" ");if(normalizedPath===normalizedToken)return 0;if(pathSegments.includes(normalizedToken))return 1;if(pathSegments.some(segment=>segment.startsWith(normalizedToken)))return 2;if(normalizedPath.includes(normalizedToken))return 3;const maxDistance=normalizedToken.length>=5?2:1;let bestDistance=Number.POSITIVE_INFINITY;for(const segment of pathSegments){const distance=levenshteinDistanceWithinLimit(segment,normalizedToken,maxDistance);distance!==null&&(bestDistance=Math.min(bestDistance,distance))}return Number.isFinite(bestDistance)?4+bestDistance:Number.POSITIVE_INFINITY}function toComparableFlag(flag){return normalizeLongFlag(flag).slice(2).replace(/-/g,"")}function renderAttemptedCommand(argv){return renderPmCommand(argv)}function resolveOptionalPackageInstallHint(commandPath){const canonicalPath=resolvePmCommandAlias(commandPath)?.canonical??EXECUTABLE_COMMAND_ALIASES[commandPath]??commandPath,topLevel=canonicalPath.split(" ")[0]?.trim().toLowerCase();if(!topLevel)return null;const packageAlias=OPTIONAL_PACKAGE_INSTALL_HINTS[topLevel];return packageAlias?{packageAlias,canonicalPath,installCommand:`pm package install ${packageAlias} --project`}:null}function normalizePackageCommandAliasToken(value){let normalized=normalizeExtensionNameForMatch(value);for(const prefix of["@unbrained/","builtin-","pm-"])normalized.startsWith(prefix)&&(normalized=normalized.slice(prefix.length));return normalized}function collectInstalledPackageCommandPathHints(unknownToken,extensionDescriptors){const normalizedUnknown=normalizePackageCommandAliasToken(unknownToken);if(normalizedUnknown.length===0)return[];const hints=[];for(const descriptor of extensionDescriptors.values()){const identifiers=new Set,source=descriptor.source;if(source)for(const identifier of[source.name,source.package]){const normalizedIdentifier=normalizePackageCommandAliasToken(identifier??"");normalizedIdentifier.length>0&&identifiers.add(normalizedIdentifier)}identifiers.size!==0&&[...identifiers].some(identifier=>identifier===normalizedUnknown||identifier.includes(normalizedUnknown)||normalizedUnknown.includes(identifier))&&hints.push(descriptor.command)}return[...new Set(hints)].sort((left,right)=>left.localeCompare(right))}function collectKnownLongFlags(commandName,contractsOverride){const flags=new Set,contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName);for(const contract of contracts){contract.flag.startsWith("--")&&flags.add(normalizeLongFlag(contract.flag));for(const alias of contract.aliases??[])alias.startsWith("--")&&flags.add(normalizeLongFlag(alias))}return[...flags].sort((left,right)=>left.localeCompare(right))}function suggestNearestLongFlags(unknownOption,knownFlags){if(!unknownOption.startsWith("--"))return[];const unknownComparable=toComparableFlag(unknownOption);if(unknownComparable.length===0)return[];const maxDistance=unknownComparable.length>=8?2:1,candidates=[];for(const flag of knownFlags){const flagComparable=toComparableFlag(flag);if(flagComparable===unknownComparable)continue;if(unknownComparable.length>=3&&flagComparable.startsWith(unknownComparable)){candidates.push({flag,rank:0,distance:flagComparable.length-unknownComparable.length});continue}const distance=levenshteinDistanceWithinLimit(unknownComparable,flagComparable,maxDistance);distance===null||distance<=0||candidates.push({flag,rank:1,distance})}return candidates.sort((left,right)=>left.rank!==right.rank?left.rank-right.rank:left.distance!==right.distance?left.distance-right.distance:left.flag.localeCompare(right.flag)).map(entry=>entry.flag).slice(0,3)}let crossCommandFlagIndexCache;const CROSS_COMMAND_FLAG_EXCLUSIONS=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function getCrossCommandFlagIndex(){if(crossCommandFlagIndexCache)return crossCommandFlagIndexCache;const index=new Map;for(const command of PM_CORE_COMMAND_NAMES)if(!CROSS_COMMAND_FLAG_EXCLUSIONS.has(command))for(const flag of collectKnownLongFlags(command)){const commands=index.get(flag)??[];commands.push(command),index.set(flag,commands)}return crossCommandFlagIndexCache=index,crossCommandFlagIndexCache}function findOtherCommandsForFlag(unknownOption,currentCommand){if(!unknownOption.startsWith("--"))return[];const commands=getCrossCommandFlagIndex().get(normalizeLongFlag(unknownOption));if(!commands)return[];const normalizedCurrent=currentCommand?.trim().toLowerCase(),currentFlags=new Set(collectKnownLongFlags(normalizedCurrent));return[...new Set(commands.filter(command=>command!==normalizedCurrent).map(command=>({command,sharedFlagCount:collectKnownLongFlags(command).filter(flag=>currentFlags.has(flag)).length})).sort((left,right)=>left.sharedFlagCount!==right.sharedFlagCount?right.sharedFlagCount-left.sharedFlagCount:left.command.localeCompare(right.command)).map(({command})=>resolvePmCommandAlias(command)?.canonical??command))]}function rewriteUnknownOptionArgv(argv,unknownOption,replacementFlag){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(!token.startsWith("--"))continue;const equalsIndex=token.indexOf("="),key=equalsIndex>=0?token.slice(0,equalsIndex):token;if(normalizeLongFlag(key)!==normalizeLongFlag(unknownOption))continue;const next=[...argv];return next[index]=equalsIndex>=0?`${replacementFlag}${token.slice(equalsIndex)}`:replacementFlag,next}}function scoreRuntimeCommandCandidates(params){const commandPathSet=new Set(params.commandPaths),scoreAgainstUnknown=candidatePath=>Math.min(scoreCommandPathMatch(candidatePath,params.normalizedUnknown),params.primaryToken!==params.normalizedUnknown?scoreCommandPathMatch(candidatePath,params.primaryToken):Number.POSITIVE_INFINITY),scoresByCommandPath=new Map,recordCandidateScore=(commandPath,score)=>{if(!Number.isFinite(score)||!commandPathSet.has(commandPath))return;const existing=scoresByCommandPath.get(commandPath);(existing===void 0||score<existing)&&scoresByCommandPath.set(commandPath,score)};for(const commandPath of params.commandPaths)recordCandidateScore(commandPath,scoreAgainstUnknown(commandPath));for(const[aliasToken,canonicalPath]of Object.entries(EXECUTABLE_COMMAND_ALIASES))aliasToken!=="read"&&recordCandidateScore(canonicalPath,scoreAgainstUnknown(aliasToken));return[...scoresByCommandPath.entries()].sort(([leftPath,leftScore],[rightPath,rightScore])=>leftScore!==rightScore?leftScore-rightScore:leftPath.localeCompare(rightPath)).map(([commandPath])=>commandPath)}function resolveUnknownCommandCandidates(params){const exactAlias=resolvePmCommandAlias(params.normalizedUnknown),semanticCandidates=rankCommandPaths(params.commandPaths,params.primaryToken),rankedCandidates=scoreRuntimeCommandCandidates(params),installedPackageCandidates=collectInstalledPackageCommandPathHints(params.primaryToken,params.extensionDescriptors).filter(commandPath=>params.commandPaths.includes(commandPath));return canonicalizeCommandSuggestions([...exactAlias&&params.commandPaths.includes(exactAlias.canonical)?[exactAlias.canonical_argv.join(" ")]:[],...semanticCandidates,...rankedCandidates,...installedPackageCandidates],params.commandPaths,params.primaryToken).filter(path=>!params.normalizedUnknown.includes(" ")||path!==params.normalizedUnknown)}function resolveUnknownCommandFallbacks(commandPaths){return[...new Set(commandPaths.map(commandPath=>commandPath.split(" ")[0]).filter(segment=>segment.length>0))].sort((left,right)=>left.localeCompare(right))}function buildUnknownCommandExamples(suggestedPaths,hasConcreteCandidates){const suggestedExamples=suggestedPaths.map(path=>`pm ${path} --help`);return hasConcreteCandidates?[...new Set([...suggestedExamples,"pm --help --all"])]:[...new Set(["pm --help --all",...suggestedExamples])]}function resolveUnknownCommandPath(token,invocationArgv,commandPaths){let commandIndex=findBootstrapCommandTokenIndex([...invocationArgv]);const path=[];for(;commandIndex!==void 0;){if(path.push(invocationArgv[commandIndex]),invocationArgv[commandIndex]===token)return path.join(" ");if(!commandPaths.includes(path.join(" ")))return token;const offset=findBootstrapCommandTokenIndex(invocationArgv.slice(commandIndex+1));commandIndex=offset===void 0?void 0:commandIndex+1+offset}return token}function buildCanonicalHelpRetryArgs(canonicalPath,invocationArgv){if(!canonicalPath)return;const bootstrapGlobal=parseBootstrapGlobalOptions([...invocationArgv]);return[...resolvePmCommandScopeArgs(bootstrapGlobal),...canonicalPath.split(" "),"--help"]}function buildUnknownCommandGuidanceFromRuntime(rawMessage,root,extensionDescriptors,invocationArgv=[]){const unknownCommandMatch=rawMessage.match(/unknown command '([^']+)'/i);if(!unknownCommandMatch||typeof unknownCommandMatch[1]!="string")return;const commandPaths=collectRuntimeCommandPaths(root,extensionDescriptors),unknownPath=resolveUnknownCommandPath(unknownCommandMatch[1],invocationArgv,commandPaths),normalizedUnknown=normalizeHelpCommandPath(unknownPath);if(normalizedUnknown.length===0||commandPaths.length===0)return;const lifecycleRecovery=resolveLifecycleVerbRecovery(normalizedUnknown,commandPaths);if(lifecycleRecovery){const retryArgs2=buildCanonicalHelpRetryArgs("update",invocationArgv),bootstrapArgs=retryArgs2.slice(0,-2);return{suggestedRetryCommand:renderPmCommand(retryArgs2),suggestedRetryArgs:retryArgs2,unknownCommandExamples:[renderPmCommand(retryArgs2),...lifecycleRecovery.examples.map(args=>renderPmCommand([...bootstrapArgs,...args]))],unknownCommandNextSteps:lifecycleRecovery.nextSteps}}const optionalPackageHint=resolveOptionalPackageInstallHint(normalizedUnknown);if(optionalPackageHint&&!commandPaths.includes(optionalPackageHint.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[optionalPackageHint.installCommand,`pm ${optionalPackageHint.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${normalizedUnknown}" is provided by the "${optionalPackageHint.packageAlias}" package. Install it with: ${optionalPackageHint.installCommand}. Command after installation: pm ${optionalPackageHint.canonicalPath}.`],suggestedRetryCommand:optionalPackageHint.installCommand};const primaryToken=normalizedUnknown.split(" ")[0],combinedCandidates=resolveUnknownCommandCandidates({commandPaths,normalizedUnknown,primaryToken,extensionDescriptors}),fallbackTopLevel=resolveUnknownCommandFallbacks(commandPaths),misnestedPath=resolveMisnestedCommandPath(normalizedUnknown,commandPaths),retryArgs=buildCanonicalHelpRetryArgs(misnestedPath,invocationArgv),suggestedPaths=[...new Set([...misnestedPath?[misnestedPath]:[],...combinedCandidates.length>0?combinedCandidates:canonicalizeCommandSuggestions(fallbackTopLevel,commandPaths)])].slice(0,3),examples=buildUnknownCommandExamples(suggestedPaths,combinedCandidates.length>0),didYouMean=combinedCandidates.length>0?`Did you mean: ${suggestedPaths.join(", ")}?`:null;return{...retryArgs?{suggestedRetryCommand:renderPmCommand(retryArgs),suggestedRetryArgs:retryArgs}:{},unknownCommandExamples:retryArgs?[renderPmCommand(retryArgs),...examples.slice(1)]:examples,unknownCommandNextSteps:[...didYouMean?[didYouMean]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...didYouMean?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function dedupeStrings(values){return Array.from(new Set(values))}function firstWhitespaceSeparatedToken(input){let token="";for(const character of input){if(character===" "||character===" "||character===`
14
- `||character==="\r"||character==="\f"||character==="\v")break;token+=character}return token}function trimTrailingPunctuationToken(token){let end=token.length;for(;end>0;){const character=token[end-1];if(character!==","&&character!==":"&&character!==";")break;end-=1}return token.slice(0,end)}function resolveChildCommandByToken(parent,token){const normalizedToken=token.trim().toLowerCase();return parent.commands.find(candidate=>candidate.name().trim().toLowerCase()===normalizedToken?!0:(typeof candidate.aliases=="function"?candidate.aliases():[]).some(alias=>alias.trim().toLowerCase()===normalizedToken))}function isKnownHelpCommandPath(root,commandPathTokens){if(commandPathTokens.length===0)return!0;let current=root;for(const[tokenIndex,token]of commandPathTokens.entries()){const next=resolveChildCommandByToken(current,token);if(!next){const declaredArguments=current.registeredArguments;return declaredArguments.length>0&&(current.commands.length===0||declaredArguments[0]?.required===!0)&&(declaredArguments.at(-1)?.variadic===!0||commandPathTokens.length-tokenIndex<=declaredArguments.length)}current=next}return!0}async function resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName){try{const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);if(!await pathExists(getSettingsPath(pmRoot)))return{allowedTypes:BUILTIN_TYPE_HELP_VALUES};const settings=await readSettings(pmRoot),extensionRegistrations=bootstrapGlobal.noExtensions?void 0:getActiveExtensionRegistrations(),typeRegistry=resolveItemTypeRegistry(settings,extensionRegistrations);let verifiedCollectionItemId;if(/too many arguments/i.test(message)&&["comments","docs","files","learnings","notes","test"].includes(commandName??"")){const commandIndex=invocationArgv.findIndex(token=>token===commandName),candidate=invocationArgv[commandIndex+2];if(invocationArgv[commandIndex+1]?.toLowerCase()==="add"&&candidate!==void 0&&!candidate.startsWith("-"))try{verifiedCollectionItemId=(await locateItem(pmRoot,candidate,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder))?.id}catch{}}return{allowedTypes:typeRegistry.types.length>0?typeRegistry.types.join("|"):BUILTIN_TYPE_HELP_VALUES,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,verifiedCollectionItemId}}catch{return{allowedTypes:BUILTIN_TYPE_HELP_VALUES}}}function resolveUnknownOptionSuggestions(message,commandName){const match=message.match(/unknown option '([^']+)'/i),suggestions=match&&commandName?dedupeStrings([...getSemanticUnknownOptionSuggestions(commandName,match[1]),...suggestNearestLongFlags(match[1],collectKnownLongFlags(commandName))]).filter(candidate=>isCompatibleRecoveryFlag(match[1],candidate)):void 0,otherCommands=match?findOtherCommandsForFlag(match[1],commandName):[],declaredOnPath=match!==null&&collectKnownLongFlags(commandName).includes(normalizeLongFlag(match[1]));return{match,suggestions,otherCommands,scope:declaredOnPath?"declared_on_path":otherCommands.length>0?"declared_elsewhere":"declared_nowhere"}}function resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOptionMatch,unknownOptionSuggestions){if(!unknownOptionMatch||!unknownOptionSuggestions||unknownOptionSuggestions.length===0)return;const rewritten=rewriteUnknownOptionArgv(invocationArgv,unknownOptionMatch[1],unknownOptionSuggestions[0]);return rewritten?renderAttemptedCommand(rewritten):void 0}function resolveSuggestedRetryForMissingOption(message,invocationArgv){const missingRequiredOption=message.match(/required option '([^']+)' not specified/i),requiredOptionToken=missingRequiredOption?.[1]?trimTrailingPunctuationToken(firstWhitespaceSeparatedToken(missingRequiredOption[1].trim())):void 0;if(!requiredOptionToken?.startsWith("--"))return;const commandName=parseBootstrapCommandName(invocationArgv);if(commandName)return renderMissingOptionRetry(invocationArgv,commandName,[requiredOptionToken])}function resolveSplitSchemaSubcommand(message,invocationArgv){if(!/too many arguments/i.test(message))return;const commandIndex=findBootstrapCommandTokenIndex(invocationArgv),namespaced=findPmNamespacedCommand(invocationArgv.slice(commandIndex));if(namespaced?.alias!=="schema")return;const schemaIndex=commandIndex+namespaced.canonical_argv.length-1,verb=invocationArgv[schemaIndex+1]?.trim().toLowerCase(),noun=invocationArgv[schemaIndex+2]?.trim().toLowerCase();if(!verb||!noun)return;const joined=`${verb}-${noun}`;if(!SCHEMA_SUBCOMMAND_VALUES.includes(joined))return;const rewritten=[...invocationArgv.slice(0,schemaIndex+1),joined,...invocationArgv.slice(schemaIndex+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${verb} ${noun}`,unknownSubcommandAllowedValues:[...SCHEMA_SUBCOMMAND_VALUES],suggestedRetryCommand:renderAttemptedCommand(rewritten)}}function resolveRecoveryCommandName(message,invocationArgv,rootProgram,extensionDescriptors){const commandIndex=findBootstrapCommandTokenIndex(invocationArgv),inferred=findPmNamespacedCommand(invocationArgv.slice(commandIndex))?.alias??parseBootstrapCommandName(invocationArgv);if(!/unknown option /i.test(message)||inferred===void 0)return inferred;const canonical=resolvePmCommandAlias(inferred)?.canonical??inferred;return PM_CORE_COMMAND_NAMES.some(name=>name===inferred)||collectRuntimeCommandPaths(rootProgram,extensionDescriptors).includes(canonical)?inferred:void 0}async function resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides={},invocationArgs=process.argv.slice(2)){const message=(typeof error=="object"&&error!==null?error.message:void 0)??"Invalid command usage",invocationArgv=normalizeBootstrapInvocation([...invocationArgs]).argv,bootstrapGlobal=parseBootstrapGlobalOptions(invocationArgv),commandName=resolveRecoveryCommandName(message,invocationArgv,rootProgram,extensionDescriptors),attemptedCommand=renderAttemptedCommand(invocationArgv),providedOptionFlags=extractProvidedOptionFlags(invocationArgv),workspaceUsage=await resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName),allowedTypes=workspaceUsage.allowedTypes,unknownCommandGuidance=buildUnknownCommandGuidanceFromRuntime(message,rootProgram,extensionDescriptors,invocationArgv),unknownOption=resolveUnknownOptionSuggestions(message,commandName),splitSchemaSubcommand=resolveSplitSchemaSubcommand(message,invocationArgv),suggestedRetryCommand=splitSchemaSubcommand?.suggestedRetryCommand??resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOption.match,unknownOption.suggestions)??resolveSuggestedRetryForMissingOption(message,invocationArgv);return{message,commandName,allowedTypes,attemptedCommand,normalizedInvocationArgs:[...invocationArgv],providedOptionFlags,unknownOptionSuggestions:unknownOption.suggestions,unknownOptionOtherCommands:unknownOption.otherCommands.length>0?unknownOption.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:unknownOption.otherCommands.length>0?unknownOption.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:unknownOption.otherCommands.length>12||void 0,unknownOptionScope:unknownOption.scope,suggestedRetryCommand,verifiedCollectionItemId:workspaceUsage.verifiedCollectionItemId,...splitSchemaSubcommand,...unknownCommandGuidance,...guidanceOverrides}}async function formatCommanderUsageMessage(error,rootProgram,extensionDescriptors,guidanceOverrides={},invocationArgs=process.argv.slice(2)){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides,invocationArgs),{message,commandName,allowedTypes,...guidance}=usageContext,formatted=formatCommanderErrorForDisplay(message,commandName,allowedTypes,guidance),serviceOverride=await runActiveServiceOverride("help_format",{message:formatted,command:commandName,allowed_types:allowedTypes});return serviceOverride.handled&&typeof serviceOverride.result=="string"?serviceOverride.result:formatted}async function formatCommanderUsageJson(error,rootProgram,extensionDescriptors,lean=!1,guidanceOverrides={},invocationArgs=process.argv.slice(2)){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides,invocationArgs),envelope=formatCommanderErrorForJson(usageContext.message,usageContext.commandName,usageContext.allowedTypes,EXIT_CODE.USAGE,usageContext),projected=lean?projectLeanErrorEnvelope(envelope):envelope,accountingRequested=parseBootstrapGlobalOptions(usageContext.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(accountingRequested?attachOutputTokenAccounting(projected,value=>`${JSON.stringify(value,null,2)}
14
+ `||character==="\r"||character==="\f"||character==="\v")break;token+=character}return token}function trimTrailingPunctuationToken(token){let end=token.length;for(;end>0;){const character=token[end-1];if(character!==","&&character!==":"&&character!==";")break;end-=1}return token.slice(0,end)}function resolveChildCommandByToken(parent,token){const normalizedToken=token.trim().toLowerCase();return parent.commands.find(candidate=>candidate.name().trim().toLowerCase()===normalizedToken?!0:(typeof candidate.aliases=="function"?candidate.aliases():[]).some(alias=>alias.trim().toLowerCase()===normalizedToken))}function isKnownHelpCommandPath(root,commandPathTokens){if(commandPathTokens.length===0)return!0;let current=root;for(const[tokenIndex,token]of commandPathTokens.entries()){const next=resolveChildCommandByToken(current,token);if(!next){const declaredArguments=current.registeredArguments;return declaredArguments.length>0&&(current.commands.length===0||declaredArguments[0]?.required===!0)&&(declaredArguments.at(-1)?.variadic===!0||commandPathTokens.length-tokenIndex<=declaredArguments.length)}current=next}return!0}async function resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName){try{const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);if(!await pathExists(getSettingsPath(pmRoot)))return{allowedTypes:BUILTIN_TYPE_HELP_VALUES};const settings=await readSettings(pmRoot),extensionRegistrations=bootstrapGlobal.noExtensions?void 0:getActiveExtensionRegistrations(),typeRegistry=resolveItemTypeRegistry(settings,extensionRegistrations);let verifiedCollectionItemId;if(/too many arguments/i.test(message)&&["comments","docs","files","learnings","notes","test"].includes(commandName??"")){const commandIndex=invocationArgv.findIndex(token=>token===commandName),candidate=invocationArgv[commandIndex+2];if(invocationArgv[commandIndex+1]?.toLowerCase()==="add"&&candidate!==void 0&&!candidate.startsWith("-"))try{verifiedCollectionItemId=(await locateItem(pmRoot,candidate,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder))?.id}catch{}}return{allowedTypes:typeRegistry.types.length>0?typeRegistry.types.join("|"):BUILTIN_TYPE_HELP_VALUES,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,verifiedCollectionItemId}}catch{return{allowedTypes:BUILTIN_TYPE_HELP_VALUES}}}function resolveUnknownOptionSuggestions(message,commandName){const match=message.match(/unknown option '([^']+)'/i),suggestions=match&&commandName?dedupeStrings([...getSemanticUnknownOptionSuggestions(commandName,match[1]),...suggestNearestLongFlags(match[1],collectKnownLongFlags(commandName))]).filter(candidate=>isCompatibleRecoveryFlag(match[1],candidate)):void 0,otherCommands=match?findOtherCommandsForFlag(match[1],commandName):[],declaredOnPath=match!==null&&collectKnownLongFlags(commandName).includes(normalizeLongFlag(match[1]));return{match,suggestions,otherCommands,scope:declaredOnPath?"declared_on_path":otherCommands.length>0?"declared_elsewhere":"declared_nowhere"}}function resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOptionMatch,unknownOptionSuggestions){if(!unknownOptionMatch||!unknownOptionSuggestions||unknownOptionSuggestions.length===0)return;const rewritten=rewriteUnknownOptionArgv(invocationArgv,unknownOptionMatch[1],unknownOptionSuggestions[0]);return rewritten?renderAttemptedCommand(rewritten):void 0}function resolveSuggestedRetryForMissingOption(message,invocationArgv){const missingRequiredOption=message.match(/required option '([^']+)' not specified/i),requiredOptionToken=missingRequiredOption?.[1]?trimTrailingPunctuationToken(firstWhitespaceSeparatedToken(missingRequiredOption[1].trim())):void 0;if(!requiredOptionToken?.startsWith("--"))return;const commandName=parseBootstrapCommandName(invocationArgv);if(commandName)return renderMissingOptionRetry(invocationArgv,commandName,[requiredOptionToken])}function resolveSplitSchemaSubcommand(message,invocationArgv){if(!/too many arguments/i.test(message))return;const commandIndex=findBootstrapCommandTokenIndex(invocationArgv),namespaced=findPmNamespacedCommand(invocationArgv.slice(commandIndex));if(namespaced?.alias!=="schema")return;const schemaIndex=commandIndex+namespaced.canonical_argv.length-1,verb=invocationArgv[schemaIndex+1]?.trim().toLowerCase(),noun=invocationArgv[schemaIndex+2]?.trim().toLowerCase();if(!verb||!noun)return;const joined=`${verb}-${noun}`;if(!SCHEMA_SUBCOMMAND_VALUES.includes(joined))return;const rewritten=[...invocationArgv.slice(0,schemaIndex+1),joined,...invocationArgv.slice(schemaIndex+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${verb} ${noun}`,unknownSubcommandAllowedValues:[...SCHEMA_SUBCOMMAND_VALUES],suggestedRetryCommand:renderAttemptedCommand(rewritten)}}function resolveRecoveryCommandName(message,invocationArgv,rootProgram,extensionDescriptors){const commandIndex=findBootstrapCommandTokenIndex(invocationArgv),inferred=findPmNamespacedCommand(invocationArgv.slice(commandIndex))?.alias??parseBootstrapCommandName(invocationArgv);if(!/unknown option /i.test(message)||inferred===void 0)return inferred;const canonical=resolvePmCommandAlias(inferred)?.canonical??inferred;return PM_CORE_COMMAND_NAMES.some(name=>name===inferred)||collectRuntimeCommandPaths(rootProgram,extensionDescriptors).includes(canonical)?inferred:void 0}async function resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides={},invocationArgs=process.argv.slice(2)){const message=(typeof error=="object"&&error!==null?error.message:void 0)??"Invalid command usage",invocationArgv=normalizeBootstrapInvocation([...invocationArgs]).argv,bootstrapGlobal=parseBootstrapGlobalOptions(invocationArgv),commandName=resolveRecoveryCommandName(message,invocationArgv,rootProgram,extensionDescriptors),attemptedCommand=renderAttemptedCommand(invocationArgv),providedOptionFlags=extractProvidedOptionFlags(invocationArgv),workspaceUsage=await resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName),allowedTypes=workspaceUsage.allowedTypes,unknownCommandGuidance=buildUnknownCommandGuidanceFromRuntime(message,rootProgram,extensionDescriptors,invocationArgv),unknownOption=resolveUnknownOptionSuggestions(message,commandName),splitSchemaSubcommand=resolveSplitSchemaSubcommand(message,invocationArgv),suggestedRetryCommand=splitSchemaSubcommand?.suggestedRetryCommand??resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOption.match,unknownOption.suggestions)??resolveSuggestedRetryForMissingOption(message,invocationArgv);return{message,commandName,allowedTypes,attemptedCommand,normalizedInvocationArgs:[...invocationArgv],providedOptionFlags,unknownOptionSuggestions:unknownOption.suggestions,unknownOptionOtherCommands:unknownOption.otherCommands.length>0?unknownOption.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:unknownOption.otherCommands.length>0?unknownOption.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:unknownOption.otherCommands.length>12||void 0,unknownOptionScope:unknownOption.scope,suggestedRetryCommand,verifiedCollectionItemId:workspaceUsage.verifiedCollectionItemId,...splitSchemaSubcommand,...unknownCommandGuidance,...guidanceOverrides}}async function formatCommanderUsageMessage(error,rootProgram,extensionDescriptors,guidanceOverrides={},invocationArgs=process.argv.slice(2)){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides,invocationArgs),{message,commandName,allowedTypes,...guidance}=usageContext,lean=parseBootstrapGlobalOptions(usageContext.normalizedInvocationArgs).lean,formatted=formatCommanderErrorForDisplay(message,commandName,allowedTypes,guidance,{lean}),serviceOverride=await runActiveServiceOverride("help_format",{message:formatted,command:commandName,allowed_types:allowedTypes});return serviceOverride.handled&&typeof serviceOverride.result=="string"?serviceOverride.result:formatted}async function formatCommanderUsageJson(error,rootProgram,extensionDescriptors,lean=!1,guidanceOverrides={},invocationArgs=process.argv.slice(2)){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides,invocationArgs),envelope=formatCommanderErrorForJson(usageContext.message,usageContext.commandName,usageContext.allowedTypes,EXIT_CODE.USAGE,usageContext),projected=lean?projectLeanErrorEnvelope(envelope):envelope,accountingRequested=parseBootstrapGlobalOptions(usageContext.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(accountingRequested?attachOutputTokenAccounting(projected,value=>`${JSON.stringify(value,null,2)}
15
15
  `):projected,null,2)}const _testOnly={collectKnownLongFlags,collectInstalledPackageCommandPathHints,resolveOptionalPackageInstallHint,resolveSuggestedRetryForMissingOption,suggestNearestLongFlags};export{BUILTIN_TYPE_HELP_VALUES,_testOnly,appendCommanderExtensionFailures,buildUnknownCommandGuidanceFromRuntime,collectRuntimeCommandPaths,formatCommanderUsageJson,formatCommanderUsageMessage,isKnownHelpCommandPath,resolveChildCommandByToken,resolveCommanderUsageContext,resolveUnknownCommanderToken,scoreCommandPathMatch};
16
16
  //# sourceMappingURL=commander-usage.js.map
@@ -14,6 +14,12 @@ tombstone?:PmCliErrorContext["tombstone"];
14
14
  lease?:PmCliErrorContext["lease"];
15
15
  /** Lock generation observed at a refused lock_lost commit. */
16
16
  currentOwner?:PmCliErrorContext["current_owner"];
17
+ /** Principal holding the item behind an already_claimed_by refusal. */
18
+ claimedBy?:string;
19
+ /** When that holder took the item; null when history was silent. */
20
+ claimedAt?:string | null;
21
+ /** Whether the holder arrived through a claim or an assignment. */
22
+ claimSource?:PmCliErrorContext["claim_source"];
17
23
  code:string;
18
24
  type:string;
19
25
  title:string;
@@ -46,8 +52,20 @@ policy_violation_count?:number;
46
52
  /** Process exit code paired with the refusal. */
47
53
  exit_code:number;
48
54
  }
55
+ /** Structured preflight advisories retained alongside a machine-readable outcome. */
56
+ export interface PreflightWarningDiagnostics {
57
+ /** Stable advisory codes emitted before command execution. */
58
+ warnings?:string[];
59
+ /** Additional actionable guidance that accompanies an advisory code. */
60
+ warning_details?:Array<{
61
+ /** Stable code identifying the advisory. */
62
+ code:string;
63
+ /** Human-readable remediation retained for this code. */
64
+ message:string;
65
+ }>;
66
+ }
49
67
  /** Documents the json error envelope payload exchanged by command, SDK, and package integrations. */
50
- export interface JsonErrorEnvelope {
68
+ export interface JsonErrorEnvelope extends PreflightWarningDiagnostics {
51
69
  /** Completed durable writes, with paths relative to the selected tracker. */
52
70
  side_effects?:PmCliErrorContext["side_effects"];
53
71
  /** Verified admission refusal before any mutation. */
@@ -64,6 +82,12 @@ tombstone?:PmCliErrorContext["tombstone"];
64
82
  lease?:PmCliErrorContext["lease"];
65
83
  /** Lock generation observed at a refused lock_lost commit, or null when none exists. */
66
84
  current_owner?:PmCliErrorContext["current_owner"];
85
+ /** Principal holding the item behind an already_claimed_by refusal. */
86
+ claimed_by?:string;
87
+ /** When that holder took the item, or null when history was silent. */
88
+ claimed_at?:string | null;
89
+ /** Whether the holder arrived through an explicit claim or a metadata assignment. */
90
+ claim_source?:PmCliErrorContext["claim_source"];
67
91
  /** Schema type that determines the shape and validation rules for this value. */
68
92
  type:string;
69
93
  /** Value that configures or reports code for this contract. */
@@ -101,7 +125,12 @@ diagnostic_output?:PmDiagnosticOutputReceipt;
101
125
  }
102
126
  /** Error envelope after deterministic budget projection. */
103
127
  export type ProjectedJsonErrorEnvelope = PmProjectedDiagnostic<JsonErrorEnvelope>;
104
- /** Compact an error envelope to fields that change the caller's next action. */
128
+ /**
129
+ * Compact an error envelope to fields that change the caller's next action:
130
+ * the duplicated title, generic `required`/`why`/examples and the invocation
131
+ * echo go; code-specific rationale, examples, recovery and typed holder
132
+ * evidence stay (GH-1610).
133
+ */
105
134
  export declare function projectLeanErrorEnvelope(envelope:ProjectedJsonErrorEnvelope):ProjectedJsonErrorEnvelope;
106
135
  /** Documents the error classification payload exchanged by command, SDK, and package integrations. */
107
136
  export interface ErrorClassification {
@@ -121,6 +150,12 @@ tombstone?:PmCliErrorContext["tombstone"];
121
150
  lease?:PmCliErrorContext["lease"];
122
151
  /** Lock generation observed at a refused lock_lost commit, or null when none exists. */
123
152
  current_owner?:PmCliErrorContext["current_owner"];
153
+ /** Principal holding the item behind an already_claimed_by refusal. */
154
+ claimed_by?:string;
155
+ /** When that holder took the item, or null when history was silent. */
156
+ claimed_at?:string | null;
157
+ /** Whether the holder arrived through an explicit claim or a metadata assignment. */
158
+ claim_source?:PmCliErrorContext["claim_source"];
124
159
  /** Schema type that determines the shape and validation rules for this value. */
125
160
  type:string;
126
161
  /** Value that configures or reports code for this contract. */
@@ -199,8 +234,13 @@ declare function resolveKnownPackageCommandHint(commandToken:string):PackageComm
199
234
  declare function renderList(title:string,entries:string[]):string[];
200
235
  /** Whitelist valid recovery fields before exposing them in public CLI diagnostics. */
201
236
  declare function normalizeRecoveryPayload(payload:PmCliErrorRecoveryPayload | undefined):PmCliErrorRecoveryPayload | undefined;
237
+ /** Presentation controls for text refusals. */
238
+ export interface RenderGuidanceOptions {
239
+ /** Omit constant boilerplate and the invocation echo; keep code-specific recovery (GH-1610). */
240
+ lean?:boolean;
241
+ }
202
242
  /** Implements render guidance message for the public runtime surface of this module. */
203
- export declare function renderGuidanceMessage(message:GuidanceMessage):string;
243
+ export declare function renderGuidanceMessage(message:GuidanceMessage,options?:RenderGuidanceOptions):string;
204
244
  /** Project guidance into JSON, preserving no-write evidence only when explicitly verified. */
205
245
  declare function guidanceToJsonEnvelope(message:GuidanceMessage,exitCode:number):JsonErrorEnvelope;
206
246
  /** Classify guidance with the same optional refusal evidence as the JSON envelope. */
@@ -216,13 +256,13 @@ declare function appendIfMissing(entries:string[],value:string | undefined):stri
216
256
  /** Synthesize a copy-pasteable retry for the unquoted linked-test value shape `pm test <id> --add command npm test -- parser` by re-joining the shell-split value tokens into the documented quoted `key=value` form. Only fires when the item id already precedes the flag (so trailing tokens unambiguously belong to the value) and the token after `--add`/`--remove` is an entry-identity key. */
217
257
  export declare function buildLinkedTestQuotedRetryCommand(argv:string[] | undefined):string | undefined;
218
258
  /** Render concise initialization recovery or the bounded diagnostic for other failures. */
219
- export declare function formatPmCliErrorForDisplay(rawMessage:string,context?:PmCliErrorContext):string;
259
+ export declare function formatPmCliErrorForDisplay(rawMessage:string,context?:PmCliErrorContext,options?:RenderGuidanceOptions):string;
220
260
  /** Implements classify pm cli error for the public runtime surface of this module. */
221
261
  export declare function classifyPmCliError(rawMessage:string,context?:PmCliErrorContext):ErrorClassification;
222
262
  /** Implements format pm cli error for json for the public runtime surface of this module. */
223
263
  export declare function formatPmCliErrorForJson(rawMessage:string,exitCode:number,context?:PmCliErrorContext):ProjectedJsonErrorEnvelope;
224
264
  /** Implements format commander error for display for the public runtime surface of this module. */
225
- export declare function formatCommanderErrorForDisplay(rawMessage:string,commandName:string | undefined,allowedTypes:string,context?:CommanderGuidanceContext):string;
265
+ export declare function formatCommanderErrorForDisplay(rawMessage:string,commandName:string | undefined,allowedTypes:string,context?:CommanderGuidanceContext,options?:RenderGuidanceOptions):string;
226
266
  /** Implements classify commander error for the public runtime surface of this module. */
227
267
  export declare function classifyCommanderError(rawMessage:string,commandName:string | undefined,allowedTypes:string,context?:CommanderGuidanceContext):ErrorClassification;
228
268
  /** Implements format commander error for json for the public runtime surface of this module. */
@@ -1,4 +1,6 @@
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]="2302a550-7046-5865-93ed-93771ac4b787")}catch{}})();import{isReadProjectionRecoveryFlag,resolveReadOptionRetryArgs,resolveLinkedResourcePositionalRecovery}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.sideEffects!==void 0&&(payload.side_effects=message.sideEffects),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,sideEffects:context.side_effects,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=context?.allowed??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",...commandName==="activity"?["--since"]:[]].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 buildLinkedResourcePositionalGuidance(message,commandName,context){if(!/too many arguments/i.test(message))return null;const recovery=resolveLinkedResourcePositionalRecovery(commandName,context?.normalizedInvocationArgs??[]);if(!recovery)return null;const retry=recovery.retryArgs?renderPmCommand(recovery.retryArgs):void 0,template=renderPmCommand(recovery.templateArgs??["test",recovery.itemId,"--add",`command=<actual command>,${recovery.value}`]);return makeGuidanceMessage({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${commandName}.`,required:retry?`Retry the explicit collection mutation: ${retry}`:`Supply the actual command and its metadata together, for example ${template}.`,examples:[retry??template],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:retry,suggested_retry_args:recovery.retryArgs})})}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)??buildLinkedResourcePositionalGuidance(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
- `):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};
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]="df89d031-f8e3-5d3b-bfe8-a1d8c00f18fd")}catch{}})();import{describeReadCompletenessControls,isReadProjectionRecoveryFlag,resolveReadCompletenessControls,resolveReadOptionRetryArgs,resolveLinkedResourcePositionalRecovery}from"../sdk/agent/command-recovery.js";import{isPmTokenBudgetRecovery}from"../sdk/errors.js";import{resolveRecoveryCommandName}from"../sdk/agent/command-recovery.js";import{estimatePmOutputTokens,isGenericRefusalRequired,isGenericRefusalWhy,projectLeanRecoveryPayload,projectPmDiagnosticOutput,projectPmDiagnosticText,resolvePmDiagnosticOutputBudget,withoutGenericRefusalExamples}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{title:_title,...actionable}=envelope;isGenericRefusalWhy(actionable.why)&&delete actionable.why,isGenericRefusalRequired(actionable.required)&&delete actionable.required;const examples=withoutGenericRefusalExamples(actionable.examples);examples.length>0?actionable.examples=examples:delete actionable.examples;const recovery=projectLeanRecoveryPayload(actionable.recovery);return recovery===void 0?delete actionable.recovery:actionable.recovery=recovery,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}const CLAIM_HOLDER_TEXT_MAX_CODE_POINTS=120;function renderClaimHolderLine(message){if(message.claimedBy===void 0)return;const since=message.claimedAt?` since ${message.claimedAt}`:"",holder=Array.from(message.claimedBy);return`Held by: ${holder.length>CLAIM_HOLDER_TEXT_MAX_CODE_POINTS?`${holder.slice(0,CLAIM_HOLDER_TEXT_MAX_CODE_POINTS).join("")}...`:message.claimedBy} (${message.claimSource??"unknown"}${since})`}function renderGuidanceLead(message,lean){const lines=[`Error: ${message.title}`];(!lean||!isGenericRefusalRequired(message.required))&&lines.push("","What is required:",` ${message.required}`),message.nextSteps&&message.nextSteps.length>0&&(lines.push(""),lines.push(...renderList("Next steps:",message.nextSteps))),message.happened!==message.title&&lines.push("","What happened:",` ${message.happened}`);const holderLine=renderClaimHolderLine(message);return holderLine!==void 0&&lines.push("",holderLine),lines}function renderGuidanceExplanation(message,lean){const lines=[];message.why&&!(lean&&isGenericRefusalWhy(message.why))&&lines.push("","Why:",` ${message.why}`);const examples=lean?withoutGenericRefusalExamples(message.examples):message.examples??[];examples.length>0&&lines.push("",...renderList("Examples:",examples));const verificationErrors=message.verificationErrors??[];return verificationErrors.length>0&&lines.push("",...renderList("Verification errors:",verificationErrors)),lines}function renderGuidanceMessage(message,options={}){const lean=options.lean===!0,lines=[...renderGuidanceLead(message,lean),...renderGuidanceExplanation(message,lean)],recoveryLines=renderRecoveryBundle(lean?projectLeanRecoveryPayload(message.recovery):message.recovery);return recoveryLines.length>0&&(lines.push(""),lines.push(...recoveryLines)),lines.join(`
2
+ `)}const TEXT_DIAGNOSTIC_OMISSION_NOTICE="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for the full recovery envelope.",TEXT_RECOVERY_RETRY_MAX_BYTES=400,TEXT_HAPPENED_MAX_CODE_POINTS=320;function compactTextRecovery(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized)return;const compact={};normalized.suggested_retry&&Buffer.byteLength(normalized.suggested_retry,"utf8")<=TEXT_RECOVERY_RETRY_MAX_BYTES&&(compact.suggested_retry=normalized.suggested_retry);for(const key of["missing","missing_required_fields","allowed_values"]){const values=normalized[key];values&&values.length>0&&(compact[key]=values.slice(0,3))}return normalized.next_best_command&&(compact.next_best_command=normalized.next_best_command),Object.keys(compact).length>0?compact:void 0}function renderBoundedGuidanceMessage(message,options={}){const full=renderGuidanceMessage(message,options),budget=resolvePmDiagnosticOutputBudget("error").default_max_estimated_tokens_by_format.text,fits=text=>estimatePmOutputTokens(Buffer.byteLength(text,"utf8"))<=budget;if(fits(full))return full;const withoutExplanation={...message,why:void 0},limitedCollections={...withoutExplanation,examples:message.examples?.slice(0,1),nextSteps:message.nextSteps?.slice(0,1),verificationErrors:message.verificationErrors?.slice(0,3)},compactRecovery={...limitedCollections,recovery:compactTextRecovery(message.recovery)},happenedCodePoints=Array.from(message.happened),boundedHappened={...compactRecovery,examples:void 0,happened:happenedCodePoints.length>TEXT_HAPPENED_MAX_CODE_POINTS?`${happenedCodePoints.slice(0,TEXT_HAPPENED_MAX_CODE_POINTS).join("")}...`:message.happened};for(const candidate of[withoutExplanation,limitedCollections,compactRecovery,boundedHappened]){const text=`${renderGuidanceMessage(candidate,options)}
3
+
4
+ ${TEXT_DIAGNOSTIC_OMISSION_NOTICE}`;if(fits(text))return text}return full}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),message.claimedBy!==void 0&&(payload.claimed_by=message.claimedBy,payload.claimed_at=message.claimedAt??null,payload.claim_source=message.claimSource??"unknown",payload.item_id=message.itemId)}function attachStructuredGuidanceDetails(payload,message){return message.sideEffects!==void 0&&(payload.side_effects=message.sideEffects),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,sideEffects:context.side_effects,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,claimedBy:context.claimed_by,claimedAt:context.claimed_at,claimSource:context.claim_source,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=context?.allowed??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,retryCommand?void 0:describeSameCommandCompleteness(optionName,commandName),proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,isDashLeadingValue(optionName)?`"${optionName}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`: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")}const READ_COMPLETENESS_SPELLINGS=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function describeSameCommandCompleteness(optionName,commandName){if(commandName===void 0||!READ_COMPLETENESS_SPELLINGS.includes(optionName.split("=",1)[0]))return;const controls=resolveReadCompletenessControls(commandName);return controls===void 0?void 0:`Completeness controls accepted by pm ${controls.command}: ${describeReadCompletenessControls(controls)}.`}function resolveReadIntentRetry(context,optionName,commandName){const retry=resolveReadOptionRetryArgs(commandName??"",context.normalizedInvocationArgs??[],optionName);return retry?{retryCommand:renderPmCommand(retry),suggestedRetryArgs:retry}:[...READ_COMPLETENESS_SPELLINGS,"--toon",...commandName==="activity"?["--since"]:[]].includes(optionName.split("=",1)[0])?{}:void 0}function isDashLeadingValue(optionName){return/\s/u.test(optionName)}function resolveDashLeadingValueRetry(args,optionName){const index=args?.indexOf(optionName)??-1;if(args===void 0||index<0||args.includes("--")||args.lastIndexOf(optionName)!==index)return{};if(args.slice(index+1).some(token=>!token.startsWith("-")))return{};const suggestedRetryArgs=[...stripGlobalBootstrapTokens(args.filter((_,position)=>position!==index)),"--",optionName];return{retryCommand:renderPmCommand(suggestedRetryArgs),suggestedRetryArgs}}function resolveUnknownOptionRetry(context,optionName,commandName){if(isDashLeadingValue(optionName))return resolveDashLeadingValueRetry(context.normalizedInvocationArgs,optionName);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 buildLinkedResourcePositionalGuidance(message,commandName,context){if(!/too many arguments/i.test(message))return null;const recovery=resolveLinkedResourcePositionalRecovery(commandName,context?.normalizedInvocationArgs??[]);if(!recovery)return null;const retry=recovery.retryArgs?renderPmCommand(recovery.retryArgs):void 0,template=renderPmCommand(recovery.templateArgs??["test",recovery.itemId,"--add",`command=<actual command>,${recovery.value}`]);return makeGuidanceMessage({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${commandName}.`,required:retry?`Retry the explicit collection mutation: ${retry}`:`Supply the actual command and its metadata together, for example ${template}.`,examples:[retry??template],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:retry,suggested_retry_args:recovery.retryArgs})})}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)??buildLinkedResourcePositionalGuidance(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,options={}){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(`
5
+ `):renderBoundedGuidanceText(guidance,options)}function renderBoundedGuidanceText(guidance,options){const render=renderOptions=>projectPmDiagnosticText(renderBoundedGuidanceMessage(guidance,renderOptions),guidance.required).output,output=render(options);if(options.lean!==!0)return output;const fallback=render({});return Buffer.byteLength(fallback,"utf8")<Buffer.byteLength(output,"utf8")?fallback: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,options={}){const guidance=buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context);return renderBoundedGuidanceText(guidance,options)}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
6
  //# sourceMappingURL=error-guidance.js.map
@@ -44,6 +44,7 @@ source?:{
44
44
  layer:"global" | "project";
45
45
  name:string;
46
46
  package?:string;
47
+ version?:string;
47
48
  };
48
49
  }
49
50
  /** Documents the help option summary payload exchanged by command, SDK, and package integrations. */