@unbrained/pm-cli 2026.10.24 → 2026.10.26

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 (222) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +48 -0
  3. package/dist/cli/error-guidance.d.ts +5 -0
  4. package/dist/cli/error-guidance.js +2 -2
  5. package/dist/cli/extension-command-help.js +2 -2
  6. package/dist/cli/register-history-activity.js +1 -1
  7. package/dist/cli/register-mutation.js +2 -2
  8. package/dist/cli-bundle/bundle-manifest.json +1 -1
  9. package/dist/cli-bundle/chunks/{chunk-3S5FLCG7.js → chunk-25MTQAHX.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-57YPOOED.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-YEI4N4A6.js → chunk-7UDQAINZ.js} +22 -22
  12. package/dist/cli-bundle/chunks/{chunk-ZDVTXLA6.js → chunk-ER7RLJW5.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-CSE47ZAN.js → chunk-MWCG25PO.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-N6FTEILW.js +20 -0
  15. package/dist/cli-bundle/chunks/{chunk-CDR5ES7Q.js → chunk-NGKTROAO.js} +90 -86
  16. package/dist/cli-bundle/chunks/chunk-OCDRHIVQ.js +6 -0
  17. package/dist/cli-bundle/chunks/{chunk-R7KWBFM2.js → chunk-ONC4BBQP.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-URZB3USE.js → chunk-OUDR2HWR.js} +42 -42
  19. package/dist/cli-bundle/chunks/{chunk-FASDGYQC.js → chunk-T7T4WLUY.js} +3 -3
  20. package/dist/cli-bundle/chunks/{chunk-Z62RXNHW.js → chunk-TGOG5BFM.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-UF6EXZSP.js +2 -0
  22. package/dist/cli-bundle/chunks/chunk-VS2IIV3F.js +128 -0
  23. package/dist/cli-bundle/chunks/chunk-XAIR53QZ.js +2 -0
  24. package/dist/cli-bundle/chunks/{chunk-VSSHB6XI.js → chunk-Y42DYMZX.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-MA7SNKYK.js → chunk-YJBIPNDL.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-4PNAUT2E.js → chunk-Z35XAHUN.js} +2 -2
  27. package/dist/cli-bundle/chunks/chunk-ZLVFUZI4.js +30 -0
  28. package/dist/cli-bundle/chunks/{chunk-3VI4XDP2.js → chunk-ZT64RDMF.js} +2 -2
  29. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-XANVELIV.js → indexed-receipt-blobs-NWQIDTH7.js} +2 -2
  30. package/dist/cli-bundle/chunks/{mutation-admission-NVTBZ7DH.js → mutation-admission-VTNV6JV2.js} +2 -2
  31. package/dist/cli-bundle/chunks/{register-list-query-2FE6K7FQ.js → register-list-query-LZDWUZS4.js} +3 -3
  32. package/dist/cli-bundle/chunks/register-mutation-M2A7PH42.js +20 -0
  33. package/dist/cli-bundle/chunks/register-operations-E7P2JTXM.js +2 -0
  34. package/dist/cli-bundle/chunks/{register-setup-P3VLCTDY.js → register-setup-DOV7KGSH.js} +2 -2
  35. package/dist/cli-bundle/chunks/{settlement-hook-YUVCO65H.js → settlement-hook-SVD6CO7U.js} +2 -2
  36. package/dist/cli-bundle/chunks/stage-LYLEOAQB.js +2 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-226XKW3W.js +8 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-ABMNYWV6.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-RSEGFZTY.js → chunk-ADSBGYLW.js} +54 -54
  40. package/dist/cli-bundle/focused-chunks/{chunk-JYXA4JIP.js → chunk-B266DDBJ.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-R536272H.js → chunk-BH7RE2ZY.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/chunk-BL77VCRB.js +22 -0
  43. package/dist/cli-bundle/focused-chunks/chunk-CSCZYSNZ.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-6HJCSHBG.js → chunk-D5YQ4KAE.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-TAHSXKAT.js → chunk-E5C24MCV.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-SHUPX6G2.js → chunk-I7H3XF25.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-IF6C43IP.js +2 -0
  48. package/dist/cli-bundle/focused-chunks/chunk-KERJNFXY.js +2 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-BUZ2Z4P3.js → chunk-KTXU5WU6.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/chunk-NE27VCU7.js +91 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-NFN2P4TW.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-7RQOFHMH.js → chunk-NLZUI234.js} +4 -4
  53. package/dist/cli-bundle/focused-chunks/chunk-PK5FJIVA.js +12 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-IUAYTD2S.js → chunk-UHWTPOM4.js} +24 -24
  55. package/dist/cli-bundle/focused-chunks/{chunk-ES2NGVHZ.js → chunk-UP765R2V.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-POLMFGPQ.js → chunk-WDWHUJQW.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-NX7TVNUM.js → chunk-YQKLKRMW.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/chunk-YTEC2EPM.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-RVUGTIIU.js → chunk-YW5GHQN2.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-FVOA3XMI.js → indexed-receipt-blobs-YFDNGHCM.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{mutation-admission-PB6YFY7S.js → mutation-admission-L42E3U5U.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{settlement-hook-2VXEB6PP.js → settlement-hook-3CADO4XZ.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/stage-TUQHWU7N.js +2 -0
  64. package/dist/cli-bundle/main.js +19 -19
  65. package/dist/cli-bundle/sdk-authoring.js +1 -1
  66. package/dist/cli-bundle/sdk-contracts.js +2 -2
  67. package/dist/cli-bundle/sdk-core.js +23 -23
  68. package/dist/cli-bundle/sdk-governance.js +1 -1
  69. package/dist/cli-bundle/sdk-graph.js +1 -1
  70. package/dist/cli-bundle/sdk-merge.js +57 -58
  71. package/dist/cli-bundle/sdk-query.js +1 -1
  72. package/dist/cli-bundle/sdk-runtime.js +1 -1
  73. package/dist/cli-bundle/sdk-testing.js +1 -1
  74. package/dist/cli-bundle/sdk.js +9 -9
  75. package/dist/core/diagnostics/remediation.js +1 -1
  76. package/dist/core/extensions/extension-types.d.ts +3 -0
  77. package/dist/core/extensions/extension-types.js +1 -1
  78. package/dist/core/output/mutation-projection.js +1 -1
  79. package/dist/core/policy/workflow-policy-store.js +1 -1
  80. package/dist/core/shared/errors.d.ts +22 -0
  81. package/dist/core/shared/errors.js +1 -1
  82. package/dist/core/shared/secret-rules.d.ts +17 -0
  83. package/dist/core/shared/secret-rules.js +2 -1
  84. package/dist/core/store/item-mutation-precondition.d.ts +8 -0
  85. package/dist/core/store/item-mutation-precondition.js +1 -1
  86. package/dist/core/store/item-store.js +1 -1
  87. package/dist/core/store/settings.js +2 -2
  88. package/dist/sdk/agent/command-recovery.js +1 -1
  89. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  90. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  91. package/dist/sdk/cli-contracts/completeness.js +1 -1
  92. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  93. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  94. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  95. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  96. package/dist/sdk/cli-contracts/registration-helpers.d.ts +3 -1
  97. package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
  98. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  99. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +4 -0
  100. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  101. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  102. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  103. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  104. package/dist/sdk/completion/fish.js +3 -1
  105. package/dist/sdk/completion/zsh.js +3 -1
  106. package/dist/sdk/context-signal-store.js +2 -2
  107. package/dist/sdk/core.d.ts +1 -1
  108. package/dist/sdk/core.js +1 -1
  109. package/dist/sdk/extension-command-context.js +2 -2
  110. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  111. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  112. package/dist/sdk/governance/health-merge-evidence.d.ts +5 -0
  113. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  114. package/dist/sdk/governance/health.js +1 -1
  115. package/dist/sdk/index.d.ts +3 -2
  116. package/dist/sdk/index.js +1 -1
  117. package/dist/sdk/item-transaction.js +1 -1
  118. package/dist/sdk/lifecycle/close-many.d.ts +3 -0
  119. package/dist/sdk/lifecycle/close-many.js +1 -1
  120. package/dist/sdk/lifecycle/close.d.ts +3 -1
  121. package/dist/sdk/lifecycle/close.js +1 -1
  122. package/dist/sdk/lifecycle/create.d.ts +2 -0
  123. package/dist/sdk/lifecycle/create.js +1 -1
  124. package/dist/sdk/lifecycle/plan.d.ts +2 -0
  125. package/dist/sdk/lifecycle/plan.js +1 -1
  126. package/dist/sdk/lifecycle/restore.js +1 -1
  127. package/dist/sdk/lifecycle-policy.d.ts +11 -0
  128. package/dist/sdk/lifecycle-policy.js +1 -1
  129. package/dist/sdk/merge/history-scalar-rebase.d.ts +9 -0
  130. package/dist/sdk/merge/history-scalar-rebase.js +2 -0
  131. package/dist/sdk/merge/ignored-artifacts.d.ts +13 -0
  132. package/dist/sdk/merge/ignored-artifacts.js +2 -0
  133. package/dist/sdk/merge/stage.js +1 -1
  134. package/dist/sdk/merge/three-way.js +1 -1
  135. package/dist/sdk/mutation-guard.d.ts +6 -1
  136. package/dist/sdk/mutation-guard.js +1 -1
  137. package/dist/sdk/output/fit-envelope.d.ts +98 -0
  138. package/dist/sdk/output/fit-envelope.js +2 -0
  139. package/dist/sdk/public-surface.json +1 -1
  140. package/dist/sdk/query/activity.d.ts +14 -2
  141. package/dist/sdk/query/activity.js +1 -1
  142. package/dist/sdk/query/calendar.d.ts +16 -0
  143. package/dist/sdk/query/calendar.js +3 -3
  144. package/dist/sdk/query/context.js +2 -2
  145. package/dist/sdk/query/get.js +1 -1
  146. package/dist/sdk/query/list.js +1 -1
  147. package/dist/sdk/query/search-contracts.js +1 -1
  148. package/dist/sdk/query/window-pagination.d.ts +20 -0
  149. package/dist/sdk/query/window-pagination.js +2 -0
  150. package/dist/sdk/query.d.ts +1 -0
  151. package/dist/sdk/query.js +1 -1
  152. package/dist/sdk/read-output-contracts.js +1 -1
  153. package/dist/sdk/read-output-session.d.ts +1 -1
  154. package/dist/sdk/read-output-session.js +1 -1
  155. package/dist/sdk/runtime-input.js +1 -1
  156. package/dist/sdk/runtime-primitives.d.ts +1 -1
  157. package/dist/sdk/runtime-primitives.js +1 -1
  158. package/dist/sdk/runtime.d.ts +3 -3
  159. package/dist/sdk/runtime.js +1 -1
  160. package/dist/sdk/scheduling-shortcuts.d.ts +2 -0
  161. package/dist/sdk/scheduling-shortcuts.js +1 -1
  162. package/dist/sdk/schema-migration.js +2 -2
  163. package/dist/sdk/templates.d.ts +7 -1
  164. package/dist/sdk/templates.js +2 -2
  165. package/dist/sdk/workspace-transaction.d.ts +3 -1
  166. package/dist/sdk/workspace-transaction.js +2 -2
  167. package/docs/COMMANDS.md +21 -2
  168. package/docs/EXTENSIONS.md +1 -1
  169. package/docs/MERGE_SAFETY.md +28 -0
  170. package/docs/MUTATION_INTEGRITY.md +33 -0
  171. package/docs/QUALITY_EVIDENCE.md +9 -0
  172. package/docs/READ_OUTPUT_CONTRACTS.md +55 -1
  173. package/docs/SDK.md +173 -12
  174. package/docs/WORKFLOW_POLICIES.md +14 -1
  175. package/docs/agent-task-token-baseline.json +1 -1
  176. package/docs/agent-task-transcripts.json +1 -1
  177. package/docs/generated/FLAG_LEXICON_BUDGETS.md +4 -4
  178. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  179. package/marketplace.json +1 -1
  180. package/package.json +1 -1
  181. package/packages/pm-beads/package.json +1 -1
  182. package/packages/pm-calendar/extensions/calendar/index.ts +6 -0
  183. package/packages/pm-calendar/extensions/calendar/shortcuts.ts +2 -2
  184. package/packages/pm-calendar/package.json +1 -1
  185. package/packages/pm-command-kit/package.json +1 -1
  186. package/packages/pm-digital-twin/package.json +1 -1
  187. package/packages/pm-governance-audit/package.json +1 -1
  188. package/packages/pm-guide-shell/package.json +1 -1
  189. package/packages/pm-kanban/package.json +1 -1
  190. package/packages/pm-lifecycle-hooks/package.json +1 -1
  191. package/packages/pm-linked-test-adapters/package.json +1 -1
  192. package/packages/pm-search-advanced/package.json +1 -1
  193. package/packages/pm-templates/extensions/templates/runtime.ts +3 -1
  194. package/packages/pm-templates/package.json +1 -1
  195. package/packages/pm-todos/package.json +1 -1
  196. package/packages/pm-vcs/package.json +1 -1
  197. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  198. package/plugins/pm-claude/package.json +1 -1
  199. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  200. package/plugins/pm-codex/package.json +1 -1
  201. package/plugins/pm-codex/plugin.json +1 -1
  202. package/runtime-dependencies.json +1 -1
  203. package/dist/cli-bundle/chunks/chunk-CNEUJHA4.js +0 -2
  204. package/dist/cli-bundle/chunks/chunk-HZNFNETE.js +0 -127
  205. package/dist/cli-bundle/chunks/chunk-KGZGXC7T.js +0 -30
  206. package/dist/cli-bundle/chunks/chunk-TZYQ4JDZ.js +0 -6
  207. package/dist/cli-bundle/chunks/chunk-UY5UHI4I.js +0 -2
  208. package/dist/cli-bundle/chunks/chunk-VPMQEVU6.js +0 -20
  209. package/dist/cli-bundle/chunks/register-mutation-KZXQUZUH.js +0 -20
  210. package/dist/cli-bundle/chunks/register-operations-BOCBWNKJ.js +0 -2
  211. package/dist/cli-bundle/chunks/stage-WRDTMCCF.js +0 -2
  212. package/dist/cli-bundle/focused-chunks/chunk-3QYTS4OY.js +0 -12
  213. package/dist/cli-bundle/focused-chunks/chunk-5MKNVJCM.js +0 -2
  214. package/dist/cli-bundle/focused-chunks/chunk-AGCEWJ27.js +0 -21
  215. package/dist/cli-bundle/focused-chunks/chunk-CEEOWDB7.js +0 -8
  216. package/dist/cli-bundle/focused-chunks/chunk-GXAXDPD4.js +0 -2
  217. package/dist/cli-bundle/focused-chunks/chunk-NFFPNMTH.js +0 -2
  218. package/dist/cli-bundle/focused-chunks/chunk-SBJ2IKTH.js +0 -3
  219. package/dist/cli-bundle/focused-chunks/chunk-X5YRJMAY.js +0 -2
  220. package/dist/cli-bundle/focused-chunks/chunk-XTYEASIY.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-ZMWLV2CE.js +0 -91
  222. package/dist/cli-bundle/focused-chunks/stage-MQE4PFWT.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.24","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.24","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.26","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.26","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,53 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026.10.26 - 2026-10-26
4
+
5
+ ### Added
6
+
7
+ - Allow safe transaction previews in managed-package workspaces with derived dependency links ([pm-jhkzk0](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-jhkzk0.toon))
8
+
9
+ ### Changed
10
+
11
+ - Adopt release-age eligible Greptile 3.7.0 review tooling ([pm-greptile370](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-greptile370.toon))
12
+
13
+ ### Fixed
14
+
15
+ - GH-1581: Report successful context snapshot refresh without recovery warnings ([pm-gh1581](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1581.toon))
16
+ - GH-1591: guarded terminal updates conflict with their own scalar write and misreport compensation ([pm-pllp78](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-pllp78.toon))
17
+ - Session reference receipts advertise unsupported get --brief recovery ([pm-session-reference-recovery](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-session-reference-recovery.toon))
18
+ - GH-1567: fit whole SDK envelopes using the selected serializer and token budget ([pm-gh1567](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1567.toon))
19
+ - GH-1579: Make inferred completion timestamps observable on close ([pm-gh1579](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1579.toon))
20
+ - GH-1585: make tracked policy-refusal audit side effects explicit and actionable ([pm-gh1585](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1585.toon))
21
+ - GH-1577: make SDK create focus inheritance explicit and discoverable ([pm-gh1577](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1577.toon))
22
+
23
+ ### Security
24
+
25
+ - GH-1583: recognize concrete private home paths through bounded shared normalization ([pm-gh1583](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1583.toon))
26
+
27
+ ### Other
28
+
29
+ - Adopt release-age eligible gpt-tokenizer 4.1.0 and verify token-budget baselines ([pm-tokenizer410](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-tokenizer410.toon))
30
+
31
+ ## 2026.10.25 - 2026-10-25
32
+
33
+ ### Changed
34
+
35
+ - Adopt release-age eligible ESLint 10.13.0 ([pm-eslint1013](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-eslint1013.toon))
36
+
37
+ ### Fixed
38
+
39
+ - GH-1556: diagnose ignored merge-receipt paths before settlement staging ([pm-gh1556](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1556.toon))
40
+ - Rebase concurrent history assignments and removals without losing events ([pm-gh1553](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1553.toon))
41
+ - GH-1562: expose calendar matching totals and bounded continuation ([pm-gh1562](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1562.toon))
42
+ - GH-1554: resume bounded activity reads from a stable event window ([pm-gh1554](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1554.toon))
43
+ - GH-1571: allow projection of active extension item fields across read surfaces ([pm-gh1571](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1571.toon))
44
+ - Use elapsed-time task-state waits in the Windows MRTR regression ([pm-win-task-wait](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-win-task-wait.toon))
45
+ - Align the host grammar census with the latest installed package command ([pm-package-grammar24](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-package-grammar24.toon))
46
+ - GH-1573: await telemetry producers before Sentry fixture cleanup ([pm-gh1573](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1573.toon))
47
+ - GH-1568: keep read-only commands from recreating missing workflow schema files ([pm-gh1568](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1568.toon))
48
+ - GH-1561: normalize numeric template-save priority and publish supported options ([pm-gh1561](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1561.toon))
49
+ - GH-1560: retain extension flag defaults in help and runtime contracts ([pm-gh1560](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1560.toon))
50
+
3
51
  ## 2026.10.24 - 2026-10-24
4
52
 
5
53
  ### Fixed
@@ -1,6 +1,7 @@
1
1
  import { type PmCliErrorContext,type PmCliErrorRecoveryPayload } from "../sdk/runtime-primitives.js";
2
2
  import { type PmDiagnosticOutputReceipt,type PmProjectedDiagnostic } from "../sdk/cli-contracts/agent-output-contracts.js";
3
3
  interface GuidanceMessage {
4
+ sideEffects?:PmCliErrorContext["side_effects"];
4
5
  changed?:false;
5
6
  policyViolations?:PmCliErrorContext["policy_violations"];
6
7
  policyViolationCount?:number;
@@ -47,6 +48,8 @@ exit_code:number;
47
48
  }
48
49
  /** Documents the json error envelope payload exchanged by command, SDK, and package integrations. */
49
50
  export interface JsonErrorEnvelope {
51
+ /** Completed durable writes, with paths relative to the selected tracker. */
52
+ side_effects?:PmCliErrorContext["side_effects"];
50
53
  /** Verified admission refusal before any mutation. */
51
54
  changed?:false;
52
55
  /** Ordered mutation that failed semantic preview validation. */
@@ -102,6 +105,8 @@ export type ProjectedJsonErrorEnvelope = PmProjectedDiagnostic<JsonErrorEnvelope
102
105
  export declare function projectLeanErrorEnvelope(envelope:ProjectedJsonErrorEnvelope):ProjectedJsonErrorEnvelope;
103
106
  /** Documents the error classification payload exchanged by command, SDK, and package integrations. */
104
107
  export interface ErrorClassification {
108
+ /** Completed durable writes, with paths relative to the selected tracker. */
109
+ side_effects?:PmCliErrorContext["side_effects"];
105
110
  /** Verified admission refusal before any mutation. */
106
111
  changed?:false;
107
112
  /** Ordered mutation that failed semantic preview validation. */
@@ -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]="90da2526-967a-5412-bf21-e7e34b5f8f2c")}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.previewStorage!==void 0&&(payload.preview_storage=message.previewStorage),message.transactionOperation!==void 0&&(payload.transaction_operation=message.transactionOperation),attachItemDiagnostics(payload,message),includeWhyInStructuredGuidance(message)&&(payload.why=message.why),message.examples&&message.examples.length>0&&(payload.examples=message.examples),message.nextSteps&&message.nextSteps.length>0&&(payload.next_steps=message.nextSteps),message.verificationErrors&&message.verificationErrors.length>0&&(payload.verification_errors=message.verificationErrors),message.flag!==void 0&&(payload.flag=message.flag),message.value!==void 0&&(payload.value=message.value),message.unmatchedSelectors!==void 0&&(payload.unmatched_selectors=message.unmatchedSelectors),message.availableDependencies!==void 0&&(payload.available_dependencies=message.availableDependencies),message.recovery&&(payload.recovery=message.recovery),payload}function resolveRefusalCandidateFlag(message,normalizedArgs){if(message.flag)return message.flag;const isAdmissibleCandidate=flag=>{const canonicalFlag=flag.split("=",1)[0];return stripGlobalBootstrapTokens([canonicalFlag]).length>0&&!["--help","--no-changed-fields","--version"].includes(canonicalFlag)&&normalizedArgs.some(argument=>argument===canonicalFlag||argument.startsWith(`${canonicalFlag}=`))};return[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(message.flag===void 0&&candidateFlag){const candidateArgument=normalizedArgs.find(argument=>argument===candidateFlag||argument.startsWith(`${candidateFlag}=`));if(candidateArgument?.startsWith(`${candidateFlag}=`))return candidateArgument.slice(candidateFlag.length+1);const candidateIndex=normalizedArgs.indexOf(candidateFlag);return normalizedArgs[candidateIndex+1]}}function buildRefusalEnvelope(message,exitCode){if(message.policyViolations?.length)return{surface:`policy:${message.policyViolations.map(policy=>policy.policy_id).join(",")}`,policies:message.policyViolations,policy_violation_count:message.policyViolationCount,missing_fields:[...new Set(message.policyViolations.flatMap(policy=>policy.missing_fields))],exit_code:exitCode};const invocationArgs=stripGlobalBootstrapTokens(message.recovery?.normalized_args??[]),namespaced=findPmNamespacedCommand(invocationArgs),normalizedArgs=namespaced?[namespaced.alias,...invocationArgs.slice(namespaced.canonical_argv.length)]:invocationArgs,candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs),rejectedValue=resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag);return{surface:candidateFlag??message.recovery?.missing?.[0]??resolveRecoveryCommandName(normalizedArgs)??"command",...rejectedValue!==void 0?{rejected_value:rejectedValue}:{},...message.recovery?.allowed_values?.length?{legal_domain:message.recovery.allowed_values}:{},exit_code:exitCode}}function guidanceToJsonEnvelope(message,exitCode){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,exit_code:exitCode,refusal:buildRefusalEnvelope(message,exitCode),...message.changed===!1?{changed:!1}:{}},message)}function projectJsonErrorGuidance(guidance,exitCode){const recovery=guidance.recovery,hasActionableRecovery=!!recovery?.suggested_retry||!!recovery?.suggested_retry_args?.length||!!recovery?.allowed_values?.length||!!recovery?.candidate_commands?.length||!!guidance.nextSteps?.length;return projectPmDiagnosticOutput(guidanceToJsonEnvelope(guidance,exitCode),{diagnosticClass:hasActionableRecovery?"recovery_bundle":"error"})}function guidanceToClassification(message){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,...message.changed===!1?{changed:!1}:{}},message)}function normalizeMessage(message){return message.replace(/\(outputHelp\)/g,"").trim()}function isModuleResolutionErrorMessage(message){const normalized=message.toLowerCase();return normalized.includes("cannot find module")||normalized.includes("cannot find package")||normalized.includes("err_module_not_found")||normalized.includes("module_not_found")}function normalizeContextList(values){if(!Array.isArray(values))return;const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function dedupeStrings(values){const seen=new Set,result=[];for(const value of values)seen.has(value)||(seen.add(value),result.push(value));return result}function inferCommandNameFromRecovery(recovery){return resolveRecoveryCommandName(recovery?.normalized_args)}function inferAllowedValuesFromMessage(message){const match=message.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return match?match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry)):[]}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args,fields=recovery?.provided_fields,replacement=allowedValues[0];if(!(!Array.isArray(args)||!Array.isArray(fields)||!replacement))for(const field of fields){const index=args.findIndex(arg=>arg===field);if(index>=0&&index<args.length-1&&!args[index+1]?.startsWith("-")){const nextArgs=[...args];return nextArgs[index+1]=replacement,renderPmCommand(nextArgs)}}}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length!==0)return firstLine.length<=120?firstLine:`${firstLine.slice(0,117)}...`}function normalizeContextValue(value,fallback){return typeof value=="string"&&value.trim().length>0?value.trim():fallback}function resolveErrorContextFlag(context,recovery){if(context.flag!==void 0)return context.flag;if(context.field===void 0)return;const flag=context.field.startsWith("--")?context.field:`--${context.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return recovery?.normalized_args?.some(argument=>argument===flag||argument.startsWith(`${flag}=`))?flag:void 0}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context)return guidance;const normalizedRawMessage=normalizeMessage(rawMessage),code=normalizeContextValue(context.code,guidance.code),type=normalizeContextValue(context.type,errorType(code)),examples=normalizeContextList(context.examples)??guidance.examples,nextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps,verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors,fallbackTitle=guidance.code==="command_failed"&&context.code?buildFallbackTitleFromMessage(normalizedRawMessage):void 0,contextRecovery=normalizeRecoveryPayload(context.recovery),recovery=contextRecovery&&guidance.recovery?normalizeRecoveryPayload({...guidance.recovery,...contextRecovery}):contextRecovery??guidance.recovery;return{...guidance,code,changed:context.changed,type,title:fallbackTitle??guidance.title,happened:normalizedRawMessage.length>0?normalizedRawMessage:guidance.happened,required:normalizeContextValue(context.required,guidance.required),why:normalizeContextValue(context.why,guidance.why),examples,nextSteps,verificationErrors,policyViolations:context.policy_violations,policyViolationCount:context.policy_violation_count,flag:resolveErrorContextFlag(context,recovery)??guidance.flag,value:context.value??guidance.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,transactionOperation:context.transaction_operation,previewStorage:context.preview_storage,tombstone:context.tombstone,lease:context.lease,currentOwner:context.current_owner,availableDependencies:context.available_dependencies,recovery}}function buildTrackerNotInitializedGuidance(rawMessage,message,context){const trackerNotInitialized=message.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!trackerNotInitialized)return null;const attemptedRoot=trackerNotInitialized[1],nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);return applyPmCliErrorContext(makeGuidanceMessage(nearbyRoot?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${attemptedRoot}, but found a tracker at ${nearbyRoot}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${nearbyRoot} <command>`,`PM_PATH=${nearbyRoot} pm <command>`],nextSteps:[`Re-run with "--pm-path ${nearbyRoot}" or export PM_PATH=${nearbyRoot}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${trackerNotInitialized[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),rawMessage,context)}function buildItemNotFoundGuidance(rawMessage,message,context){const itemNotFound=message.match(/^Item ([^ ]+) not found$/);if(!itemNotFound)return null;const badId=itemNotFound[1],isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId),happened=isPlaceholder?`The item ID "${badId}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${badId}" exists in the active tracker scope.`;return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",flag:"id",value:badId,happened,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:isPlaceholder?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){return!message.includes("is assigned to")||!message.includes("Use --force to override")?null:applyPmCliErrorContext(makeGuidanceMessage({code:"ownership_conflict",title:"Ownership conflict",happened:message,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),rawMessage,context)}function buildLockConflictGuidance(rawMessage,message,context){if(!message.includes("is locked"))return null;const args=normalizeRecoveryArgs(context?.recovery?.normalized_args),retry=args?renderPmCommand(args):void 0,guidance=applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:retry?[retry]:["pm gc --scope locks --dry-run"]}),rawMessage,context);return args&&(guidance.recovery={...guidance.recovery,suggested_retry:retry,suggested_retry_args:[...args]}),guidance}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /),missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions)return null;const plural=!!missingRequiredOptions,missingOptionFlag=plural?null:message.replace(/^Missing required option\s+/,"").trim(),missingOptionLabel=missingOptionFlag??"",missingOptionRequired=missingOptionFlag?`Pass ${missingOptionFlag} with a valid value before running the command.`:"Provide the required option for this command invocation.";return applyPmCliErrorContext(makeGuidanceMessage({code:"missing_required_option",title:plural?"Missing required options":`Missing required option ${missingOptionLabel}`,happened:message,required:plural?"Provide every required option for this command invocation.":missingOptionRequired,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),rawMessage,context)}function buildNoUpdateFieldsGuidance(rawMessage,message,context){return message.startsWith("No update flags provided")?applyPmCliErrorContext(makeGuidanceMessage({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),rawMessage,context):null}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!message.startsWith("Invalid ")&&!message.includes(" must be ")&&!message.includes(" requires "))return null;const recovery=normalizeRecoveryPayload(context?.recovery),commandName=inferCommandNameFromRecovery(recovery),helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help",allowedValues=inferAllowedValuesFromMessage(message),enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues}),retryExample=buildAllowedValueRetryCommand(recovery,allowedValues),examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"],nextSteps=allowedValues.length>0?[`Allowed values: ${allowedValues.join("|")}`,`Run "${helpExample}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return applyPmCliErrorContext(makeGuidanceMessage({code:"invalid_argument_value",title:"Invalid argument value",happened:message,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples,nextSteps,recovery:enrichedRecovery}),rawMessage,context)}function buildPmCliErrorGuidance(rawMessage,context){const message=normalizeMessage(rawMessage);return(buildTrackerNotInitializedGuidance(rawMessage,message,context)??buildItemNotFoundGuidance(rawMessage,message,context)??buildOwnershipConflictGuidance(rawMessage,message,context)??buildLockConflictGuidance(rawMessage,message,context)??buildPmMissingRequiredOptionGuidance(rawMessage,message,context)??buildNoUpdateFieldsGuidance(rawMessage,message,context)??buildInvalidArgumentGuidance(rawMessage,message,context))||applyPmCliErrorContext(makeGuidanceMessage({code:"command_failed",title:"Command failed",happened:message,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),rawMessage,context)}function commandExampleForRequiredOption(commandName,optionFlag,allowedTypes){return commandName==="create"&&optionFlag.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${allowedTypes.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:commandName==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();return normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??normalized}function renderPmCommandFromArgs(argv){if(!(!Array.isArray(argv)||argv.length===0))return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values))return;const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function buildCommanderRecoveryPayload(context,overrides={}){const providedFields=normalizeOptionFlags(context?.providedOptionFlags),normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0,attemptedCommand=typeof context?.attemptedCommand=="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs),retryCommand=typeof context?.suggestedRetryCommand=="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,suggested_retry_args:context?.suggestedRetryArgs,...overrides})}function appendIfMissing(entries,value){return!value||entries.includes(value)?entries:[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]),LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(Array.isArray(argv))for(const token of argv){if(!token.startsWith("--"))continue;const equalsIndex=token.indexOf("="),flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag))return flag}}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv))return;const commandIndex=argv.indexOf("test");if(commandIndex<0)return;const idToken=argv[commandIndex+1];if(!(typeof idToken!="string"||idToken.startsWith("-")))for(let index=commandIndex+2;index<argv.length;index+=1){const token=argv[index];if(token!=="--add"&&token!=="--remove")continue;const key=argv[index+1];if(typeof key!="string"||!LINKED_TEST_RETRY_KEYS.has(key))return;const valueTokens=[];for(let cursor=index+2;cursor<argv.length;cursor+=1){const candidate=argv[cursor];if(candidate.startsWith("--")&&candidate.length>2)break;valueTokens.push(candidate)}if(valueTokens.length<2)return;const merged=`${key}=${valueTokens.join(" ")}`,rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption)return null;const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]),isType=optionFlag.startsWith("--type"),retryCommand=context?.suggestedRetryCommand,providedFlags=normalizeOptionFlags(context?.providedOptionFlags),missing=[optionFlag],examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes),examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples,nextStepsBase=isType?[`Allowed type values: ${allowedTypes}`,`Run "pm ${commandName??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${commandName??"<command>"} --help" for required option guidance.`],nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase,nextSteps=providedFlags&&providedFlags.length>0?appendIfMissing(nextStepsWithRetry,`Already provided options: ${providedFlags.join(", ")}`):nextStepsWithRetry;return makeGuidanceMessage({code:"missing_required_option",title:`Missing required option ${optionFlag}`,happened:`Commander rejected the command because ${optionFlag} was not provided.`,required:`Pass ${optionFlag} with a valid value before running the command.`,why:isType?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:examplesWithRetry,nextSteps,recovery:buildCommanderRecoveryPayload(context,{missing})})}function buildMissingRequiredArgumentGuidance(message,commandName,context){const missingArgument=message.match(/missing required argument '([^']+)'/);if(!missingArgument)return null;const argumentName=missingArgument[1];return makeGuidanceMessage({code:"missing_required_argument",title:`Missing required argument ${argumentName}`,happened:`Command invocation omitted positional argument ${argumentName}.`,required:`Provide ${argumentName} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context,{missing:[argumentName]})})}function buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions){return makeGuidanceMessage({code:"unsupported_update_option",title:`Unsupported option ${optionName} for update`,happened:`pm update does not accept ${optionName} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions})})}const UNKNOWN_OPTION_REQUIRED_BY_SCOPE={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function resolveUnknownOptionCandidateContext(context){const otherCommands=normalizeContextList(context.unknownOptionOtherCommands)??[];return{otherCommands,optionScope:context.unknownOptionScope??(otherCommands.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:context.unknownOptionOtherCommandsTotal??otherCommands.length}}function buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand){const proseCommands=candidateContext.otherCommands.slice(0,3),proseRemainder=candidateContext.candidateTotal-proseCommands.length,proseRemainderText=proseRemainder>0?` and ${String(proseRemainder)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",suggestions.length?`Nearest supported options: ${suggestions.join(", ")}`:void 0,proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,candidateContext.optionScope==="declared_nowhere"?`${optionName} is not declared on any command path. Use a nearest supported option on ${commandName??"the attempted command"}, or inspect that command's help.`:void 0,retryCommand?`Replay with suggested correction: ${retryCommand}`:void 0].filter(entry=>typeof entry=="string")}function resolveReadIntentRetry(context,optionName,commandName){const retry=resolveReadOptionRetryArgs(commandName??"",context.normalizedInvocationArgs??[],optionName);return retry?{retryCommand:renderPmCommand(retry),suggestedRetryArgs:retry}:["--full","--depth","--toon"].includes(optionName.split("=",1)[0])?{}:void 0}function resolveUnknownOptionRetry(context,optionName,commandName){if(["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0]))return{};const readRetry=resolveReadIntentRetry(context,optionName,commandName);if(readRetry)return readRetry;if(context.suggestedRetryCommand!==void 0)return{retryCommand:context.suggestedRetryCommand};if(isReadProjectionRecoveryFlag(optionName))return{};const normalizedArgs=context.normalizedInvocationArgs;if(normalizedArgs===void 0)return{};if(normalizedArgs.filter(argument=>argument===optionName||argument.startsWith(`${optionName}=`)).length!==1)return{};const optionIndex=normalizedArgs.findIndex(argument=>argument===optionName||argument.startsWith(`${optionName}=`));if(optionIndex<0||normalizedArgs.includes("--")||!normalizedArgs[optionIndex]?.includes("=")&&optionIndex!==normalizedArgs.length-1&&normalizedArgs[optionIndex+1]?.startsWith("-")!==!0)return{};const suggestedRetryArgs=stripGlobalBootstrapTokens(normalizedArgs.filter((_,index)=>index!==optionIndex));return{retryCommand:renderPmCommand(suggestedRetryArgs),suggestedRetryArgs}}function buildUnknownOptionGuidance(message,commandName,context){const unknownOption=message.match(/unknown option '([^']+)'/);if(!unknownOption)return null;const guidanceContext=context??{},optionName=unknownOption[1],suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[],{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName,commandName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc"))return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions);const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext),nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0])&&nextSteps.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");const examples=[retryCommand,commandName?`pm ${resolvePmCommandAlias(commandName)?.canonical??commandName} --help`:"pm --help --all"].filter(entry=>typeof entry=="string");return makeGuidanceMessage({code:"unknown_option",title:`Unknown option ${optionName}`,happened:`Commander does not recognize option ${optionName} for this command path.`,required:UNKNOWN_OPTION_REQUIRED_BY_SCOPE[candidateContext.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:optionName,value:optionName,examples,nextSteps,recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions.length>0?suggestions:void 0,suggested_retry:retryCommand,suggested_retry_args:suggestedRetryArgs,candidate_commands:candidateContext.otherCommands,candidate_commands_total:candidateContext.candidateTotal||void 0,candidate_commands_truncated:guidanceContext.unknownOptionOtherCommandsTruncated,option_scope:candidateContext.optionScope})})}function buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context){const installStep=`"${commandToken}" is provided by the ${packageHint.packageName} package. Install it with: ${packageHint.installCommand}`,nextSteps=baseNextSteps.filter(step=>!step.endsWith(`: ${packageHint.installCommand}`));return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration. It is shipped by the optional ${packageHint.packageName} package.`,required:`Install the ${packageHint.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:dedupeStrings([packageHint.installCommand,...baseExamples]),nextSteps:dedupeStrings([installStep,...nextSteps]),recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownCommandGuidance(message,context){const unknownCommand=message.match(/unknown command '([^']+)'/);if(!unknownCommand)return null;const commandToken=unknownCommand[1],runtimeExamples=normalizeContextList(context?.unknownCommandExamples),runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps),packageHint=resolveKnownPackageCommandHint(commandToken),baseExamples=runtimeExamples??["pm --help"],baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."],failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase())),hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))?buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context):makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:baseExamples,nextSteps:baseNextSteps,recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownSubcommandGuidance(context){const commandPath=context?.unknownSubcommandPath?.trim(),token=context?.unknownSubcommandToken?.trim(),allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed)return null;const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,value:token,happened:`The positional token sequence "${token}" is not a declared ${commandPath} subcommand.`,required:`Use one of: ${allowed.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...retryCommand?[retryCommand]:[],`pm ${resolvePmCommandAlias(commandPath)?.canonical??commandPath} --help`],nextSteps:retryCommand?[`Retry with the declared hyphenated action: ${retryCommand}`]:["Choose one value from recovery.allowed_values."],recovery:buildCommanderRecoveryPayload(context,{allowed_values:allowed,suggested_retry:retryCommand})})}function buildLinkedTestValueNotQuotedGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||commandName!=="test")return null;const argv=context?.normalizedInvocationArgs,mutationFlag=findLinkedTestMutationFlag(argv);if(!mutationFlag)return null;const retryCommand=buildLinkedTestQuotedRetryCommand(argv);return makeGuidanceMessage({code:"linked_test_value_not_quoted",title:`Linked-test ${mutationFlag} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${mutationFlag} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${mutationFlag} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...retryCommand?[retryCommand]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...retryCommand?[`Replay with the value re-joined into one argument: ${retryCommand}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:buildCommanderRecoveryPayload(context,retryCommand?{suggested_retry:retryCommand}:{})})}const TRANSPOSED_COLLECTION_COMMANDS=new Set(["comments","docs","files","learnings","notes","test"]);function 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(`
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]="b5bc7f6c-367e-5784-926a-f414d8bfbeac")}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=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
3
  `):projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyPmCliError(rawMessage,context){return guidanceToClassification(buildPmCliErrorGuidance(rawMessage,context))}function formatPmCliErrorForJson(rawMessage,exitCode,context){return projectJsonErrorGuidance(buildPmCliErrorGuidance(rawMessage,context),exitCode)}function formatCommanderErrorForDisplay(rawMessage,commandName,allowedTypes,context){const guidance=buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context);return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyCommanderError(rawMessage,commandName,allowedTypes,context){return guidanceToClassification(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context))}function formatCommanderErrorForJson(rawMessage,commandName,allowedTypes,exitCode,context){return projectJsonErrorGuidance(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context),exitCode)}function formatUnknownErrorForJson(rawMessage,exitCode){const guidance=buildUnknownErrorGuidance(rawMessage);return projectJsonErrorGuidance(guidance,exitCode)}function buildUnknownErrorGuidance(rawMessage){const message=normalizeMessage(rawMessage);return isModuleResolutionErrorMessage(message)?makeGuidanceMessage({code:"module_import_failed",title:"Module import failed",happened:message,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):makeGuidanceMessage({code:"unknown_error",title:"Unhandled error",happened:message,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function classifyUnknownError(rawMessage){return guidanceToClassification(buildUnknownErrorGuidance(rawMessage))}const _testOnly={applyPmCliErrorContext,appendIfMissing,buildCommanderRecoveryPayload,buildFallbackTitleFromMessage,commandExampleForRequiredOption,dedupeStrings,guidanceToClassification,guidanceToJsonEnvelope,normalizeRecoveryPayload,renderList,resolveKnownPackageCommandHint};export{_testOnly,buildLinkedTestQuotedRetryCommand,classifyCommanderError,classifyPmCliError,classifyUnknownError,formatCommanderErrorForDisplay,formatCommanderErrorForJson,formatPmCliErrorForDisplay,formatPmCliErrorForJson,formatUnknownErrorForJson,projectLeanErrorEnvelope,renderGuidanceMessage};
4
4
  //# sourceMappingURL=error-guidance.js.map
@@ -1,7 +1,7 @@
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]="c077f66e-bac4-58af-92cd-a19c30ada04d")}catch{}})();import{Option}from"commander";import{PM_RELOCATED_COMMAND_ALIASES}from"../sdk/cli-contracts/command-aliases.js";import{resolveExtensionFlagValueContract,resolveExtensionLongFlagName}from"../sdk/runtime-primitives.js";function normalizeExtensionCommandPath(commandPath){return commandPath.trim().toLowerCase().split(/\s+/).filter(part=>part.length>0).join(" ")}function buildCanonicalExtensionAliases(handlers,definitions){const aliases=new Map;for(const handler of handlers){const alias=normalizeExtensionCommandPath(handler.command);for(const definition of definitions){if(definition.layer!==handler.layer||definition.name!==handler.name)continue;const canonical=normalizeExtensionCommandPath(definition.command),parts=canonical.split(" "),action=parts.at(-1),suffix=parts.slice(1).join(" "),expectedAlias=suffix?`${parts[0]}-${action} ${suffix}`:`${parts[0]}-${action}`;if(action&&alias===expectedAlias){aliases.set(alias,canonical);break}}}return aliases}function extensionFlagTakesValueForInvocation(invocationArgv,commandName,normalizedMissing,descriptors){if(!commandName||!normalizedMissing)return;let descriptor,matchedTokenCount=0;for(const[index,token]of invocationArgv.entries()){if(token!==commandName)continue;const commandTokens=invocationArgv.slice(index);for(const[path,candidate]of descriptors.entries()){const pathTokens=path.split(" ");pathTokens.length>matchedTokenCount&&pathTokens.every((pathToken,pathIndex)=>commandTokens[pathIndex]===pathToken)&&(descriptor=candidate,matchedTokenCount=pathTokens.length)}}const flag=descriptor?.flags.find(candidate=>candidate.long===normalizedMissing||candidate.short===normalizedMissing);if(flag)return resolveExtensionFlagArity(flag).takesValue}function toNonEmptyFlagString(value){if(typeof value!="string")return null;const trimmed=value.trim();return trimmed.length>0?trimmed:null}function toOptionalBoolean(value){return typeof value=="boolean"?value:void 0}function resolveExtensionFlagArity(definition){const value=resolveExtensionFlagValueContract(definition);return{takesValue:value.value_arity!=="none",valueName:value.value_name}}function formatDynamicExtensionFlagHelpLine(definition){const longName=resolveExtensionLongFlagName(definition.long);if(!longName||!longName.startsWith("--")||longName.length<3)return null;const flags=formatDynamicExtensionOptionFlags(definition);if(!flags)return null;const description=toNonEmptyFlagString(definition.description)??"Extension-provided option.",markers=[];toOptionalBoolean(definition.required)===!0&&markers.push("required"),toOptionalBoolean(definition.enabled)===!1&&markers.push("disabled");const markerSuffix=markers.length>0?` [${markers.join(", ")}]`:"";return`${flags} ${description}${markerSuffix}`}function buildDynamicExtensionFlagHelp(definitions){const lines=[...new Set(definitions.map(formatDynamicExtensionFlagHelpLine).filter(line=>line!==null))].sort((left,right)=>left.localeCompare(right));return lines.length===0?null:`
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]="2624f51e-0100-5f98-8bd9-a30e5a3ad63e")}catch{}})();import{Option}from"commander";import{PM_RELOCATED_COMMAND_ALIASES}from"../sdk/cli-contracts/command-aliases.js";import{resolveExtensionFlagValueContract,resolveExtensionLongFlagName}from"../sdk/runtime-primitives.js";function normalizeExtensionCommandPath(commandPath){return commandPath.trim().toLowerCase().split(/\s+/).filter(part=>part.length>0).join(" ")}function buildCanonicalExtensionAliases(handlers,definitions){const aliases=new Map;for(const handler of handlers){const alias=normalizeExtensionCommandPath(handler.command);for(const definition of definitions){if(definition.layer!==handler.layer||definition.name!==handler.name)continue;const canonical=normalizeExtensionCommandPath(definition.command),parts=canonical.split(" "),action=parts.at(-1),suffix=parts.slice(1).join(" "),expectedAlias=suffix?`${parts[0]}-${action} ${suffix}`:`${parts[0]}-${action}`;if(action&&alias===expectedAlias){aliases.set(alias,canonical);break}}}return aliases}function extensionFlagTakesValueForInvocation(invocationArgv,commandName,normalizedMissing,descriptors){if(!commandName||!normalizedMissing)return;let descriptor,matchedTokenCount=0;for(const[index,token]of invocationArgv.entries()){if(token!==commandName)continue;const commandTokens=invocationArgv.slice(index);for(const[path,candidate]of descriptors.entries()){const pathTokens=path.split(" ");pathTokens.length>matchedTokenCount&&pathTokens.every((pathToken,pathIndex)=>commandTokens[pathIndex]===pathToken)&&(descriptor=candidate,matchedTokenCount=pathTokens.length)}}const flag=descriptor?.flags.find(candidate=>candidate.long===normalizedMissing||candidate.short===normalizedMissing);if(flag)return resolveExtensionFlagArity(flag).takesValue}function toNonEmptyFlagString(value){if(typeof value!="string")return null;const trimmed=value.trim();return trimmed.length>0?trimmed:null}function toOptionalBoolean(value){return typeof value=="boolean"?value:void 0}function resolveExtensionFlagArity(definition){const value=resolveExtensionFlagValueContract(definition);return{takesValue:value.value_arity!=="none",valueName:value.value_name}}function formatDynamicExtensionFlagHelpLine(definition){const longName=resolveExtensionLongFlagName(definition.long);if(!longName||!longName.startsWith("--")||longName.length<3)return null;const flags=formatDynamicExtensionOptionFlags(definition);return flags?`${flags} ${formatDynamicExtensionOptionDescription(definition)}`:null}function buildDynamicExtensionFlagHelp(definitions){const lines=[...new Set(definitions.map(formatDynamicExtensionFlagHelpLine).filter(line=>line!==null))].sort((left,right)=>left.localeCompare(right));return lines.length===0?null:`
2
2
  Extension-provided flags:
3
3
  ${lines.join(`
4
- `)}`}function collectDynamicExtensionFlagHelpByCommand(registrations){const grouped=new Map;for(const registration of registrations){const commandPath=normalizeExtensionCommandPath(registration.target_command);if(commandPath.length===0)continue;const existing=grouped.get(commandPath)??[];existing.push(...registration.flags),grouped.set(commandPath,existing)}const entries=[...grouped.entries()].sort(([left],[right])=>left.localeCompare(right)),helpByCommand=new Map;for(const[commandPath,definitions]of entries){const helpText=buildDynamicExtensionFlagHelp(definitions);helpText&&helpByCommand.set(commandPath,helpText)}return helpByCommand}function normalizeExtensionCommandAction(commandPath,action){return typeof action!="string"||action.trim().length===0?commandPath.replace(/\s+/g,"-"):action.trim().toLowerCase()}function normalizeExtensionCommandStringList(values){if(!Array.isArray(values))return[];const normalized=[],seen=new Set;for(const value of values){if(typeof value!="string")continue;const trimmed=value.trim();trimmed.length===0||seen.has(trimmed)||(seen.add(trimmed),normalized.push(trimmed))}return normalized}function normalizeExtensionCommandArguments(values){return Array.isArray(values)?values.map(value=>{const name=typeof value.name=="string"?value.name.trim():"";if(name.length===0)return null;const normalized={name,required:value.required===!0,variadic:value.variadic===!0};return typeof value.description=="string"&&value.description.trim().length>0&&(normalized.description=value.description.trim()),normalized}).filter(entry=>entry!==null):[]}function collectExtensionDefinitionsByCommand(commandDefinitions){const definitionsByCommand=new Map;for(const definition of commandDefinitions){const commandPath=normalizeExtensionCommandPath(definition.command);if(commandPath.length===0)continue;const description=typeof definition.description=="string"&&definition.description.trim().length>0?definition.description.trim():void 0,intent=typeof definition.intent=="string"&&definition.intent.trim().length>0?definition.intent.trim():void 0;definitionsByCommand.set(commandPath,{command:commandPath,action:normalizeExtensionCommandAction(commandPath,definition.action),description,intent,examples:normalizeExtensionCommandStringList(definition.examples),failure_hints:normalizeExtensionCommandStringList(definition.failure_hints),arguments:normalizeExtensionCommandArguments(definition.arguments),flags:[],tier:definition.tier??"standard",family:definition.family??"extensions",source:{layer:definition.layer,name:definition.name,package:definition.source_package}})}return definitionsByCommand}function collectExtensionFlagsByCommand(flagRegistrations){const flagsByCommand=new Map;for(const registration of flagRegistrations){const commandPath=normalizeExtensionCommandPath(registration.target_command);if(commandPath.length===0)continue;const existing=flagsByCommand.get(commandPath)??[];existing.push(...registration.flags),flagsByCommand.set(commandPath,existing)}return flagsByCommand}function collectExtensionHelpCommandSet(commandHandlers,definitionsByCommand,flagsByCommand){const commandSet=new Set;for(const commandPath of commandHandlers){const normalized=normalizeExtensionCommandPath(commandPath);normalized.length>0&&commandSet.add(normalized)}for(const commandPath of definitionsByCommand.keys())commandSet.add(commandPath);for(const commandPath of flagsByCommand.keys())commandSet.add(commandPath);return commandSet}function resolveFlattenedAliasDescriptor(commandPath,definitionsByCommand,canonicalAliases){const canonical=canonicalAliases.get(commandPath);return canonical?definitionsByCommand.get(canonical):void 0}function collectExtensionCommandHelpDescriptors(commandHandlers,commandDefinitions,flagRegistrations,canonicalAliases=new Map){const definitionsByCommand=collectExtensionDefinitionsByCommand(commandDefinitions),flagsByCommand=collectExtensionFlagsByCommand(flagRegistrations),commandSet=collectExtensionHelpCommandSet(commandHandlers,definitionsByCommand,flagsByCommand),descriptors=new Map,sortedCommands=[...commandSet].sort((left,right)=>left.localeCompare(right));for(const commandPath of sortedCommands){const definition=resolveFlattenedAliasDescriptor(commandPath,definitionsByCommand,canonicalAliases)??definitionsByCommand.get(commandPath),flags=flagsByCommand.get(commandPath)??(definition?flagsByCommand.get(definition.command):void 0)??[];if(definition){descriptors.set(commandPath,{...definition,command:commandPath,flags});continue}descriptors.set(commandPath,{command:commandPath,action:normalizeExtensionCommandAction(commandPath,void 0),examples:[],failure_hints:[],arguments:[],flags,tier:"standard",family:"extensions"})}return descriptors}function buildExtensionArgumentToken(argument){const variadicSuffix=argument.variadic?"...":"";return argument.required?`<${argument.name}${variadicSuffix}>`:`[${argument.name}${variadicSuffix}]`}function applyDynamicExtensionArguments(command,descriptor){for(const argument of descriptor.arguments)command.argument(buildExtensionArgumentToken(argument),argument.description??"Extension argument.")}function normalizeDynamicExtensionOptionNames(definition){if(toOptionalBoolean(definition.visible)===!1)return null;const longName=resolveExtensionLongFlagName(definition.long),shortName=toNonEmptyFlagString(definition.short),normalizedShort=shortName&&shortName.startsWith("-")&&!shortName.startsWith("--")?shortName:null,normalizedLong=longName&&longName.startsWith("--")&&longName.length>2?longName:null,optionNames=[normalizedShort,normalizedLong].filter(entry=>entry!==null);return optionNames.length>0?optionNames:null}function formatDynamicExtensionOptionFlags(definition){const optionNames=normalizeDynamicExtensionOptionNames(definition);if(!optionNames)return null;const{value_name:valueName,value_arity:arity}=resolveExtensionFlagValueContract(definition),optionValueSuffix=valueName?arity==="optional"?` [${valueName}]`:` <${valueName}>`:"";return`${optionNames.join(", ")}${optionValueSuffix}`}function formatDynamicExtensionParseOptionFlags(definition){return formatDynamicExtensionOptionFlags(definition)}function formatDynamicExtensionOptionDescription(definition){const description=toNonEmptyFlagString(definition.description)??"Extension-provided option.",markers=[];toOptionalBoolean(definition.required)===!0&&markers.push("required"),toOptionalBoolean(definition.enabled)===!1&&markers.push("disabled");const markerSuffix=markers.length>0?` [${markers.join(", ")}]`:"";return`${description}${markerSuffix}`}function commandAlreadyHasOption(command,definition){const longName=resolveExtensionLongFlagName(definition.long),shortName=toNonEmptyFlagString(definition.short);return command.options.some(option=>{const optionWithNames=option;return longName!==null&&optionWithNames.long===longName||shortName!==null&&optionWithNames.short===shortName})}function applyDynamicExtensionFlagOptions(command,definitions){for(const definition of definitions){if(commandAlreadyHasOption(command,definition))continue;const flags=formatDynamicExtensionParseOptionFlags(definition);if(!flags)continue;const description=formatDynamicExtensionOptionDescription(definition),option=new Option(flags,description);if(option.negate=!1,definition.list!==!0){command.addOption(option);continue}command.addOption(option.argParser((value,previous=[])=>[...Array.isArray(previous)?previous:[previous],value]))}}function buildResidualDynamicExtensionFlagHelp(command,definitions){return buildDynamicExtensionFlagHelp(definitions.filter(definition=>!commandAlreadyHasOption(command,definition)))}function buildDynamicExtensionHelpOptionSummary(definition){const flags=formatDynamicExtensionOptionFlags(definition);if(!flags)return null;const longName=resolveExtensionLongFlagName(definition.long),shortName=toNonEmptyFlagString(definition.short),normalizedLong=longName&&longName.startsWith("--")&&longName.length>2?longName:null,normalizedShort=shortName&&shortName.startsWith("-")&&!shortName.startsWith("--")?shortName:null,value=resolveExtensionFlagValueContract(definition),required=toOptionalBoolean(definition.required)===!0;return{flags,long:normalizedLong,short:normalizedShort,description:formatDynamicExtensionOptionDescription(definition),takes_value:value.value_arity!=="none",value_required:value.value_arity==="required",value_name:value.value_name,variadic:!1,required,aliases:[],alias_for:null}}function buildDynamicExtensionHelpOptionSummaries(descriptor){if(!descriptor)return[];const summaries=[],seen=new Set;for(const definition of descriptor.flags){const summary=buildDynamicExtensionHelpOptionSummary(definition);!summary||seen.has(summary.flags)||(seen.add(summary.flags),summaries.push(summary))}return summaries}function mergeHelpOptionSummaries(base,extension){if(extension.length===0)return base;const merged=[...base],seen=new Set(base.map(entry=>entry.flags));for(const entry of extension)seen.has(entry.flags)||(seen.add(entry.flags),merged.push(entry));return merged}function buildDynamicExtensionCommandMetadataHelp(descriptor){const lines=[];if(descriptor.intent&&lines.push(`Intent: ${descriptor.intent}`),descriptor.action&&lines.push(`Action contract: ${descriptor.action}`),descriptor.examples.length>0){lines.push("Examples:");for(const example of descriptor.examples)lines.push(` - ${example}`)}if(descriptor.failure_hints.length>0){lines.push("Common failure hints:");for(const hint of descriptor.failure_hints)lines.push(` - ${hint}`)}return lines.length===0?null:`
4
+ `)}`}function collectDynamicExtensionFlagHelpByCommand(registrations){const grouped=new Map;for(const registration of registrations){const commandPath=normalizeExtensionCommandPath(registration.target_command);if(commandPath.length===0)continue;const existing=grouped.get(commandPath)??[];existing.push(...registration.flags),grouped.set(commandPath,existing)}const entries=[...grouped.entries()].sort(([left],[right])=>left.localeCompare(right)),helpByCommand=new Map;for(const[commandPath,definitions]of entries){const helpText=buildDynamicExtensionFlagHelp(definitions);helpText&&helpByCommand.set(commandPath,helpText)}return helpByCommand}function normalizeExtensionCommandAction(commandPath,action){return typeof action!="string"||action.trim().length===0?commandPath.replace(/\s+/g,"-"):action.trim().toLowerCase()}function normalizeExtensionCommandStringList(values){if(!Array.isArray(values))return[];const normalized=[],seen=new Set;for(const value of values){if(typeof value!="string")continue;const trimmed=value.trim();trimmed.length===0||seen.has(trimmed)||(seen.add(trimmed),normalized.push(trimmed))}return normalized}function normalizeExtensionCommandArguments(values){return Array.isArray(values)?values.map(value=>{const name=typeof value.name=="string"?value.name.trim():"";if(name.length===0)return null;const normalized={name,required:value.required===!0,variadic:value.variadic===!0};return typeof value.description=="string"&&value.description.trim().length>0&&(normalized.description=value.description.trim()),normalized}).filter(entry=>entry!==null):[]}function collectExtensionDefinitionsByCommand(commandDefinitions){const definitionsByCommand=new Map;for(const definition of commandDefinitions){const commandPath=normalizeExtensionCommandPath(definition.command);if(commandPath.length===0)continue;const description=typeof definition.description=="string"&&definition.description.trim().length>0?definition.description.trim():void 0,intent=typeof definition.intent=="string"&&definition.intent.trim().length>0?definition.intent.trim():void 0;definitionsByCommand.set(commandPath,{command:commandPath,action:normalizeExtensionCommandAction(commandPath,definition.action),description,intent,examples:normalizeExtensionCommandStringList(definition.examples),failure_hints:normalizeExtensionCommandStringList(definition.failure_hints),arguments:normalizeExtensionCommandArguments(definition.arguments),flags:[],tier:definition.tier??"standard",family:definition.family??"extensions",source:{layer:definition.layer,name:definition.name,package:definition.source_package}})}return definitionsByCommand}function collectExtensionFlagsByCommand(flagRegistrations){const flagsByCommand=new Map;for(const registration of flagRegistrations){const commandPath=normalizeExtensionCommandPath(registration.target_command);if(commandPath.length===0)continue;const existing=flagsByCommand.get(commandPath)??[];existing.push(...registration.flags),flagsByCommand.set(commandPath,existing)}return flagsByCommand}function collectExtensionHelpCommandSet(commandHandlers,definitionsByCommand,flagsByCommand){const commandSet=new Set;for(const commandPath of commandHandlers){const normalized=normalizeExtensionCommandPath(commandPath);normalized.length>0&&commandSet.add(normalized)}for(const commandPath of definitionsByCommand.keys())commandSet.add(commandPath);for(const commandPath of flagsByCommand.keys())commandSet.add(commandPath);return commandSet}function resolveFlattenedAliasDescriptor(commandPath,definitionsByCommand,canonicalAliases){const canonical=canonicalAliases.get(commandPath);return canonical?definitionsByCommand.get(canonical):void 0}function collectExtensionCommandHelpDescriptors(commandHandlers,commandDefinitions,flagRegistrations,canonicalAliases=new Map){const definitionsByCommand=collectExtensionDefinitionsByCommand(commandDefinitions),flagsByCommand=collectExtensionFlagsByCommand(flagRegistrations),commandSet=collectExtensionHelpCommandSet(commandHandlers,definitionsByCommand,flagsByCommand),descriptors=new Map,sortedCommands=[...commandSet].sort((left,right)=>left.localeCompare(right));for(const commandPath of sortedCommands){const definition=resolveFlattenedAliasDescriptor(commandPath,definitionsByCommand,canonicalAliases)??definitionsByCommand.get(commandPath),flags=flagsByCommand.get(commandPath)??(definition?flagsByCommand.get(definition.command):void 0)??[];if(definition){descriptors.set(commandPath,{...definition,command:commandPath,flags});continue}descriptors.set(commandPath,{command:commandPath,action:normalizeExtensionCommandAction(commandPath,void 0),examples:[],failure_hints:[],arguments:[],flags,tier:"standard",family:"extensions"})}return descriptors}function buildExtensionArgumentToken(argument){const variadicSuffix=argument.variadic?"...":"";return argument.required?`<${argument.name}${variadicSuffix}>`:`[${argument.name}${variadicSuffix}]`}function applyDynamicExtensionArguments(command,descriptor){for(const argument of descriptor.arguments)command.argument(buildExtensionArgumentToken(argument),argument.description??"Extension argument.")}function normalizeDynamicExtensionOptionNames(definition){if(toOptionalBoolean(definition.visible)===!1)return null;const longName=resolveExtensionLongFlagName(definition.long),shortName=toNonEmptyFlagString(definition.short),normalizedShort=shortName&&shortName.startsWith("-")&&!shortName.startsWith("--")?shortName:null,normalizedLong=longName&&longName.startsWith("--")&&longName.length>2?longName:null,optionNames=[normalizedShort,normalizedLong].filter(entry=>entry!==null);return optionNames.length>0?optionNames:null}function formatDynamicExtensionOptionFlags(definition){const optionNames=normalizeDynamicExtensionOptionNames(definition);if(!optionNames)return null;const{value_name:valueName,value_arity:arity}=resolveExtensionFlagValueContract(definition),optionValueSuffix=valueName?arity==="optional"?` [${valueName}]`:` <${valueName}>`:"";return`${optionNames.join(", ")}${optionValueSuffix}`}function formatDynamicExtensionParseOptionFlags(definition){return formatDynamicExtensionOptionFlags(definition)}function formatDynamicExtensionOptionDescription(definition){const description=toNonEmptyFlagString(definition.description)??"Extension-provided option.",markers=[];toOptionalBoolean(definition.required)===!0&&markers.push("required"),toOptionalBoolean(definition.enabled)===!1&&markers.push("disabled");const markerSuffix=markers.length>0?` [${markers.join(", ")}]`:"",defaultSuffix=definition.default!==void 0?` (default: ${JSON.stringify(definition.default)})`:"";return`${description}${markerSuffix}${defaultSuffix}`}function commandAlreadyHasOption(command,definition){const longName=resolveExtensionLongFlagName(definition.long),shortName=toNonEmptyFlagString(definition.short);return command.options.some(option=>{const optionWithNames=option;return longName!==null&&optionWithNames.long===longName||shortName!==null&&optionWithNames.short===shortName})}function applyDynamicExtensionFlagOptions(command,definitions){for(const definition of definitions){if(commandAlreadyHasOption(command,definition))continue;const flags=formatDynamicExtensionParseOptionFlags(definition);if(!flags)continue;const description=formatDynamicExtensionOptionDescription(definition),option=new Option(flags,description);if(option.negate=!1,definition.list!==!0){command.addOption(option);continue}command.addOption(option.argParser((value,previous=[])=>[...Array.isArray(previous)?previous:[previous],value]))}}function buildResidualDynamicExtensionFlagHelp(command,definitions){return buildDynamicExtensionFlagHelp(definitions.filter(definition=>!commandAlreadyHasOption(command,definition)))}function buildDynamicExtensionHelpOptionSummary(definition){const flags=formatDynamicExtensionOptionFlags(definition);if(!flags)return null;const longName=resolveExtensionLongFlagName(definition.long),shortName=toNonEmptyFlagString(definition.short),normalizedLong=longName&&longName.startsWith("--")&&longName.length>2?longName:null,normalizedShort=shortName&&shortName.startsWith("-")&&!shortName.startsWith("--")?shortName:null,value=resolveExtensionFlagValueContract(definition),required=toOptionalBoolean(definition.required)===!0;return{flags,long:normalizedLong,short:normalizedShort,description:formatDynamicExtensionOptionDescription(definition),takes_value:value.value_arity!=="none",value_required:value.value_arity==="required",value_name:value.value_name,variadic:!1,required,aliases:[],alias_for:null,...definition.default!==void 0?{default_value:definition.default}:{}}}function buildDynamicExtensionHelpOptionSummaries(descriptor){if(!descriptor)return[];const summaries=[],seen=new Set;for(const definition of descriptor.flags){const summary=buildDynamicExtensionHelpOptionSummary(definition);!summary||seen.has(summary.flags)||(seen.add(summary.flags),summaries.push(summary))}return summaries}function mergeHelpOptionSummaries(base,extension){if(extension.length===0)return base;const merged=new Map(base.map(entry=>[entry.flags,entry]));for(const entry of extension){const existing=merged.get(entry.flags);merged.set(entry.flags,existing?{...existing,...entry.default_value!==void 0?{default_value:entry.default_value}:{}}:entry)}return[...merged.values()]}function buildDynamicExtensionCommandMetadataHelp(descriptor){const lines=[];if(descriptor.intent&&lines.push(`Intent: ${descriptor.intent}`),descriptor.action&&lines.push(`Action contract: ${descriptor.action}`),descriptor.examples.length>0){lines.push("Examples:");for(const example of descriptor.examples)lines.push(` - ${example}`)}if(descriptor.failure_hints.length>0){lines.push("Common failure hints:");for(const hint of descriptor.failure_hints)lines.push(` - ${hint}`)}return lines.length===0?null:`
5
5
  Extension command metadata:
6
6
  ${lines.join(`
7
7
  `)}`}function commandAliases(command){const commandRecord=command;if(typeof commandRecord.aliases=="function")return commandRecord.aliases().map(value=>value.trim().toLowerCase()).filter(value=>value.length>0);if(typeof commandRecord.alias=="function"){const alias=commandRecord.alias();if(typeof alias=="string"&&alias.trim().length>0)return[alias.trim().toLowerCase()]}return Array.isArray(commandRecord._aliases)?commandRecord._aliases.map(value=>value.trim().toLowerCase()).filter(value=>value.length>0):[]}function findDirectChildCommand(parent,name){const normalizedTarget=name.trim().toLowerCase();return parent.commands.find(entry=>entry.name().trim().toLowerCase()===normalizedTarget?!0:commandAliases(entry).includes(normalizedTarget))??null}function findCommandByPath(root,pathParts){let current=root;for(const part of pathParts){const next=findDirectChildCommand(current,part);if(!next)return null;current=next}return current}const extensionCreatedCommands=new WeakSet;function ensureCommandPath(root,pathParts){if(pathParts.length===0)return null;let current=root;for(let index=0;index<pathParts.length;index+=1){const part=pathParts[index];index>0&&PM_RELOCATED_COMMAND_ALIASES.some(entry=>entry.canonical===pathParts.join(" "))&&current.enablePositionalOptions();const existing=findDirectChildCommand(current,part);if(existing){current=existing;continue}const created=current.command(part);extensionCreatedCommands.add(created),index<pathParts.length-1?(created.description("Extension-provided command group."),created.action(()=>{created.help()})):created.description("Extension-provided command path."),current=created}return current}function findExtensionCommandPathCollision(root,pathParts){const extensionPath=pathParts.join(" "),reservedLeaf=PM_RELOCATED_COMMAND_ALIASES.find(entry=>extensionPath===entry.canonical||extensionPath.startsWith(`${entry.canonical} `));if(reservedLeaf)return{core_path:reservedLeaf.canonical,extension_path:extensionPath};let current=root;const traversed=[];for(const part of pathParts){const existing=findDirectChildCommand(current,part);if(!existing)return null;traversed.push(part);const isGroup=existing.commands.length>0||PM_RELOCATED_COMMAND_ALIASES.some(entry=>entry.canonical.startsWith(`${traversed.join(" ")} `));if(!extensionCreatedCommands.has(existing)&&(traversed.length===pathParts.length||!isGroup))return{core_path:traversed.join(" "),extension_path:pathParts.join(" ")};current=existing}return null}function buildExtensionCommandCollisionWarning(root,commandPath,aliases,descriptor,hasHandler=!1){const pathParts=commandPath.split(" ").filter(part=>part.length>0),collision=findExtensionCommandPathCollision(root,pathParts),existingCommand=findCommandByPath(root,pathParts),declaredFacet=PM_RELOCATED_COMMAND_ALIASES.some(alias=>alias.canonical===commandPath&&alias.alias===descriptor?.action&&!root.commands.some(command=>command.name()===alias.alias)&&(existingCommand===null||extensionCreatedCommands.has(existingCommand)));if(!collision||collision.core_path===commandPath&&existingCommand!==null&&!aliases.has(commandPath)&&!hasHandler||declaredFacet&&!aliases.has(commandPath))return null;const extensionOwner=descriptor?.source?.package??descriptor?.source?.name??"unknown-extension";return`extension_command_collision:${collision.extension_path}:core_owner=pm-cli:${collision.core_path}:extension_owner=${extensionOwner}`}function collectSafeExtensionCommandPaths(root,commandHandlers,descriptors,aliases,onCollision){return[...new Set([...commandHandlers,...descriptors.keys()])].filter(commandPath=>commandPath.trim().length>0).sort((left,right)=>left.localeCompare(right)).filter(commandPath=>{const warning=buildExtensionCommandCollisionWarning(root,commandPath,aliases,descriptors.get(commandPath),commandHandlers.includes(commandPath));return warning?(onCollision(warning),!aliases.has(commandPath)&&findCommandByPath(root,commandPath.split(" "))!==null):!0})}function reportExtensionCommandCollision(activationWarnings,report,warning){activationWarnings.push(warning),report(`[pm] warning: ${warning}; core command preserved. Rename or namespace the extension command alias.`)}export{applyDynamicExtensionArguments,applyDynamicExtensionFlagOptions,buildCanonicalExtensionAliases,buildDynamicExtensionCommandMetadataHelp,buildDynamicExtensionHelpOptionSummaries,buildExtensionCommandCollisionWarning,buildResidualDynamicExtensionFlagHelp,collectDynamicExtensionFlagHelpByCommand,collectExtensionCommandHelpDescriptors,collectSafeExtensionCommandPaths,commandAliases,ensureCommandPath,extensionFlagTakesValueForInvocation,findCommandByPath,findDirectChildCommand,findExtensionCommandPathCollision,mergeHelpOptionSummaries,normalizeExtensionCommandPath,reportExtensionCommandCollision,resolveExtensionFlagArity};
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a51d6d75-0f11-5bdf-a384-2ca10ef064ef")}catch{}})();import{EXIT_CODE,PmCliError}from"../sdk/runtime-primitives.js";import{runActivity}from"./commands/history/activity.js";import{collect,getGlobalOptions,normalizeActivityOptions,printActivityJsonStream,printError,printResult,resolveActivityStreamMode}from"./registration-helpers.js";async function runActivityAction(options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now();if([options.raw,options.compact,options.full,options.provenance].filter(value=>value===!0).length>1)throw new PmCliError("Activity projection options are mutually exclusive. Use --raw, --compact, --provenance, or --full.",EXIT_CODE.USAGE);const streamMode=resolveActivityStreamMode(options.stream);if(streamMode&&!globalOptions.json)throw new PmCliError("--stream requires --json output mode.",EXIT_CODE.USAGE);const normalized=normalizeActivityOptions(options),result=await runActivity(streamMode&&options.full!==!0&&options.provenance!==!0?{...normalized,raw:!0,compact:!0}:normalized,globalOptions);streamMode?printActivityJsonStream(result,normalized,globalOptions):printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=activity took_ms=${Date.now()-startedAt}`)}function registerHistoryActivityCommand(command){command.option("--id <value>","Filter by item ID").option("--op <value>","Filter by history operation").option("--author <value>","Filter by history author").option("--from <value>","Lower timestamp bound (ISO/date string or relative)").option("--to <value>","Upper timestamp bound (ISO/date string or relative)").option("--limit <n>","Return only the latest n activity entries").option("--unbounded","Explicitly return every matching activity entry (disables the default bound)").option("--compact","Condensed output: show only id, op, ts, author, msg per entry").option("--raw","Show the legacy compact per-event stream instead of the item digest").option("--full","Show full activity entries with JSON Patch payloads").option("--provenance","Show patch-free author, harness, instance, and extensible provenance").option("--provenance-summary","Include bounded provenance completeness counts").option("--harness <value>","Filter by recorded or vocabulary-resolved harness (repeatable)",collect).option("--agent-instance <value>","Filter by privacy-safe agent instance (repeatable)",collect).option("--provenance-filter <dimension=value>","Filter by an exact declared provenance value (repeatable)",collect).option("--stream [mode]","Emit line-delimited JSON rows (requires --json). Optional mode: rows|ndjson|jsonl").description("Show recent activity across items.").action(runActivityAction)}export{registerHistoryActivityCommand};
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]="69ca287f-eeb9-5e65-a3ba-be47ab223c04")}catch{}})();import{EXIT_CODE,PmCliError}from"../sdk/runtime-primitives.js";import{runActivity}from"./commands/history/activity.js";import{collect,getGlobalOptions,normalizeActivityOptions,printActivityJsonStream,printError,printResult,resolveActivityStreamMode}from"./registration-helpers.js";async function runActivityAction(options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now();if([options.raw,options.compact,options.full,options.provenance].filter(value=>value===!0).length>1)throw new PmCliError("Activity projection options are mutually exclusive. Use --raw, --compact, --provenance, or --full.",EXIT_CODE.USAGE);const streamMode=resolveActivityStreamMode(options.stream);if(streamMode&&!globalOptions.json)throw new PmCliError("--stream requires --json output mode.",EXIT_CODE.USAGE);const normalized=normalizeActivityOptions(options),result=await runActivity(streamMode&&options.full!==!0&&options.provenance!==!0?{...normalized,raw:!0,compact:!0}:normalized,globalOptions);streamMode?printActivityJsonStream(result,normalized,globalOptions):printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=activity took_ms=${Date.now()-startedAt}`)}function registerHistoryActivityCommand(command){command.option("--id <value>","Filter by item ID").option("--op <value>","Filter by history operation").option("--author <value>","Filter by history author").option("--from <value>","Inclusive lower time bound (ISO or relative)").option("--to <value>","Exclusive upper time bound (ISO or relative)").option("--limit <n>","Maximum activity rows").option("--after <cursor>","Continue a fixed-window page").option("--unbounded","Return every matching row").option("--compact","Show compact event rows").option("--raw","Show the legacy compact per-event stream instead of the item digest").option("--full","Show full activity entries with JSON Patch payloads").option("--provenance","Show patch-free author, harness, instance, and extensible provenance").option("--provenance-summary","Include provenance counts").option("--harness <value>","Filter by harness (repeatable)",collect).option("--agent-instance <value>","Filter by agent instance (repeatable)",collect).option("--provenance-filter <dimension=value>","Filter exact provenance values (repeatable)",collect).option("--stream [mode]","Emit line-delimited JSON rows (requires --json): rows|ndjson|jsonl").description("Show recent activity across items.").action(runActivityAction)}export{registerHistoryActivityCommand};
2
2
  //# sourceMappingURL=register-history-activity.js.map