@unbrained/pm-cli 2026.10.25 → 2026.10.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +44 -1
  3. package/dist/cli/error-guidance.d.ts +5 -0
  4. package/dist/cli/error-guidance.js +2 -2
  5. package/dist/cli/register-list-query.js +5 -5
  6. package/dist/cli/register-mutation.js +2 -2
  7. package/dist/cli-bundle/bundle-manifest.json +1 -1
  8. package/dist/cli-bundle/chunks/{chunk-O3ZTGRIH.js → chunk-25MTQAHX.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-YCCGZHOR.js → chunk-2XUDAQK5.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-VAEB6IUQ.js → chunk-32QK43XG.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-RD6UW3MW.js → chunk-34OQP43K.js} +3 -3
  12. package/dist/cli-bundle/chunks/{chunk-TLMXSYJA.js → chunk-57YPOOED.js} +2 -2
  13. package/dist/cli-bundle/chunks/chunk-5PTMQBKJ.js +30 -0
  14. package/dist/cli-bundle/chunks/{chunk-FNZT4BTE.js → chunk-EKV5GP6P.js} +86 -86
  15. package/dist/cli-bundle/chunks/{chunk-LNKPH2DD.js → chunk-ER7RLJW5.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-F26MRQZY.js +6 -0
  17. package/dist/cli-bundle/chunks/chunk-H434DKYU.js +2 -0
  18. package/dist/cli-bundle/chunks/{chunk-MVJGGCGQ.js → chunk-HIX2OMEZ.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-4GD6QOP6.js → chunk-NNIYQHYT.js} +3 -3
  20. package/dist/cli-bundle/chunks/chunk-O3LPT34G.js +20 -0
  21. package/dist/cli-bundle/chunks/{chunk-3CYXE6BV.js → chunk-ONC4BBQP.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-UI3FD3DW.js → chunk-OQOEBWHU.js} +2 -2
  23. package/dist/cli-bundle/chunks/chunk-Q55KZDNF.js +2 -0
  24. package/dist/cli-bundle/chunks/chunk-QQYLNHZK.js +128 -0
  25. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +2 -0
  26. package/dist/cli-bundle/chunks/chunk-UHKN6TJM.js +114 -0
  27. package/dist/cli-bundle/chunks/{chunk-7T3H24HN.js → chunk-X5TMR7KC.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-EYCVAAIP.js → chunk-XERBUA6A.js} +2 -2
  29. package/dist/cli-bundle/chunks/indexed-receipt-blobs-63WYG2PY.js +4 -0
  30. package/dist/cli-bundle/chunks/{mutation-admission-747C6IUR.js → mutation-admission-L3A6FSZ7.js} +2 -2
  31. package/dist/cli-bundle/chunks/{register-list-query-COST6KRV.js → register-list-query-YSQ7UTFI.js} +9 -9
  32. package/dist/cli-bundle/chunks/register-mutation-6HRXYASW.js +20 -0
  33. package/dist/cli-bundle/chunks/{register-operations-S4LKLUBJ.js → register-operations-4O3YOYXF.js} +2 -2
  34. package/dist/cli-bundle/chunks/{register-setup-3ITZXPOL.js → register-setup-3WAXNDMY.js} +2 -2
  35. package/dist/cli-bundle/chunks/{settlement-hook-5IVCF6ZY.js → settlement-hook-CRW6PVQK.js} +2 -2
  36. package/dist/cli-bundle/chunks/{stage-3UUIYROS.js → stage-I46WD4EN.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-U6HXIF6G.js → chunk-4TXZBGOR.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-22727JYL.js → chunk-B266DDBJ.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-Y4JHHY24.js → chunk-BH7RE2ZY.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-ZYCOMRFT.js → chunk-E5C24MCV.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/chunk-HWD63G54.js +2 -0
  43. package/dist/cli-bundle/focused-chunks/chunk-J67PFM3O.js +91 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-46KDJH3K.js → chunk-KTXU5WU6.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/chunk-MVY6JDIH.js +12 -0
  46. package/dist/cli-bundle/focused-chunks/{chunk-NC5HUGHU.js → chunk-NLZUI234.js} +4 -4
  47. package/dist/cli-bundle/focused-chunks/{chunk-B5JOVH5F.js → chunk-R2MTHS2H.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/chunk-SM2KGD4J.js +79 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-HMYDUEQK.js → chunk-SYL73MEI.js} +3 -3
  50. package/dist/cli-bundle/focused-chunks/{chunk-77NU7NPN.js → chunk-TAFMNTA5.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-74KC7FUQ.js → chunk-TGUOEOKP.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-U4UBQBS7.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-URWYYJ7K.js → chunk-WDKZB3V6.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-XK3XMZM4.js +2 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-3M5FZCMC.js → chunk-Y57A4ZDI.js} +55 -55
  56. package/dist/cli-bundle/focused-chunks/chunk-YC6NCPLK.js +22 -0
  57. package/dist/cli-bundle/focused-chunks/{chunk-7DEZT4JN.js → chunk-YQKLKRMW.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-3FM75SBJ.js → chunk-YW5GHQN2.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/chunk-ZA6AEYIM.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-ZH7GTEWL.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-GAFC52LQ.js +4 -0
  62. package/dist/cli-bundle/focused-chunks/{mutation-admission-BQBQXILV.js → mutation-admission-ENBFMV2X.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{settlement-hook-XVS6P2XI.js → settlement-hook-PUYJJDFL.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{stage-VSIL4MTZ.js → stage-MAWZTM2H.js} +2 -2
  65. package/dist/cli-bundle/main.js +4 -4
  66. package/dist/cli-bundle/sdk-authoring.js +1 -1
  67. package/dist/cli-bundle/sdk-contracts.js +2 -2
  68. package/dist/cli-bundle/sdk-core.js +33 -33
  69. package/dist/cli-bundle/sdk-governance.js +1 -1
  70. package/dist/cli-bundle/sdk-graph.js +1 -1
  71. package/dist/cli-bundle/sdk-merge.js +57 -57
  72. package/dist/cli-bundle/sdk-query.js +1 -1
  73. package/dist/cli-bundle/sdk-runtime.js +1 -1
  74. package/dist/cli-bundle/sdk-testing.js +1 -1
  75. package/dist/cli-bundle/sdk.js +9 -9
  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/history/event-index.d.ts +6 -0
  79. package/dist/core/history/event-index.js +7 -6
  80. package/dist/core/history/read.d.ts +3 -1
  81. package/dist/core/history/read.js +1 -1
  82. package/dist/core/output/mutation-projection.js +1 -1
  83. package/dist/core/policy/workflow-policy-store.js +1 -1
  84. package/dist/core/shared/errors.d.ts +9 -0
  85. package/dist/core/shared/errors.js +1 -1
  86. package/dist/core/shared/secret-rules.d.ts +17 -0
  87. package/dist/core/shared/secret-rules.js +2 -1
  88. package/dist/core/store/item-mutation-precondition.d.ts +8 -0
  89. package/dist/core/store/item-mutation-precondition.js +1 -1
  90. package/dist/core/store/item-store.js +1 -1
  91. package/dist/mcp/tool-definitions.js +1 -1
  92. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  93. package/dist/sdk/cli-contracts/completeness.js +1 -1
  94. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  95. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  96. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  97. package/dist/sdk/cli-contracts/registration-helpers.d.ts +1 -1
  98. package/dist/sdk/cli-contracts/registration-helpers.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/context-signal-store.js +2 -2
  105. package/dist/sdk/core.d.ts +1 -1
  106. package/dist/sdk/core.js +1 -1
  107. package/dist/sdk/extension-command-context.js +2 -2
  108. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  109. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  110. package/dist/sdk/index.d.ts +2 -1
  111. package/dist/sdk/index.js +1 -1
  112. package/dist/sdk/item-transaction.js +1 -1
  113. package/dist/sdk/lifecycle/close-many.d.ts +3 -0
  114. package/dist/sdk/lifecycle/close-many.js +1 -1
  115. package/dist/sdk/lifecycle/close.d.ts +3 -1
  116. package/dist/sdk/lifecycle/close.js +1 -1
  117. package/dist/sdk/lifecycle/create.d.ts +2 -0
  118. package/dist/sdk/lifecycle/create.js +1 -1
  119. package/dist/sdk/lifecycle/plan.d.ts +2 -0
  120. package/dist/sdk/lifecycle/plan.js +1 -1
  121. package/dist/sdk/lifecycle/restore.js +1 -1
  122. package/dist/sdk/lifecycle-policy.d.ts +11 -0
  123. package/dist/sdk/lifecycle-policy.js +1 -1
  124. package/dist/sdk/merge/indexed-receipt-blobs.d.ts +3 -1
  125. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  126. package/dist/sdk/merge/receipt-file-boundary.d.ts +2 -0
  127. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  128. package/dist/sdk/merge/receipts.js +2 -2
  129. package/dist/sdk/mutation-events.d.ts +6 -0
  130. package/dist/sdk/mutation-events.js +1 -1
  131. package/dist/sdk/mutation-guard.d.ts +6 -1
  132. package/dist/sdk/mutation-guard.js +1 -1
  133. package/dist/sdk/output/fit-envelope.d.ts +98 -0
  134. package/dist/sdk/output/fit-envelope.js +2 -0
  135. package/dist/sdk/public-surface.json +1 -1
  136. package/dist/sdk/query.d.ts +1 -0
  137. package/dist/sdk/query.js +1 -1
  138. package/dist/sdk/read-output-session.d.ts +1 -1
  139. package/dist/sdk/read-output-session.js +1 -1
  140. package/dist/sdk/runtime-extended-actions.js +1 -1
  141. package/dist/sdk/runtime-input.js +1 -1
  142. package/dist/sdk/runtime-primitives.d.ts +1 -1
  143. package/dist/sdk/runtime-primitives.js +1 -1
  144. package/dist/sdk/runtime.d.ts +2 -2
  145. package/dist/sdk/runtime.js +1 -1
  146. package/dist/sdk/scheduling-shortcuts.d.ts +2 -0
  147. package/dist/sdk/scheduling-shortcuts.js +1 -1
  148. package/dist/sdk/test/execution.js +2 -2
  149. package/dist/sdk/test/receipt-index-snapshot.d.ts +2 -0
  150. package/dist/sdk/test/receipt-index-snapshot.js +2 -0
  151. package/dist/sdk/test/workspace-snapshot.d.ts +1 -1
  152. package/dist/sdk/test/workspace-snapshot.js +1 -1
  153. package/dist/sdk/workspace-transaction.d.ts +3 -1
  154. package/dist/sdk/workspace-transaction.js +2 -2
  155. package/docs/COMMANDS.md +2 -1
  156. package/docs/MUTATION_INTEGRITY.md +33 -0
  157. package/docs/PERFORMANCE.md +21 -6
  158. package/docs/QUALITY_EVIDENCE.md +9 -0
  159. package/docs/READ_OUTPUT_CONTRACTS.md +55 -1
  160. package/docs/RELEASING.md +11 -0
  161. package/docs/SDK.md +88 -6
  162. package/docs/SDK_CONTEXT_COORDINATION.md +35 -4
  163. package/docs/TESTING.md +14 -1
  164. package/docs/WORKFLOW_POLICIES.md +14 -1
  165. package/docs/agent-task-token-baseline.json +1 -1
  166. package/docs/agent-task-transcripts.json +1 -1
  167. package/docs/generated/FLAG_LEXICON_BUDGETS.md +4 -4
  168. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +5 -3
  169. package/marketplace.json +1 -1
  170. package/package.json +1 -1
  171. package/packages/pm-beads/package.json +1 -1
  172. package/packages/pm-calendar/extensions/calendar/shortcuts.ts +2 -2
  173. package/packages/pm-calendar/package.json +1 -1
  174. package/packages/pm-command-kit/package.json +1 -1
  175. package/packages/pm-digital-twin/package.json +1 -1
  176. package/packages/pm-governance-audit/package.json +1 -1
  177. package/packages/pm-guide-shell/package.json +1 -1
  178. package/packages/pm-kanban/package.json +1 -1
  179. package/packages/pm-lifecycle-hooks/package.json +1 -1
  180. package/packages/pm-linked-test-adapters/package.json +1 -1
  181. package/packages/pm-search-advanced/package.json +1 -1
  182. package/packages/pm-templates/package.json +1 -1
  183. package/packages/pm-todos/package.json +1 -1
  184. package/packages/pm-vcs/package.json +1 -1
  185. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  186. package/plugins/pm-claude/package.json +1 -1
  187. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  188. package/plugins/pm-codex/package.json +1 -1
  189. package/plugins/pm-codex/plugin.json +1 -1
  190. package/runtime-dependencies.json +1 -1
  191. package/dist/cli-bundle/chunks/chunk-444VPGQT.js +0 -20
  192. package/dist/cli-bundle/chunks/chunk-5ZPT67NJ.js +0 -127
  193. package/dist/cli-bundle/chunks/chunk-7C3GCLOO.js +0 -30
  194. package/dist/cli-bundle/chunks/chunk-HMJSFWHK.js +0 -2
  195. package/dist/cli-bundle/chunks/chunk-RLXK2S7P.js +0 -2
  196. package/dist/cli-bundle/chunks/chunk-RQKDANP7.js +0 -113
  197. package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +0 -2
  198. package/dist/cli-bundle/chunks/chunk-XYLBOXSH.js +0 -6
  199. package/dist/cli-bundle/chunks/indexed-receipt-blobs-47I6KKDO.js +0 -4
  200. package/dist/cli-bundle/chunks/register-mutation-JZVVJUHY.js +0 -20
  201. package/dist/cli-bundle/focused-chunks/chunk-5LBZR6YW.js +0 -2
  202. package/dist/cli-bundle/focused-chunks/chunk-IVLIUPVV.js +0 -12
  203. package/dist/cli-bundle/focused-chunks/chunk-KIIGME23.js +0 -2
  204. package/dist/cli-bundle/focused-chunks/chunk-LWJ2X75I.js +0 -78
  205. package/dist/cli-bundle/focused-chunks/chunk-MT5TYMEU.js +0 -3
  206. package/dist/cli-bundle/focused-chunks/chunk-NI5SG2M2.js +0 -2
  207. package/dist/cli-bundle/focused-chunks/chunk-QH5KMIYZ.js +0 -91
  208. package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +0 -2
  209. package/dist/cli-bundle/focused-chunks/chunk-W7MCCFYV.js +0 -2
  210. package/dist/cli-bundle/focused-chunks/chunk-WMPDY5ZU.js +0 -21
  211. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-YCLN2ZZG.js +0 -4
@@ -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.25","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.25","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.27","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.27","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,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026.10.27 - 2026-10-27
4
+
5
+ ### Fixed
6
+
7
+ - GH-1593: verify authoritative history integrity in SDK mutation-event reads ([pm-gh1593](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1593.toon))
8
+ - Isolate telemetry setup in the health cursor replay regression ([pm-oahhyc](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-oahhyc.toon))
9
+ - Preserve Git-backed merge-receipt evidence in isolated linked-test contexts ([pm-ycyymg](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-ycyymg.toon))
10
+ - Let superseded CI aggregators stop when their workflow is canceled ([pm-ci-cancel-aggregate](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-ci-cancel-aggregate.toon))
11
+ - Reserve preparation and runner queue time before serial release acceptance ([pm-29bwud](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-29bwud.toon))
12
+
13
+ ### Other
14
+
15
+ - Use resilient temporary-root cleanup in the packed-install workflow fixture ([pm-p5u6](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-p5u6.toon))
16
+ - Refresh mature tooling, scanner pins and changelog SDK contracts ([pm-8skz5z](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-8skz5z.toon))
17
+
18
+ ## 2026.10.26 - 2026-10-26
19
+
20
+ ### Added
21
+
22
+ - 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))
23
+
24
+ ### Changed
25
+
26
+ - 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))
27
+
28
+ ### Fixed
29
+
30
+ - 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))
31
+ - 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))
32
+ - 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))
33
+ - 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))
34
+ - 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))
35
+ - 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))
36
+ - 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))
37
+
38
+ ### Security
39
+
40
+ - 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))
41
+
42
+ ### Other
43
+
44
+ - 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))
45
+
3
46
  ## 2026.10.25 - 2026-10-25
4
47
 
5
48
  ### Changed
@@ -343,8 +386,8 @@
343
386
 
344
387
  ### Other
345
388
 
346
- - Prove native Git lock retry after observed contention in PR1425 ([pm-native-git-retry-proof](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-native-git-retry-proof.toon))
347
389
  - Bound local temp footprint: prune Node compile cache and guarantee smoke/dogfood sandbox cleanup on failure ([pm-p5u6](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-p5u6.toon))
390
+ - Prove native Git lock retry after observed contention in PR1425 ([pm-native-git-retry-proof](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-native-git-retry-proof.toon))
348
391
 
349
392
  ## 2026.10.7 - 2026-10-07
350
393
 
@@ -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]="6a8cb05a-e2d2-53ce-a8fe-64ef2aabe699")}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",...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(`
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,11 +1,11 @@
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]="888bf806-b6de-5dee-9494-59ad5057c159")}catch{}})();import{EXIT_CODE,PmCliError,readSettings,renderRowsAsCsv,renderRowsAsTable,resolvePmRoot}from"../sdk/runtime-primitives.js";import{renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"../sdk/cli-contracts.js";import{EVAL_QUERY_SET_SCHEMA_ID}from"../sdk/eval.js";import{applyContextIntentProjection}from"../sdk/context-intent-contracts.js";import{renderPmClosedDomainHelp}from"../sdk/agent/closed-domain-contracts.js";import{serializeNdjsonRows,serializeNdjsonStream}from"../sdk/output.js";import{listMutationEvents,subscribeMutationEventBatches,subscribeMutationEvents}from"../sdk/mutation-events.js";import{registerHistoryActivityCommand}from"./register-history-activity.js";import{registerHistoryMaintenanceCommands}from"./register-history-maintenance.js";import{runAggregate}from"./commands/query/aggregate.js";import{renderContextMarkdown,runContext,resolveContextOutputFormat}from"./commands/query/context.js";import{runEval}from"./commands/query/eval.js";import{runGet}from"./commands/query/get.js";import{runGraph}from"./commands/query/graph.js";import{runHistory}from"./commands/history/history.js";import{runList}from"./commands/query/list.js";import{LIST_COMMAND_DEFAULT_PROJECTIONS}from"../sdk/query/list.js";import{renderNextMarkdown,runNext,resolveNextOutputFormat}from"./commands/query/next.js";import{runSearch}from"./commands/query/search.js";import{addHiddenOption,collect,getGlobalOptions,normalizeAggregateOptions,normalizeContextOptions,normalizeListOptions,normalizeNextOptions,normalizeSearchKeywordsInput,normalizeSearchOptions,printError,printListJsonStream,printResult,setActiveCommandResult,writeStdout}from"./registration-helpers.js";function shouldRegisterListQueryCommand(commandName,commandFilter){return!commandFilter||commandFilter.size===0?!0:commandName==="context"?commandFilter.has("context")||commandFilter.has("ctx"):commandFilter.has(commandName)}function parseListFormat(rawFormat){if(rawFormat===void 0)return;if(typeof rawFormat!="string")throw new PmCliError("List --format must be one of csv|table|json|ndjson|toon",EXIT_CODE.USAGE);const normalized=rawFormat.trim().toLowerCase();if(normalized==="csv"||normalized==="table"||normalized==="json"||normalized==="ndjson"||normalized==="toon")return normalized;throw new PmCliError("List --format must be one of csv|table|json|ndjson|toon",EXIT_CODE.USAGE)}function resolveReadCommandOutputFormat(commandLabel,rawFormat,globalOptions,allowNdjson=!1){if(rawFormat===void 0)return globalOptions;if(typeof rawFormat!="string")throw new PmCliError(`${commandLabel} --format must be one of ${allowNdjson?"json|ndjson|toon":"json|toon"}`,EXIT_CODE.USAGE);const normalized=rawFormat.trim().toLowerCase();if(normalized!=="json"&&(normalized!=="ndjson"||!allowNdjson)&&normalized!=="toon")throw new PmCliError(`${commandLabel} --format must be one of ${allowNdjson?"json|ndjson|toon":"json|toon"}`,EXIT_CODE.USAGE);if(globalOptions.json===!0&&normalized==="toon")throw new PmCliError(`${commandLabel} cannot combine --json with --format toon`,EXIT_CODE.USAGE);return{...globalOptions,json:normalized==="json"||normalized==="ndjson"}}function applyDefaultListProjection(listOptions,commandName){LIST_COMMAND_DEFAULT_PROJECTIONS[commandName]==="brief"&&listOptions.includeBody!==!0&&listOptions.compact!==!0&&listOptions.brief!==!0&&listOptions.full!==!0&&listOptions.fields===void 0&&(listOptions.brief=!0)}function registerContentAndGovernanceFilters(command){command.option("--has-notes","Show only items that have notes").option("--has-learnings","Show only items that have learnings").option("--has-files","Show only items that have linked files").option("--has-docs","Show only items that have linked docs").option("--has-tests","Show only items that have linked tests").option("--has-comments","Show only items that have comments").option("--has-deps","Show only items that have dependencies").option("--has-body","Show only items that have a non-empty body").option("--has-linked-command","Show only items whose linked tests carry a runnable command").option("--no-notes","Show only items that have no notes").option("--no-learnings","Show only items that have no learnings").option("--no-files","Show only items that have no linked files").option("--filter-files-missing","Alias for --no-files").option("--no-docs","Show only items that have no linked docs").option("--filter-docs-missing","Alias for --no-docs").option("--no-tests","Show only items that have no linked tests").option("--no-comments","Show only items that have no comments").option("--no-deps","Show only items that have no dependencies").option("--empty-body","Show only items with an empty body").option("--no-linked-command","Show only items whose linked tests carry no runnable command").option("--filter-reviewer-missing","Show only items missing reviewer").option("--filter-risk-missing","Show only items missing risk").option("--filter-confidence-missing","Show only items missing confidence").option("--filter-sprint-missing","Show only items missing sprint").option("--filter-release-missing","Show only items missing release")}const CANONICAL_LIST_STATUS_VARIANTS={draft:{name:"list-draft",dependencyBlocked:!1},open:{name:"list-open",dependencyBlocked:!1},in_progress:{name:"list-in-progress",dependencyBlocked:!1},blocked:{name:"list-blocked",dependencyBlocked:!0},closed:{name:"list-closed",dependencyBlocked:!1},canceled:{name:"list-canceled",dependencyBlocked:!1}};function resolveRegisteredListOutputContext(options,globalOptions){const streamMode=options.stream===!0,listFormat=parseListFormat(options.format),tabular=listFormat==="csv"||listFormat==="table",effectiveGlobal=listFormat==="json"||listFormat==="ndjson"||listFormat==="toon"?resolveReadCommandOutputFormat("List",options.format,globalOptions,!0):globalOptions;if(streamMode&&!effectiveGlobal.json)throw new PmCliError("--stream requires --json output mode.",EXIT_CODE.USAGE);if((tabular||listFormat==="ndjson")&&streamMode)throw new PmCliError("--format csv|table|ndjson cannot be combined with --stream.",EXIT_CODE.USAGE);return{streamMode,listFormat,effectiveGlobal}}function renderRegisteredListResult(commandName,result,output){if(output.listFormat==="csv"||output.listFormat==="table"){setActiveCommandResult(result);const rows=result.items,rendered=output.listFormat==="csv"?renderRowsAsCsv(rows):renderRowsAsTable(rows);!output.effectiveGlobal.quiet&&rendered.length>0&&writeStdout(`${rendered}
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]="9c5f2e6d-c6a0-5ecf-b659-712fb5b37f3c")}catch{}})();import{EXIT_CODE,PmCliError,readSettings,renderRowsAsCsv,renderRowsAsTable,resolvePmRoot}from"../sdk/runtime-primitives.js";import{renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"../sdk/cli-contracts.js";import{EVAL_QUERY_SET_SCHEMA_ID}from"../sdk/eval.js";import{applyContextIntentProjection}from"../sdk/context-intent-contracts.js";import{renderPmClosedDomainHelp}from"../sdk/agent/closed-domain-contracts.js";import{serializeNdjsonRows,serializeNdjsonStream}from"../sdk/output.js";import{listMutationEvents,subscribeMutationEventBatches,subscribeMutationEvents}from"../sdk/mutation-events.js";import{registerHistoryActivityCommand}from"./register-history-activity.js";import{registerHistoryMaintenanceCommands}from"./register-history-maintenance.js";import{runAggregate}from"./commands/query/aggregate.js";import{renderContextMarkdown,runContext,resolveContextOutputFormat}from"./commands/query/context.js";import{runEval}from"./commands/query/eval.js";import{runGet}from"./commands/query/get.js";import{runGraph}from"./commands/query/graph.js";import{runHistory}from"./commands/history/history.js";import{runList}from"./commands/query/list.js";import{LIST_COMMAND_DEFAULT_PROJECTIONS}from"../sdk/query/list.js";import{renderNextMarkdown,runNext,resolveNextOutputFormat}from"./commands/query/next.js";import{runSearch}from"./commands/query/search.js";import{addHiddenOption,collect,getGlobalOptions,normalizeAggregateOptions,normalizeContextOptions,normalizeListOptions,normalizeNextOptions,normalizeSearchKeywordsInput,normalizeSearchOptions,printError,printListJsonStream,printResult,setActiveCommandResult,writeStdout}from"./registration-helpers.js";function shouldRegisterListQueryCommand(commandName,commandFilter){return!commandFilter||commandFilter.size===0?!0:commandName==="context"?commandFilter.has("context")||commandFilter.has("ctx"):commandFilter.has(commandName)}function parseListFormat(rawFormat){if(rawFormat===void 0)return;if(typeof rawFormat!="string")throw new PmCliError("List --format must be one of csv|table|json|ndjson|toon",EXIT_CODE.USAGE);const normalized=rawFormat.trim().toLowerCase();if(normalized==="csv"||normalized==="table"||normalized==="json"||normalized==="ndjson"||normalized==="toon")return normalized;throw new PmCliError("List --format must be one of csv|table|json|ndjson|toon",EXIT_CODE.USAGE)}function resolveReadCommandOutputFormat(commandLabel,rawFormat,globalOptions,allowNdjson=!1){if(rawFormat===void 0)return globalOptions;if(typeof rawFormat!="string")throw new PmCliError(`${commandLabel} --format must be one of ${allowNdjson?"json|ndjson|toon":"json|toon"}`,EXIT_CODE.USAGE);const normalized=rawFormat.trim().toLowerCase();if(normalized!=="json"&&(normalized!=="ndjson"||!allowNdjson)&&normalized!=="toon")throw new PmCliError(`${commandLabel} --format must be one of ${allowNdjson?"json|ndjson|toon":"json|toon"}`,EXIT_CODE.USAGE);if(globalOptions.json===!0&&normalized==="toon")throw new PmCliError(`${commandLabel} cannot combine --json with --format toon`,EXIT_CODE.USAGE);return{...globalOptions,json:normalized==="json"||normalized==="ndjson"}}function applyDefaultListProjection(listOptions,commandName){LIST_COMMAND_DEFAULT_PROJECTIONS[commandName]==="brief"&&listOptions.includeBody!==!0&&listOptions.compact!==!0&&listOptions.brief!==!0&&listOptions.full!==!0&&listOptions.fields===void 0&&(listOptions.brief=!0)}function registerContentAndGovernanceFilters(command){command.option("--has-notes","Show only items that have notes").option("--has-learnings","Show only items that have learnings").option("--has-files","Show only items that have linked files").option("--has-docs","Show only items that have linked docs").option("--has-tests","Show only items that have linked tests").option("--has-comments","Show only items that have comments").option("--has-deps","Show only items that have dependencies").option("--has-body","Show only items that have a non-empty body").option("--has-linked-command","Show only items whose linked tests carry a runnable command").option("--no-notes","Show only items that have no notes").option("--no-learnings","Show only items that have no learnings").option("--no-files","Show only items that have no linked files").option("--filter-files-missing","Alias for --no-files").option("--no-docs","Show only items that have no linked docs").option("--filter-docs-missing","Alias for --no-docs").option("--no-tests","Show only items that have no linked tests").option("--no-comments","Show only items that have no comments").option("--no-deps","Show only items that have no dependencies").option("--empty-body","Show only items with an empty body").option("--no-linked-command","Show only items whose linked tests carry no runnable command").option("--filter-reviewer-missing","Show only items missing reviewer").option("--filter-risk-missing","Show only items missing risk").option("--filter-confidence-missing","Show only items missing confidence").option("--filter-sprint-missing","Show only items missing sprint").option("--filter-release-missing","Show only items missing release")}const CANONICAL_LIST_STATUS_VARIANTS={draft:{name:"list-draft",dependencyBlocked:!1},open:{name:"list-open",dependencyBlocked:!1},in_progress:{name:"list-in-progress",dependencyBlocked:!1},blocked:{name:"list-blocked",dependencyBlocked:!0},closed:{name:"list-closed",dependencyBlocked:!1},canceled:{name:"list-canceled",dependencyBlocked:!1}};function resolveRegisteredListOutputContext(options,globalOptions){const streamMode=options.stream===!0,listFormat=parseListFormat(options.format),tabular=listFormat==="csv"||listFormat==="table",effectiveGlobal=listFormat==="json"||listFormat==="ndjson"||listFormat==="toon"?resolveReadCommandOutputFormat("List",options.format,globalOptions,!0):globalOptions;if(streamMode&&!effectiveGlobal.json)throw new PmCliError("--stream requires --json output mode.",EXIT_CODE.USAGE);if((tabular||listFormat==="ndjson")&&streamMode)throw new PmCliError("--format csv|table|ndjson cannot be combined with --stream.",EXIT_CODE.USAGE);return{streamMode,listFormat,effectiveGlobal}}function renderRegisteredListResult(commandName,result,output){if(output.listFormat==="csv"||output.listFormat==="table"){setActiveCommandResult(result);const rows=result.items,rendered=output.listFormat==="csv"?renderRowsAsCsv(rows):renderRowsAsTable(rows);!output.effectiveGlobal.quiet&&rendered.length>0&&writeStdout(`${rendered}
2
2
  `)}else if(output.listFormat==="ndjson"){setActiveCommandResult(result);const rendered=serializeNdjsonRows(result.items);!output.effectiveGlobal.quiet&&rendered.length>0&&writeStdout(`${rendered}
3
3
  `)}else output.streamMode?printListJsonStream(commandName,result,output.effectiveGlobal):printResult(result,output.effectiveGlobal)}async function runRegisteredListCommand(params){const parsedGlobalOptions=getGlobalOptions(params.actionCommand),globalOptions=params.aliasContract?{...parsedGlobalOptions,command:params.aliasContract.canonical}:parsedGlobalOptions,startedAt=Date.now();params.aliasContract?.lifecycle==="deprecated"&&await readSettings(resolvePmRoot(process.cwd(),globalOptions.path)).then(settings=>settings.ux.deprecation_hints)&&printError(renderPmCommandAliasMigrationHint(params.aliasContract));const intentOptions=applyContextIntentProjection("list",params.options),listOptions=normalizeListOptions(intentOptions),selection=resolveRegisteredListSelection(params,listOptions),{effectiveName,effectiveStatus,effectiveDependencyBlocked,effectiveExcludeTerminal}=selection;applyDefaultListProjection(listOptions,params.name),Object.assign(listOptions,{projectionCommand:effectiveName}),effectiveExcludeTerminal&&(listOptions.excludeTerminal=!0),listOptions.dependencyBlocked=effectiveDependencyBlocked;const output=resolveRegisteredListOutputContext(intentOptions,globalOptions),result=await runList(effectiveDependencyBlocked?void 0:effectiveStatus,listOptions,globalOptions);renderRegisteredListResult("list",result,output),globalOptions.profile&&printError(`profile:command=list took_ms=${Date.now()-startedAt}`)}function resolveRegisteredListSelection(params,listOptions){let effectiveName=params.name,effectiveStatus=params.status,effectiveDependencyBlocked=params.dependencyBlocked===!0,effectiveExcludeTerminal=params.excludeTerminal===!0;const requestedStatus=listOptions.status?.trim().toLowerCase(),requestedVariant=params.name==="list"&&requestedStatus!==void 0?CANONICAL_LIST_STATUS_VARIANTS[requestedStatus]:void 0;return params.name==="list"&&(params.options.all===!0||requestedStatus==="all"?(effectiveName="list-all",effectiveExcludeTerminal=!1,listOptions.status=void 0):requestedStatus!==void 0&&requestedVariant!==void 0&&(effectiveName=requestedVariant.name,effectiveStatus=requestedStatus,effectiveDependencyBlocked=requestedVariant.dependencyBlocked,effectiveExcludeTerminal=!1,listOptions.status=void 0)),(effectiveName==="list-open"||effectiveName==="list-in-progress")&&(listOptions.lifecycleBucket=effectiveName==="list-open"?"open":"in_progress",effectiveStatus=void 0),{effectiveName,effectiveStatus,effectiveDependencyBlocked,effectiveExcludeTerminal}}function registerListCommand(program,descriptor){const{name,description,status,excludeTerminal,allowStatusFilter,dependencyBlocked,aliasContract}=descriptor,command=program.command(name,{hidden:aliasContract?.hidden===!0}).description(description);allowStatusFilter&&command.option("--status <value>","Filter by status (repeatable or comma-separated; matches any; all selects every status)",collect),name==="list"&&command.option("--all","Include every lifecycle status"),command.option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("list","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--type <value>","Filter by item type (repeatable or comma-separated; matches any)",collect).option("--tag <value>","Filter by tag (repeatable or comma-separated; matches any)",collect).option("--priority <value>","Filter by priority (repeatable or comma-separated; matches any)",collect).option("--deadline-before <value>","Filter by deadline upper bound (ISO/date string or relative)").option("--deadline-after <value>","Filter by deadline lower bound (ISO/date string or relative)").option("--today","Filter to items updated since local midnight today").option("--recent","Filter to items updated in the last 7 days").option("--updated-after <value>","Updated since ISO timestamp or signed relative (-2h/-7d for past); use last-window ISO").option("--updated-before <value>","Filter by updated_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-after <value>","Filter by created_at lower bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-before <value>","Filter by created_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--ids <value>","Filter by explicit item IDs (comma-separated or repeatable)").option("--assignee <value>","Filter by assignee",collect).option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--parent <value>","Filter by parent item ID").option("--sprint <value>","Filter by sprint",collect).option("--release <value>","Filter by release",collect).option("--filter-ac-missing","Show only items missing acceptance_criteria").option("--filter-estimates-missing","Show only items missing estimated_minutes").option("--filter-resolution-missing","Show only terminal items missing resolution").option("--filter-metadata-missing","Show only items missing any tracked metadata (AC, estimate, or resolution)").option("--limit <n>","Alias for --output-limit; --output-budget may cap rows").option("--offset <n>","Skip the first n matching rows before limit is applied").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor").option("--no-truncate","Disable default token cap; explicit --limit and --output-budget apply").option("--include-body","Include item body in each returned list row").option("--strict-read","Fail closed if any item document or item directory cannot be read").option("--compact","Render compact list projection fields (mutually exclusive with --brief/--full/--fields)").option("--brief","Brief rows: id, status, type, title and leading sort field (priority by default; excludes --compact/--full/--fields)").option("--full","Render full list projection fields (mutually exclusive with --compact/--brief/--fields)").option("--fields <value>",`Render custom comma-separated list fields (mutually exclusive with --compact/--brief/--full). ${renderPmClosedDomainHelp(name,"--fields")}`).option("--sort <value>","Sort field: priority|deadline|updated_at|created_at|title|parent (aliases: updated, created)").option("--order <value>","Sort order: asc|desc (requires --sort)").option("--tree","Render rows in parent/child tree order").option("--tree-depth <n>","Maximum recursion depth with --tree (0 keeps root rows only)").option("--format <value>","Output render mode: csv|table (human export) or json|ndjson|toon (machine output override)").option("--stream","Emit line-delimited JSON rows (requires --json)"),registerContentAndGovernanceFilters(command),command.action(async(options,actionCommand)=>{await runRegisteredListCommand({name,status,excludeTerminal,dependencyBlocked,options,actionCommand,aliasContract})}),addHiddenOption(command,"--tags <value>","Alias for --tag"),addHiddenOption(command,"--assignee_filter <value>","Alias for --assignee-filter"),addHiddenOption(command,"--tree_depth <n>","Alias for --tree-depth"),addHiddenOption(command,"--token_budget <n>","Alias for --token-budget"),addHiddenOption(command,"--filter-estimate-missing","Alias for --filter-estimates-missing")}async function runAggregateAction(options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runAggregate(normalizeAggregateOptions(options),globalOptions);printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=aggregate took_ms=${Date.now()-startedAt}`)}async function runContextAction(options,actionCommand){const globalOptions=getGlobalOptions(actionCommand),startedAt=Date.now(),normalized=normalizeContextOptions(applyContextIntentProjection("context",options)),result=await runContext(normalized,globalOptions),outputFormat=resolveContextOutputFormat(normalized,globalOptions);if(outputFormat==="markdown")globalOptions.quiet||writeStdout(`${renderContextMarkdown(result)}
4
4
  `);else if(outputFormat==="ndjson"){setActiveCommandResult(result);const rendered=serializeNdjsonRows([...result.high_level,...result.low_level,...result.blocked_fallback]);!globalOptions.quiet&&rendered.length>0&&writeStdout(`${rendered}
5
5
  `)}else printResult(result,{...globalOptions,json:outputFormat==="json"});globalOptions.profile&&printError(`profile:command=context took_ms=${Date.now()-startedAt}`)}async function runNextAction(options,actionCommand){const globalOptions=getGlobalOptions(actionCommand),startedAt=Date.now(),nextOptions=normalizeNextOptions(applyContextIntentProjection("next",options)),result=await runNext(nextOptions,globalOptions),outputFormat=resolveNextOutputFormat(nextOptions,globalOptions);outputFormat==="markdown"?globalOptions.quiet||writeStdout(`${renderNextMarkdown(result)}
6
6
  `):printResult(result,{...globalOptions,json:outputFormat==="json"}),globalOptions.profile&&printError(`profile:command=next took_ms=${Date.now()-startedAt}`)}async function runSearchAction(keywords,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),query=normalizeSearchKeywordsInput(keywords),intentOptions=applyContextIntentProjection("search",options,[query]),searchOptions=normalizeSearchOptions(intentOptions),result=await runSearch(query,searchOptions,globalOptions),outputFormat=typeof intentOptions.format=="string"?intentOptions.format.trim().toLowerCase():void 0,effectiveGlobal=resolveReadCommandOutputFormat("Search",intentOptions.format,globalOptions,!0);if(outputFormat==="ndjson"){setActiveCommandResult(result);const rendered=serializeNdjsonRows(result.items);!effectiveGlobal.quiet&&rendered.length>0&&writeStdout(`${rendered}
7
- `)}else printResult(result,effectiveGlobal);globalOptions.profile&&printError(`profile:command=search took_ms=${Date.now()-startedAt}`)}async function runEvalAction(options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runEval({mode:typeof options.mode=="string"?options.mode:void 0,k:typeof options.k=="string"?options.k:void 0,failUnder:typeof options.failUnder=="string"?options.failUnder:void 0,queries:typeof options.queries=="string"?options.queries:void 0,format:typeof options.format=="string"?options.format:void 0},globalOptions);if(printResult(result,resolveReadCommandOutputFormat("Eval",options.format,globalOptions)),globalOptions.profile&&printError(`profile:command=eval took_ms=${Date.now()-startedAt}`),!result.passed)throw new PmCliError("Eval gate failed: one or more aggregate or per-query thresholds were not met; inspect the metric report",EXIT_CODE.GENERIC_FAILURE)}async function runGetAction(id,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),intentOptions=applyContextIntentProjection("get",options,[id]),result=await runGet(id,globalOptions,{depth:typeof intentOptions.depth=="string"?intentOptions.depth:void 0,fields:typeof intentOptions.fields=="string"?intentOptions.fields:void 0,full:!!intentOptions.full,tree:intentOptions.tree===!0,treeDepth:typeof intentOptions.treeDepth=="string"?intentOptions.treeDepth:typeof intentOptions.tree_depth=="string"?intentOptions.tree_depth:void 0,at:typeof intentOptions.at=="string"?intentOptions.at:void 0});printResult(result,resolveReadCommandOutputFormat("Get",intentOptions.format,globalOptions)),globalOptions.profile&&printError(`profile:command=get took_ms=${Date.now()-startedAt}`)}async function runHistoryAction(id,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now();if([options.compact,options.raw,options.full,options.provenance].filter(value=>value===!0).length>1)throw new PmCliError("History projection options are mutually exclusive. Use --compact, --provenance, or --full.",EXIT_CODE.USAGE);const field=typeof options.field=="string"?options.field:void 0,strictExit=!!options.strictExit||!!options.failOnWarn;if(strictExit&&!options.verify)throw new PmCliError("--strict-exit requires --verify (it gates on the verification result).",EXIT_CODE.USAGE);const result=await runHistory(id,{limit:typeof options.limit=="string"?options.limit:void 0,compact:!(options.full===!0||options.provenance===!0),provenance:options.provenance===!0,provenanceSummary:options.provenanceSummary===!0,harness:readRepeatableStringOption(options,"harness"),agentInstance:readRepeatableStringOption(options,"agentInstance"),provenanceFilter:readRepeatableStringOption(options,"provenanceFilter"),diff:!!options.diff||field!==void 0,field,verify:!!options.verify},globalOptions);printResult(result,resolveReadCommandOutputFormat("History",options.format,globalOptions)),strictExit&&result.verification&&!result.verification.ok&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE),globalOptions.profile&&printError(`profile:command=history took_ms=${Date.now()-startedAt}`)}function readRepeatableStringOption(options,key){const value=options[key];return Array.isArray(value)?value:void 0}function buildMutationEventOptions(options,pmRoot){const harness=readRepeatableStringOption(options,"harness"),agentInstance=readRepeatableStringOption(options,"agentInstance"),provenanceFilter=readRepeatableStringOption(options,"provenanceFilter"),rawCursorMode=typeof options.cursorMode=="string"?options.cursorMode:void 0;if(rawCursorMode!==void 0&&rawCursorMode!=="batch"&&rawCursorMode!=="row")throw new PmCliError("Events --cursor-mode must be batch or row.",EXIT_CODE.USAGE,{code:"invalid_event_cursor_mode"});const cursorMode=rawCursorMode;return{pmRoot,since:typeof options.since=="string"?options.since:void 0,type:readRepeatableStringOption(options,"type"),author:readRepeatableStringOption(options,"author"),item:readRepeatableStringOption(options,"item"),limit:typeof options.limit=="string"?Number(options.limit):void 0,full:options.full===!0,...options.provenance===!0?{provenance:!0}:{},...options.provenanceSummary===!0?{provenanceSummary:!0}:{},...harness===void 0?{}:{harness},...agentInstance===void 0?{}:{agentInstance},...provenanceFilter===void 0?{}:{provenanceFilter},cursorMode}}async function followMutationEvents(eventOptions,options,quiet){if(options.provenanceSummary===!0)throw new PmCliError("Events --provenance-summary is bounded to one page and cannot be combined with --follow.",EXIT_CODE.USAGE);const intervalMs=typeof options.intervalMs=="string"?Number(options.intervalMs):void 0;if(eventOptions.cursorMode==="row"){for await(const event of subscribeMutationEvents({...eventOptions,intervalMs}))quiet||writeStdout(`${JSON.stringify(event)}
8
- `);return}for await(const page of subscribeMutationEventBatches({...eventOptions,intervalMs}))quiet||writeStdout(`${serializeNdjsonStream(page.events,{count:page.count,has_more:page.has_more,next_cursor:page.next_cursor??null,source:page.source,heartbeat:page.count===0})}
9
- `)}function renderMutationEventPage(page){return page.cursor_mode==="row"?serializeNdjsonRows(page.events):serializeNdjsonStream(page.events,{count:page.count,has_more:page.has_more,next_cursor:page.next_cursor??null,source:page.source,...page.provenance_summary===void 0?{}:{provenance_summary:page.provenance_summary}})}async function runEventsAction(options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),eventOptions=buildMutationEventOptions(options,globalOptions.path);if(options.follow===!0){await followMutationEvents(eventOptions,options,globalOptions.quiet===!0);return}const page=await listMutationEvents(eventOptions);if(setActiveCommandResult(page),globalOptions.json){printResult(page,globalOptions),globalOptions.profile&&printError(`profile:command=events took_ms=${Date.now()-startedAt}`);return}const rendered=renderMutationEventPage(page);!globalOptions.quiet&&rendered.length>0&&writeStdout(`${rendered}
10
- `),globalOptions.profile&&printError(`profile:command=events took_ms=${Date.now()-startedAt}`)}async function runGraphAction(subcommand,id,target,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runGraph(subcommand,id,target,{...Array.isArray(options.kind)?{kind:options.kind}:{},maxDepth:typeof options.maxDepth=="string"?options.maxDepth:void 0,limit:typeof options.limit=="string"?options.limit:void 0,after:typeof options.after=="string"?options.after:void 0,direction:typeof options.direction=="string"?options.direction:void 0,maxPaths:typeof options.maxPaths=="string"?options.maxPaths:void 0,sample:typeof options.sample=="string"?options.sample:void 0,...Array.isArray(options.exemptIsolate)?{exemptIsolate:options.exemptIsolate}:{},...Array.isArray(options.exemptIsolateType)?{exemptIsolateType:options.exemptIsolateType}:{},saveBaseline:options.saveBaseline===!0,rebuild:options.rebuild===!0,clear:options.clear===!0,summary:options.summary===!0,full:options.full===!0},globalOptions);printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=graph took_ms=${Date.now()-startedAt}`)}function registerListQueryCommands(program,options){const commandFilter=options?.commandFilter,shouldRegister=commandName=>shouldRegisterListQueryCommand(commandName,commandFilter),listCommandDescriptors=[{name:"list",description:"List active items with optional lifecycle-status and project filters.",excludeTerminal:!0,allowStatusFilter:!0},{name:"list-all",description:"List all items with optional filters.",excludeTerminal:!1,allowStatusFilter:!0},{name:"list-draft",description:"List draft items with optional filters.",status:"draft"},{name:"list-open",description:"List open items with optional filters.",status:"open",excludeTerminal:!1,allowStatusFilter:!1},{name:"list-in-progress",description:"List in-progress items with optional filters.",status:"in_progress",excludeTerminal:!1,allowStatusFilter:!1},{name:"list-blocked",description:"List blocked items (blocked status or open blocked_by dependencies, matching pm next) with optional filters.",dependencyBlocked:!0,excludeTerminal:!1,allowStatusFilter:!1},{name:"list-closed",description:"List closed items with optional filters.",status:"closed"},{name:"list-canceled",description:"List canceled items with optional filters.",status:"canceled"}];for(const descriptor of listCommandDescriptors)if(shouldRegister(descriptor.name)){const aliasContract=resolvePmCommandAlias(descriptor.name);registerListCommand(program,{...descriptor,...aliasContract?.registration==="commander"?{aliasContract}:{}})}if(shouldRegister("aggregate")){const aggregateCommand=program.command("aggregate").description("Group item counts and numeric measures.").option("--set-mode <value>","Set grouping: element (default)|tuple").option("--limit <value>","Group page size (default: 50)").option("--after <value>","Continue with next_after cursor").option("--group-by <value>","Fields: parent,type,priority,status,assignee,tags,sprint,release (comma-separated)").option("--count","Counts (default)").option("--completion","Status counts and completion_pct").option("--sum <field>","Group numeric sum").option("--avg <field>","Group numeric average").option("--include-unparented","Keep unparented group").option("--status <value>","Item status").option("--type <value>","Item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--deadline-before <value>","Latest deadline (ISO/date or relative)").option("--deadline-after <value>","Earliest deadline (ISO/date or relative)").option("--assignee <value>","Filter by assignee").option("--assignee-filter <value>","Assignee presence: assigned|unassigned").option("--parent <value>","Parent ID").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release");addHiddenOption(aggregateCommand,"--include_unparented","Alias for --include-unparented"),addHiddenOption(aggregateCommand,"--assignee_filter <value>","Alias for --assignee-filter"),aggregateCommand.action(runAggregateAction)}if(shouldRegister("context")){const contextCommand=program.command("context").alias("ctx").description("Show a token-efficient project context snapshot for next-work decisions.").option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("context","--for")}`).option("--date <value>","Anchor date/time for agenda window calculations (ISO/date string or relative)").option("--from <value>","Agenda lower bound (ISO/date string or relative)").option("--to <value>","Agenda upper bound (ISO/date string or relative)").option("--past","Include past agenda entries in bounded windows").option("--type <value>","Filter by item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--assignee <value>","Filter by assignee").option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release").option("--parent <id>","Scope the snapshot to one item's subtree (the item plus all descendants)").option("--limit <n>","Limit focus and agenda rows per section").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor").option("--format <value>","Context output format override: markdown|toon|json|ndjson").option("--depth <value>","Context depth: brief|standard|deep|full (full = every section, no per-section cap)").option("--section <value...>","Include specific sections (repeatable; overrides --depth)").option("--fields <value>","Project focus rows to a comma-separated field subset (e.g. id,title,priority)").option("--activity-limit <n>","Limit recent activity entries (default: settings or 10)").option("--stale-threshold <value>","Staleness cutoff in days (e.g. 7 or 7d; default: settings or 7)").option("--explain-ranking","Include the scorer model, per-signal contributions, and ranked candidate ids").option("--token-budget <n>","Complete JSON/TOON response token ceiling").option("--no-extension-health","Omit the installed extension health summary").option("--no-tags","Omit tag arrays from context focus rows");addHiddenOption(contextCommand,"--assignee_filter <value>","Alias for --assignee-filter"),addHiddenOption(contextCommand,"--max-items <n>","Alias for --limit"),addHiddenOption(contextCommand,"--explain_ranking","Alias for --explain-ranking"),addHiddenOption(contextCommand,"--token_budget <n>","Alias for --token-budget"),contextCommand.action(runContextAction)}if(shouldRegister("next")){const nextCommand=program.command("next").description("Recommend the next actionable (unblocked, ready) work item with rationale + blocked companion.").option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("next","--for")}`).option("--type <value>","Filter candidate items by type").option("--tag <value>","Filter candidate items by tag").option("--priority <value>","Filter candidate items by priority").option("--assignee <value>","Filter candidate items by assignee").option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--sprint <value>","Filter candidate items by sprint").option("--release <value>","Filter candidate items by release").option("--parent <id>","Scope to one item's subtree (the item plus all descendants)").option("--limit <n>","Limit ready rows (default: 5; non-positive falls back to default)").option("--blocked-limit <n>","Limit blocked rows (default: same as --limit)").option("--ready-only","Omit the blocked companion list").option("--include-decisions","Include human-gated Decision items in the claimable ready queue").option("--include-gates","Include outcome gates in the ready queue").option("--include-containers","Include containers with unfinished descendants in the ready queue").option("--format <value>","Next output format override: markdown|toon|json").option("--explain-ranking","Include the scorer model, per-signal contributions, and ranked ready ids").option("--token-budget <n>","Maximum estimated tokens spent on the ranked ready queue");addHiddenOption(nextCommand,"--assignee_filter <value>","Alias for --assignee-filter"),addHiddenOption(nextCommand,"--blocked_limit <n>","Alias for --blocked-limit"),addHiddenOption(nextCommand,"--ready_only","Alias for --ready-only"),addHiddenOption(nextCommand,"--explain_ranking","Alias for --explain-ranking"),addHiddenOption(nextCommand,"--token_budget <n>","Alias for --token-budget"),nextCommand.action(runNextAction)}if(shouldRegister("search")){const searchCommand=program.command("search").argument("<keywords...>","Keyword query tokens").description("Search items with keyword, semantic, or hybrid retrieval. Inline field:value tokens (tag:/status:/type:/priority:) in the query are parsed as filters, e.g. 'auth tag:area:search status:open'.").option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("search","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--mode <value>","Search mode: keyword|semantic|hybrid (default: auto)").option("--semantic","Shorthand for --mode semantic").option("--hybrid","Shorthand for --mode hybrid").option("--match-mode <value>","Token match mode: and|or|exact (default: or with all-terms ranking bonus; and = hard-require every token; exact = exact phrase)").option("--min-score <value>","Per-query minimum score threshold (finite number >= 0); overrides settings search.score_threshold for this query only").option("--count","Return only the count of matching items (post-filter/threshold, pre-limit); skips hit rows").option("--semantic-weight <value>","Override hybrid semantic weight for this query (0..1); invalid values fall back to settings").option("--include-linked","Include linked files, docs, and tests in the searchable corpus").option("--title-exact","Require exact normalized title match for the full query string").option("--phrase-exact","Require exact normalized phrase match in searchable text").option("--highlight","Emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit; off by default").option("--status <value>","Filter by status before query (all, open/closed/canceled aliases, or configured status id; CSV)").option("--type <value>","Filter by item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--deadline-before <value>","Filter by deadline upper bound (ISO/date string or relative)").option("--deadline-after <value>","Filter by deadline lower bound (ISO/date string or relative)").option("--updated-after <value>",'Filter by updated_at lower bound: ISO timestamp or signed relative (e.g. "-2h"/"-7d" for the past)').option("--updated-before <value>","Filter by updated_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-after <value>","Filter by created_at lower bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-before <value>","Filter by created_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--assignee <value>","Filter by assignee").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release").option("--parent <value>","Filter by parent item ID").option("--compact","Render compact search hits (default; mutually exclusive with --full/--fields)").option("--full","Render full search hits with nested item payloads (mutually exclusive with --compact/--fields)").option("--fields <value>",`Render custom comma-separated search hit fields (mutually exclusive with --compact/--full). ${renderPmClosedDomainHelp("search","--fields")}`).option("--format <value>","Search output format override: json|ndjson|toon").option("--limit <n>","Limit returned item count").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor");registerContentAndGovernanceFilters(searchCommand),searchCommand.action(runSearchAction),addHiddenOption(searchCommand,"--tags <value>","Alias for --tag"),addHiddenOption(searchCommand,"--token_budget <n>","Alias for --token-budget")}if(shouldRegister("eval")&&program.command("eval").description("Evaluate search relevance against a curated golden-query set: reports nDCG@k, MRR@k, precision@k, and recall@k per query plus the macro average. Use --fail-under as a CI gate.").option("--mode <value>","Default retrieval mode for queries without their own: keyword|semantic|hybrid (default: keyword)").option("--k <n>","Metric cutoff @k (positive integer; default: 10)").option("--fail-under <value>","Exit non-zero when aggregate nDCG@k falls below this threshold (0..1); CI gate").option("--queries <path>",`Query JSON (${EVAL_QUERY_SET_SCHEMA_ID}); default: search/eval-queries.json; errors show an example`).option("--format <value>","Eval output format override: json|toon").action(runEvalAction),shouldRegister("get")){const getCommand=program.command("get").argument("<id>","Item id").option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("get","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--depth <value>","brief|standard|deep|full (default: standard)").option("--full","Full details and children for any type; excludes --depth/--fields").option("--fields <value>",`Render custom comma-separated item metadata fields. ${renderPmClosedDomainHelp("get","--fields")}`).option("--tree","Include descendants rooted at the requested item").option("--tree-depth <n>","Maximum subtree depth for --tree descendants").option("--at <version-or-timestamp>","Reconstruct a verified historical item state without mutating it").option("--format <value>","Get output format override: json|toon").description("Show item details by ID.").action(runGetAction);addHiddenOption(getCommand,"--tree_depth <n>","Alias for --tree-depth"),addHiddenOption(getCommand,"--token_budget <n>","Alias for --token-budget")}if(shouldRegister("history")){const historyCommand=program.command("history").enablePositionalOptions().argument("<id>","Item id").option("--limit <n>","Latest n entries").option("--compact","Index, time, op, author, patch count, fields").option("--full","Full entries with JSON Patches").option("--provenance","Authors and provenance; no patches").option("--provenance-summary","Count provenance completeness").option("--harness <value>","Recorded/resolved harness (repeatable)",collect).option("--agent-instance <value>","Agent instance (repeatable)",collect).option("--provenance-filter <dimension=value>","Exact provenance match (repeatable)",collect).option("--diff","Before/after field diffs").option("--field <name>","Filter changed field; implies --diff").option("--verify","Verify full chain and replay").option("--strict-exit","With --verify, fail on integrity errors").option("--fail-on-warn","Alias for --strict-exit").option("--format <value>","Output: json|toon").description("Show item history entries.").action(runHistoryAction);registerHistoryMaintenanceCommands(historyCommand,!0),registerHistoryActivityCommand(historyCommand.command("activity"))}shouldRegister("events")&&program.command("events").option("--since <cursor-or-timestamp>","Resume strictly after a durable cursor, or include events from an ISO timestamp").option("--type <value>","Filter by mutation operation (repeatable or comma-separated)",collect).option("--author <value>","Filter by mutation author (repeatable or comma-separated)",collect).option("--item <value>","Filter by item or workspace stream id (repeatable or comma-separated)",collect).option("--limit <n>","Return at most 1,000 events (default: 100)").option("--cursor-mode <mode>","Cursor framing: batch emits one terminal trailer (default); row preserves one cursor per event").option("--full","Include each complete authoritative history entry").option("--provenance","Include 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("--follow","Continue emitting committed events as newline-delimited JSON").option("--interval-ms <n>","Empty-read delay while following (minimum: 10ms; default: 250ms)").description("Emit cursor-resumable committed mutation facts as newline-delimited JSON.").action(runEventsAction),shouldRegister("activity")&&registerHistoryActivityCommand(program.command("activity",{hidden:!0})),shouldRegister("graph")&&program.command("graph").argument("<subcommand>","Graph query (ancestors, descendants, predecessors, successors, paths, impact, analyze, audit, communities, redundancy, dominators, slack, centrality, articulation, plan, index)").argument("[id]","Root item id (traversals, paths, impact, and dominators)").argument("[target]","Target item id (paths only)").option("--kind <value>","Restrict traversal to registered relationship kinds (repeatable or comma-separated)",collect).option("--max-depth <value>","Maximum traversal depth (non-negative integer)").option("--limit <value>","Maximum returned rows per bounded collection").option("--after <value>","Resume a traversal after this previously returned node id").option("--direction <value>","Edge orientation for paths/impact (outgoing, incoming, or both)").option("--max-paths <value>","Maximum enumerated paths (paths only)").option("--sample <value>","Maximum evidence sample entries per audit finding (audit only)").option("--exempt-isolate <value>","Item ids treated as explicitly valid isolates by the audit (repeatable or comma-separated)",collect).option("--exempt-isolate-type <value>","Item types whose active isolates are policy-valid for the audit (repeatable or comma-separated)",collect).option("--save-baseline","Persist the audit census as the change-since-baseline comparison point (audit only)").option("--rebuild","Rebuild and warm the durable graph index (index only)").option("--clear","Delete the durable graph index (index only)").option("--summary","Return counts-first envelopes without row collections").option("--full","Return the complete graph row projection").description("Bounded workspace relationship-graph queries, analytics, and governance audit.").action(runGraphAction)}const _testOnlyRegisterListQuery={resolveReadCommandOutputFormat,parseListFormat};export{_testOnlyRegisterListQuery,registerListQueryCommands};
7
+ `)}else printResult(result,effectiveGlobal);globalOptions.profile&&printError(`profile:command=search took_ms=${Date.now()-startedAt}`)}async function runEvalAction(options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runEval({mode:typeof options.mode=="string"?options.mode:void 0,k:typeof options.k=="string"?options.k:void 0,failUnder:typeof options.failUnder=="string"?options.failUnder:void 0,queries:typeof options.queries=="string"?options.queries:void 0,format:typeof options.format=="string"?options.format:void 0},globalOptions);if(printResult(result,resolveReadCommandOutputFormat("Eval",options.format,globalOptions)),globalOptions.profile&&printError(`profile:command=eval took_ms=${Date.now()-startedAt}`),!result.passed)throw new PmCliError("Eval gate failed: one or more aggregate or per-query thresholds were not met; inspect the metric report",EXIT_CODE.GENERIC_FAILURE)}async function runGetAction(id,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),intentOptions=applyContextIntentProjection("get",options,[id]),result=await runGet(id,globalOptions,{depth:typeof intentOptions.depth=="string"?intentOptions.depth:void 0,fields:typeof intentOptions.fields=="string"?intentOptions.fields:void 0,full:!!intentOptions.full,tree:intentOptions.tree===!0,treeDepth:typeof intentOptions.treeDepth=="string"?intentOptions.treeDepth:typeof intentOptions.tree_depth=="string"?intentOptions.tree_depth:void 0,at:typeof intentOptions.at=="string"?intentOptions.at:void 0});printResult(result,resolveReadCommandOutputFormat("Get",intentOptions.format,globalOptions)),globalOptions.profile&&printError(`profile:command=get took_ms=${Date.now()-startedAt}`)}async function runHistoryAction(id,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now();if([options.compact,options.raw,options.full,options.provenance].filter(value=>value===!0).length>1)throw new PmCliError("History projection options are mutually exclusive. Use --compact, --provenance, or --full.",EXIT_CODE.USAGE);const field=typeof options.field=="string"?options.field:void 0,strictExit=!!options.strictExit||!!options.failOnWarn;if(strictExit&&!options.verify)throw new PmCliError("--strict-exit requires --verify (it gates on the verification result).",EXIT_CODE.USAGE);const result=await runHistory(id,{limit:typeof options.limit=="string"?options.limit:void 0,compact:!(options.full===!0||options.provenance===!0),provenance:options.provenance===!0,provenanceSummary:options.provenanceSummary===!0,harness:readRepeatableStringOption(options,"harness"),agentInstance:readRepeatableStringOption(options,"agentInstance"),provenanceFilter:readRepeatableStringOption(options,"provenanceFilter"),diff:!!options.diff||field!==void 0,field,verify:!!options.verify},globalOptions);printResult(result,resolveReadCommandOutputFormat("History",options.format,globalOptions)),strictExit&&result.verification&&!result.verification.ok&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE),globalOptions.profile&&printError(`profile:command=history took_ms=${Date.now()-startedAt}`)}function readRepeatableStringOption(options,key){const value=options[key];return Array.isArray(value)?value:void 0}function buildMutationEventOptions(options,pmRoot){const harness=readRepeatableStringOption(options,"harness"),agentInstance=readRepeatableStringOption(options,"agentInstance"),provenanceFilter=readRepeatableStringOption(options,"provenanceFilter"),rawCursorMode=typeof options.cursorMode=="string"?options.cursorMode:void 0;if(rawCursorMode!==void 0&&rawCursorMode!=="batch"&&rawCursorMode!=="row")throw new PmCliError("Events --cursor-mode must be batch or row.",EXIT_CODE.USAGE,{code:"invalid_event_cursor_mode"});const cursorMode=rawCursorMode;return{pmRoot,since:typeof options.since=="string"?options.since:void 0,type:readRepeatableStringOption(options,"type"),author:readRepeatableStringOption(options,"author"),item:readRepeatableStringOption(options,"item"),limit:typeof options.limit=="string"?Number(options.limit):void 0,full:options.full===!0,...options.verify===!0?{verify:!0}:{},...options.provenance===!0?{provenance:!0}:{},...options.provenanceSummary===!0?{provenanceSummary:!0}:{},...harness===void 0?{}:{harness},...agentInstance===void 0?{}:{agentInstance},...provenanceFilter===void 0?{}:{provenanceFilter},cursorMode}}async function followMutationEvents(eventOptions,options,quiet){if(options.provenanceSummary===!0)throw new PmCliError("Events --provenance-summary is bounded to one page and cannot be combined with --follow.",EXIT_CODE.USAGE);const intervalMs=typeof options.intervalMs=="string"?Number(options.intervalMs):void 0;if(eventOptions.cursorMode==="row"){for await(const event of subscribeMutationEvents({...eventOptions,intervalMs}))quiet||writeStdout(`${JSON.stringify(event)}
8
+ `);return}for await(const page of subscribeMutationEventBatches({...eventOptions,intervalMs}))quiet||writeStdout(`${serializeNdjsonStream(page.events,{count:page.count,has_more:page.has_more,next_cursor:page.next_cursor??null,source:page.source,integrity:page.integrity,...page.verified_streams===void 0?{}:{verified_streams:page.verified_streams},heartbeat:page.count===0})}
9
+ `)}function renderMutationEventPage(page){return page.cursor_mode==="row"?serializeNdjsonRows(page.events):serializeNdjsonStream(page.events,{count:page.count,has_more:page.has_more,next_cursor:page.next_cursor??null,source:page.source,integrity:page.integrity,...page.verified_streams===void 0?{}:{verified_streams:page.verified_streams},...page.provenance_summary===void 0?{}:{provenance_summary:page.provenance_summary}})}async function runEventsAction(options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),eventOptions=buildMutationEventOptions(options,globalOptions.path);if(options.follow===!0){await followMutationEvents(eventOptions,options,globalOptions.quiet===!0);return}const page=await listMutationEvents(eventOptions);if(setActiveCommandResult(page),globalOptions.json){printResult(page,globalOptions),globalOptions.profile&&printError(`profile:command=events took_ms=${Date.now()-startedAt}`);return}const rendered=renderMutationEventPage(page);!globalOptions.quiet&&rendered.length>0&&writeStdout(`${rendered}
10
+ `),globalOptions.profile&&printError(`profile:command=events took_ms=${Date.now()-startedAt}`)}async function runGraphAction(subcommand,id,target,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runGraph(subcommand,id,target,{...Array.isArray(options.kind)?{kind:options.kind}:{},maxDepth:typeof options.maxDepth=="string"?options.maxDepth:void 0,limit:typeof options.limit=="string"?options.limit:void 0,after:typeof options.after=="string"?options.after:void 0,direction:typeof options.direction=="string"?options.direction:void 0,maxPaths:typeof options.maxPaths=="string"?options.maxPaths:void 0,sample:typeof options.sample=="string"?options.sample:void 0,...Array.isArray(options.exemptIsolate)?{exemptIsolate:options.exemptIsolate}:{},...Array.isArray(options.exemptIsolateType)?{exemptIsolateType:options.exemptIsolateType}:{},saveBaseline:options.saveBaseline===!0,rebuild:options.rebuild===!0,clear:options.clear===!0,summary:options.summary===!0,full:options.full===!0},globalOptions);printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=graph took_ms=${Date.now()-startedAt}`)}function registerListQueryCommands(program,options){const commandFilter=options?.commandFilter,shouldRegister=commandName=>shouldRegisterListQueryCommand(commandName,commandFilter),listCommandDescriptors=[{name:"list",description:"List active items with optional lifecycle-status and project filters.",excludeTerminal:!0,allowStatusFilter:!0},{name:"list-all",description:"List all items with optional filters.",excludeTerminal:!1,allowStatusFilter:!0},{name:"list-draft",description:"List draft items with optional filters.",status:"draft"},{name:"list-open",description:"List open items with optional filters.",status:"open",excludeTerminal:!1,allowStatusFilter:!1},{name:"list-in-progress",description:"List in-progress items with optional filters.",status:"in_progress",excludeTerminal:!1,allowStatusFilter:!1},{name:"list-blocked",description:"List blocked items (blocked status or open blocked_by dependencies, matching pm next) with optional filters.",dependencyBlocked:!0,excludeTerminal:!1,allowStatusFilter:!1},{name:"list-closed",description:"List closed items with optional filters.",status:"closed"},{name:"list-canceled",description:"List canceled items with optional filters.",status:"canceled"}];for(const descriptor of listCommandDescriptors)if(shouldRegister(descriptor.name)){const aliasContract=resolvePmCommandAlias(descriptor.name);registerListCommand(program,{...descriptor,...aliasContract?.registration==="commander"?{aliasContract}:{}})}if(shouldRegister("aggregate")){const aggregateCommand=program.command("aggregate").description("Group item counts and numeric measures.").option("--set-mode <value>","Set grouping: element (default)|tuple").option("--limit <value>","Group page size (default: 50)").option("--after <value>","Continue with next_after cursor").option("--group-by <value>","Fields: parent,type,priority,status,assignee,tags,sprint,release (comma-separated)").option("--count","Counts (default)").option("--completion","Status counts and completion_pct").option("--sum <field>","Group numeric sum").option("--avg <field>","Group numeric average").option("--include-unparented","Keep unparented group").option("--status <value>","Item status").option("--type <value>","Item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--deadline-before <value>","Latest deadline (ISO/date or relative)").option("--deadline-after <value>","Earliest deadline (ISO/date or relative)").option("--assignee <value>","Filter by assignee").option("--assignee-filter <value>","Assignee presence: assigned|unassigned").option("--parent <value>","Parent ID").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release");addHiddenOption(aggregateCommand,"--include_unparented","Alias for --include-unparented"),addHiddenOption(aggregateCommand,"--assignee_filter <value>","Alias for --assignee-filter"),aggregateCommand.action(runAggregateAction)}if(shouldRegister("context")){const contextCommand=program.command("context").alias("ctx").description("Show a token-efficient project context snapshot for next-work decisions.").option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("context","--for")}`).option("--date <value>","Anchor date/time for agenda window calculations (ISO/date string or relative)").option("--from <value>","Agenda lower bound (ISO/date string or relative)").option("--to <value>","Agenda upper bound (ISO/date string or relative)").option("--past","Include past agenda entries in bounded windows").option("--type <value>","Filter by item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--assignee <value>","Filter by assignee").option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release").option("--parent <id>","Scope the snapshot to one item's subtree (the item plus all descendants)").option("--limit <n>","Limit focus and agenda rows per section").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor").option("--format <value>","Context output format override: markdown|toon|json|ndjson").option("--depth <value>","Context depth: brief|standard|deep|full (full = every section, no per-section cap)").option("--section <value...>","Include specific sections (repeatable; overrides --depth)").option("--fields <value>","Project focus rows to a comma-separated field subset (e.g. id,title,priority)").option("--activity-limit <n>","Limit recent activity entries (default: settings or 10)").option("--stale-threshold <value>","Staleness cutoff in days (e.g. 7 or 7d; default: settings or 7)").option("--explain-ranking","Include the scorer model, per-signal contributions, and ranked candidate ids").option("--token-budget <n>","Complete JSON/TOON response token ceiling").option("--no-extension-health","Omit the installed extension health summary").option("--no-tags","Omit tag arrays from context focus rows");addHiddenOption(contextCommand,"--assignee_filter <value>","Alias for --assignee-filter"),addHiddenOption(contextCommand,"--max-items <n>","Alias for --limit"),addHiddenOption(contextCommand,"--explain_ranking","Alias for --explain-ranking"),addHiddenOption(contextCommand,"--token_budget <n>","Alias for --token-budget"),contextCommand.action(runContextAction)}if(shouldRegister("next")){const nextCommand=program.command("next").description("Recommend the next actionable (unblocked, ready) work item with rationale + blocked companion.").option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("next","--for")}`).option("--type <value>","Filter candidate items by type").option("--tag <value>","Filter candidate items by tag").option("--priority <value>","Filter candidate items by priority").option("--assignee <value>","Filter candidate items by assignee").option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--sprint <value>","Filter candidate items by sprint").option("--release <value>","Filter candidate items by release").option("--parent <id>","Scope to one item's subtree (the item plus all descendants)").option("--limit <n>","Limit ready rows (default: 5; non-positive falls back to default)").option("--blocked-limit <n>","Limit blocked rows (default: same as --limit)").option("--ready-only","Omit the blocked companion list").option("--include-decisions","Include human-gated Decision items in the claimable ready queue").option("--include-gates","Include outcome gates in the ready queue").option("--include-containers","Include containers with unfinished descendants in the ready queue").option("--format <value>","Next output format override: markdown|toon|json").option("--explain-ranking","Include the scorer model, per-signal contributions, and ranked ready ids").option("--token-budget <n>","Maximum estimated tokens spent on the ranked ready queue");addHiddenOption(nextCommand,"--assignee_filter <value>","Alias for --assignee-filter"),addHiddenOption(nextCommand,"--blocked_limit <n>","Alias for --blocked-limit"),addHiddenOption(nextCommand,"--ready_only","Alias for --ready-only"),addHiddenOption(nextCommand,"--explain_ranking","Alias for --explain-ranking"),addHiddenOption(nextCommand,"--token_budget <n>","Alias for --token-budget"),nextCommand.action(runNextAction)}if(shouldRegister("search")){const searchCommand=program.command("search").argument("<keywords...>","Keyword query tokens").description("Search items with keyword, semantic, or hybrid retrieval. Inline field:value tokens (tag:/status:/type:/priority:) in the query are parsed as filters, e.g. 'auth tag:area:search status:open'.").option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("search","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--mode <value>","Search mode: keyword|semantic|hybrid (default: auto)").option("--semantic","Shorthand for --mode semantic").option("--hybrid","Shorthand for --mode hybrid").option("--match-mode <value>","Token match mode: and|or|exact (default: or with all-terms ranking bonus; and = hard-require every token; exact = exact phrase)").option("--min-score <value>","Per-query minimum score threshold (finite number >= 0); overrides settings search.score_threshold for this query only").option("--count","Return only the count of matching items (post-filter/threshold, pre-limit); skips hit rows").option("--semantic-weight <value>","Override hybrid semantic weight for this query (0..1); invalid values fall back to settings").option("--include-linked","Include linked files, docs, and tests in the searchable corpus").option("--title-exact","Require exact normalized title match for the full query string").option("--phrase-exact","Require exact normalized phrase match in searchable text").option("--highlight","Emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit; off by default").option("--status <value>","Filter by status before query (all, open/closed/canceled aliases, or configured status id; CSV)").option("--type <value>","Filter by item type").option("--tag <value>","Filter by tag").option("--priority <value>","Filter by priority").option("--deadline-before <value>","Filter by deadline upper bound (ISO/date string or relative)").option("--deadline-after <value>","Filter by deadline lower bound (ISO/date string or relative)").option("--updated-after <value>",'Filter by updated_at lower bound: ISO timestamp or signed relative (e.g. "-2h"/"-7d" for the past)').option("--updated-before <value>","Filter by updated_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-after <value>","Filter by created_at lower bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-before <value>","Filter by created_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--assignee <value>","Filter by assignee").option("--sprint <value>","Filter by sprint").option("--release <value>","Filter by release").option("--parent <value>","Filter by parent item ID").option("--compact","Render compact search hits (default; mutually exclusive with --full/--fields)").option("--full","Render full search hits with nested item payloads (mutually exclusive with --compact/--fields)").option("--fields <value>",`Render custom comma-separated search hit fields (mutually exclusive with --compact/--full). ${renderPmClosedDomainHelp("search","--fields")}`).option("--format <value>","Search output format override: json|ndjson|toon").option("--limit <n>","Limit returned item count").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor");registerContentAndGovernanceFilters(searchCommand),searchCommand.action(runSearchAction),addHiddenOption(searchCommand,"--tags <value>","Alias for --tag"),addHiddenOption(searchCommand,"--token_budget <n>","Alias for --token-budget")}if(shouldRegister("eval")&&program.command("eval").description("Evaluate search relevance against a curated golden-query set: reports nDCG@k, MRR@k, precision@k, and recall@k per query plus the macro average. Use --fail-under as a CI gate.").option("--mode <value>","Default retrieval mode for queries without their own: keyword|semantic|hybrid (default: keyword)").option("--k <n>","Metric cutoff @k (positive integer; default: 10)").option("--fail-under <value>","Exit non-zero when aggregate nDCG@k falls below this threshold (0..1); CI gate").option("--queries <path>",`Query JSON (${EVAL_QUERY_SET_SCHEMA_ID}); default: search/eval-queries.json; errors show an example`).option("--format <value>","Eval output format override: json|toon").action(runEvalAction),shouldRegister("get")){const getCommand=program.command("get").argument("<id>","Item id").option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("get","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--depth <value>","brief|standard|deep|full (default: standard)").option("--full","Full details and children for any type; excludes --depth/--fields").option("--fields <value>",`Render custom comma-separated item metadata fields. ${renderPmClosedDomainHelp("get","--fields")}`).option("--tree","Include descendants rooted at the requested item").option("--tree-depth <n>","Maximum subtree depth for --tree descendants").option("--at <version-or-timestamp>","Reconstruct a verified historical item state without mutating it").option("--format <value>","Get output format override: json|toon").description("Show item details by ID.").action(runGetAction);addHiddenOption(getCommand,"--tree_depth <n>","Alias for --tree-depth"),addHiddenOption(getCommand,"--token_budget <n>","Alias for --token-budget")}if(shouldRegister("history")){const historyCommand=program.command("history").enablePositionalOptions().argument("<id>","Item id").option("--limit <n>","Latest n entries").option("--compact","Index, time, op, author, patch count, fields").option("--full","Full entries with JSON Patches").option("--provenance","Authors and provenance; no patches").option("--provenance-summary","Count provenance completeness").option("--harness <value>","Recorded/resolved harness (repeatable)",collect).option("--agent-instance <value>","Agent instance (repeatable)",collect).option("--provenance-filter <dimension=value>","Exact provenance match (repeatable)",collect).option("--diff","Before/after field diffs").option("--field <name>","Filter changed field; implies --diff").option("--verify","Verify full chain and replay").option("--strict-exit","With --verify, fail on integrity errors").option("--fail-on-warn","Alias for --strict-exit").option("--format <value>","Output: json|toon").description("Show item history entries.").action(runHistoryAction);registerHistoryMaintenanceCommands(historyCommand,!0),registerHistoryActivityCommand(historyCommand.command("activity"))}shouldRegister("events")&&program.command("events").option("--since <cursor-or-timestamp>","Resume strictly after a durable cursor, or include events from an ISO timestamp").option("--type <value>","Filter by mutation operation (repeatable or comma-separated)",collect).option("--author <value>","Filter by mutation author (repeatable or comma-separated)",collect).option("--item <value>","Filter by item or workspace stream id (repeatable or comma-separated)",collect).option("--limit <n>","Return at most 1,000 events (default: 100)").option("--cursor-mode <mode>","Cursors: batch trailer (default) or per-row").option("--full","Include each complete authoritative history entry").option("--verify","Verify selected authoritative history chains").option("--provenance","Include 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("--follow","Follow committed events as NDJSON").option("--interval-ms <n>","Empty-read delay while following (minimum: 10ms; default: 250ms)").description("Read mutation events as NDJSON with resumable cursors.").action(runEventsAction),shouldRegister("activity")&&registerHistoryActivityCommand(program.command("activity",{hidden:!0})),shouldRegister("graph")&&program.command("graph").argument("<subcommand>","Graph query (ancestors, descendants, predecessors, successors, paths, impact, analyze, audit, communities, redundancy, dominators, slack, centrality, articulation, plan, index)").argument("[id]","Root item id (traversals, paths, impact, and dominators)").argument("[target]","Target item id (paths only)").option("--kind <value>","Restrict traversal to registered relationship kinds (repeatable or comma-separated)",collect).option("--max-depth <value>","Maximum traversal depth (non-negative integer)").option("--limit <value>","Maximum returned rows per bounded collection").option("--after <value>","Resume a traversal after this previously returned node id").option("--direction <value>","Edge orientation for paths/impact (outgoing, incoming, or both)").option("--max-paths <value>","Maximum enumerated paths (paths only)").option("--sample <value>","Maximum evidence sample entries per audit finding (audit only)").option("--exempt-isolate <value>","Item ids treated as explicitly valid isolates by the audit (repeatable or comma-separated)",collect).option("--exempt-isolate-type <value>","Item types whose active isolates are policy-valid for the audit (repeatable or comma-separated)",collect).option("--save-baseline","Persist the audit census as the change-since-baseline comparison point (audit only)").option("--rebuild","Rebuild and warm the durable graph index (index only)").option("--clear","Delete the durable graph index (index only)").option("--summary","Return counts-first envelopes without row collections").option("--full","Return the complete graph row projection").description("Bounded workspace relationship-graph queries, analytics, and governance audit.").action(runGraphAction)}const _testOnlyRegisterListQuery={resolveReadCommandOutputFormat,parseListFormat};export{_testOnlyRegisterListQuery,registerListQueryCommands};
11
11
  //# sourceMappingURL=register-list-query.js.map