@unbrained/pm-cli 2026.9.6 → 2026.9.8

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 (719) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +12 -4
  2. package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +19 -10
  3. package/.agents/skills/pm-extensions/SKILL.md +6 -0
  4. package/.agents/skills/pm-sdk/SKILL.md +11 -2
  5. package/.agents/skills/pm-user/SKILL.md +5 -0
  6. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
  7. package/.claude-plugin/marketplace.json +2 -2
  8. package/CHANGELOG.md +218 -182
  9. package/dist/cli/after-command-context-usage.js +1 -48
  10. package/dist/cli/argv-utils.js +1 -40
  11. package/dist/cli/bootstrap-args.js +1 -9
  12. package/dist/cli/bundle-integrity.js +2 -110
  13. package/dist/cli/commander-usage.js +11 -771
  14. package/dist/cli/commands/activity.js +1 -9
  15. package/dist/cli/commands/aggregate.js +1 -5
  16. package/dist/cli/commands/append.js +1 -5
  17. package/dist/cli/commands/claim.js +1 -5
  18. package/dist/cli/commands/close-many.js +1 -5
  19. package/dist/cli/commands/close.js +1 -9
  20. package/dist/cli/commands/comments.js +1 -5
  21. package/dist/cli/commands/config.js +1 -9
  22. package/dist/cli/commands/context.js +1 -9
  23. package/dist/cli/commands/contracts.js +1 -5
  24. package/dist/cli/commands/copy.js +1 -9
  25. package/dist/cli/commands/create.js +1 -9
  26. package/dist/cli/commands/delete.js +1 -9
  27. package/dist/cli/commands/deps.js +1 -9
  28. package/dist/cli/commands/docs.js +1 -9
  29. package/dist/cli/commands/duplicates.js +1 -9
  30. package/dist/cli/commands/eval.js +1 -9
  31. package/dist/cli/commands/extension/describe.js +1 -5
  32. package/dist/cli/commands/extension/scaffold.js +1 -5
  33. package/dist/cli/commands/extension/shared.js +1 -5
  34. package/dist/cli/commands/extension.js +1 -9
  35. package/dist/cli/commands/files.js +1 -9
  36. package/dist/cli/commands/focus.js +1 -9
  37. package/dist/cli/commands/gc.js +1 -9
  38. package/dist/cli/commands/get.js +1 -9
  39. package/dist/cli/commands/graph.js +1 -10
  40. package/dist/cli/commands/health.js +1 -9
  41. package/dist/cli/commands/history-compact.js +1 -10
  42. package/dist/cli/commands/history-redact.js +1 -11
  43. package/dist/cli/commands/history-repair.js +1 -10
  44. package/dist/cli/commands/history.js +1 -5
  45. package/dist/cli/commands/index.js +1 -58
  46. package/dist/cli/commands/init-agent-guidance.js +1 -9
  47. package/dist/cli/commands/init.js +1 -9
  48. package/dist/cli/commands/learnings.js +1 -5
  49. package/dist/cli/commands/lifecycle-transitions.js +1 -5
  50. package/dist/cli/commands/list.js +1 -9
  51. package/dist/cli/commands/merge.js +1 -11
  52. package/dist/cli/commands/next.js +1 -9
  53. package/dist/cli/commands/notes.js +1 -5
  54. package/dist/cli/commands/plan.js +1 -9
  55. package/dist/cli/commands/profile.js +1 -9
  56. package/dist/cli/commands/restore.js +1 -9
  57. package/dist/cli/commands/scheduling-shortcuts.js +1 -9
  58. package/dist/cli/commands/schema.js +1 -10
  59. package/dist/cli/commands/search.js +1 -9
  60. package/dist/cli/commands/stats.js +1 -9
  61. package/dist/cli/commands/telemetry.js +1 -9
  62. package/dist/cli/commands/test-all.js +1 -9
  63. package/dist/cli/commands/test-runs.js +1 -9
  64. package/dist/cli/commands/test.js +1 -9
  65. package/dist/cli/commands/update-many.js +1 -5
  66. package/dist/cli/commands/update.js +1 -9
  67. package/dist/cli/commands/upgrade.js +1 -5
  68. package/dist/cli/commands/validate.js +1 -15
  69. package/dist/cli/context-intent-invocation.js +1 -20
  70. package/dist/cli/description-stdin.js +1 -17
  71. package/dist/cli/error-guidance.js +1 -1353
  72. package/dist/cli/extension-command-help.js +5 -636
  73. package/dist/cli/extension-command-options.js +1 -427
  74. package/dist/cli/extension-recovery.js +1 -126
  75. package/dist/cli/help-content.js +2 -1001
  76. package/dist/cli/help-json-payload.js +4 -570
  77. package/dist/cli/main.d.ts +4 -0
  78. package/dist/cli/main.js +5 -2573
  79. package/dist/cli/migration-gates.js +1 -289
  80. package/dist/cli/public.js +1 -20
  81. package/dist/cli/register-annotations.js +1 -270
  82. package/dist/cli/register-assurance.js +1 -62
  83. package/dist/cli/register-files-lookup.js +1 -56
  84. package/dist/cli/register-history-activity.d.ts +8 -0
  85. package/dist/cli/register-history-activity.js +2 -0
  86. package/dist/cli/register-history-author.js +1 -38
  87. package/dist/cli/register-history-maintenance.d.ts +9 -0
  88. package/dist/cli/register-history-maintenance.js +2 -0
  89. package/dist/cli/register-list-query.js +10 -943
  90. package/dist/cli/register-mutation-options.js +1 -9
  91. package/dist/cli/register-mutation.js +19 -1893
  92. package/dist/cli/register-operations.js +1 -920
  93. package/dist/cli/register-setup.js +1 -716
  94. package/dist/cli/register-structured-mutation.js +1 -196
  95. package/dist/cli/registration-helpers.js +1 -5
  96. package/dist/cli/runtime-compatibility-boundary.js +4 -42
  97. package/dist/cli/schema-registration-helpers.js +1 -73
  98. package/dist/cli/search-refresh.js +1 -13
  99. package/dist/cli/stats-analytics-json.js +1 -68
  100. package/dist/cli/telemetry-flush.js +1 -10
  101. package/dist/cli-bundle/bundle-manifest.json +164 -156
  102. package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +5 -0
  103. package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +235 -0
  104. package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +2202 -0
  105. package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
  106. package/dist/cli-bundle/chunks/chunk-FLDWYEND.js +77 -0
  107. package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-G5ADGQ2D.js} +3 -3
  108. package/dist/cli-bundle/chunks/chunk-JAAEYHUA.js +2 -0
  109. package/dist/cli-bundle/chunks/{chunk-JX4DH4WC.js → chunk-KR3RP4FH.js} +3 -3
  110. package/dist/cli-bundle/chunks/chunk-LEZOUXG6.js +2 -0
  111. package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
  112. package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +29 -0
  113. package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +2 -0
  114. package/dist/cli-bundle/chunks/chunk-XOD2PCB6.js +20 -0
  115. package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-YVEQ2AMO.js} +4 -4
  116. package/dist/cli-bundle/chunks/register-list-query-KSK3R63M.js +11 -0
  117. package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +20 -0
  118. package/dist/cli-bundle/chunks/{register-operations-I5W3KMGB.js → register-operations-DWVHR2NC.js} +2 -2
  119. package/dist/cli-bundle/chunks/register-setup-BQ5SVD4B.js +2 -0
  120. package/dist/cli-bundle/focused-chunks/chunk-3WRPWLA7.js +3 -0
  121. package/dist/cli-bundle/focused-chunks/chunk-7MBUII7U.js +2 -0
  122. package/dist/cli-bundle/focused-chunks/chunk-COPBO5HW.js +8 -0
  123. package/dist/cli-bundle/focused-chunks/chunk-DUN4IXYN.js +20 -0
  124. package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-EE5QSM4Z.js} +3 -3
  125. package/dist/cli-bundle/focused-chunks/chunk-HJVARYM3.js +6 -0
  126. package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +177 -0
  127. package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +2 -0
  128. package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +56 -0
  129. package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-OPFHFGDD.js} +2 -2
  130. package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +9 -0
  131. package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-RMWES4M6.js} +2 -2
  132. package/dist/cli-bundle/focused-chunks/chunk-RXT4P5QH.js +10 -0
  133. package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +12 -0
  134. package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +2 -0
  135. package/dist/cli-bundle/focused-chunks/{chunk-PEFABF7E.js → chunk-WE3IUNIW.js} +3 -3
  136. package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +2 -0
  137. package/dist/cli-bundle/main.js +20 -20
  138. package/dist/cli-bundle/sdk-authoring.js +1 -1
  139. package/dist/cli-bundle/sdk-contracts.js +2 -2
  140. package/dist/cli-bundle/sdk-core.js +29 -29
  141. package/dist/cli-bundle/sdk-governance.js +1 -1
  142. package/dist/cli-bundle/sdk-graph.js +1 -1
  143. package/dist/cli-bundle/sdk-merge.js +42 -42
  144. package/dist/cli-bundle/sdk-query.js +1 -1
  145. package/dist/cli-bundle/sdk-runtime.js +1 -1
  146. package/dist/cli-bundle/sdk-testing.js +1 -1
  147. package/dist/cli-bundle/sdk.js +11 -11
  148. package/dist/cli.js +1 -104
  149. package/dist/core/checkpoint/checkpoint-gc.js +1 -169
  150. package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
  151. package/dist/core/config/nested-settings.js +1 -534
  152. package/dist/core/config/positional-value.js +1 -109
  153. package/dist/core/diagnostics/remediation.js +1 -506
  154. package/dist/core/extensions/activation-summary-markdown.js +2 -145
  155. package/dist/core/extensions/activation-summary.js +1 -92
  156. package/dist/core/extensions/activation-transaction.js +1 -46
  157. package/dist/core/extensions/capability-usage.js +1 -173
  158. package/dist/core/extensions/command-hook-context.js +1 -13
  159. package/dist/core/extensions/command-metadata-contract.js +1 -22
  160. package/dist/core/extensions/command-visibility-tier.js +1 -29
  161. package/dist/core/extensions/contribution-inventory.js +1 -173
  162. package/dist/core/extensions/exporter-output-contract.js +1 -66
  163. package/dist/core/extensions/extension-candidate.js +1 -18
  164. package/dist/core/extensions/extension-capability-aliases.js +1 -158
  165. package/dist/core/extensions/extension-hook-runtime.js +1 -699
  166. package/dist/core/extensions/extension-policy.js +1 -599
  167. package/dist/core/extensions/extension-registries.js +1 -62
  168. package/dist/core/extensions/extension-runtime-helpers.js +1 -33
  169. package/dist/core/extensions/extension-types.js +1 -102
  170. package/dist/core/extensions/flag-definition-validation.js +1 -52
  171. package/dist/core/extensions/flag-value-types.js +1 -64
  172. package/dist/core/extensions/index.js +1 -526
  173. package/dist/core/extensions/item-field-types.js +1 -39
  174. package/dist/core/extensions/item-fields.js +1 -261
  175. package/dist/core/extensions/loader.js +1 -2223
  176. package/dist/core/extensions/manifest-schema.js +1 -69
  177. package/dist/core/extensions/module-graph-snapshot.js +1 -33
  178. package/dist/core/extensions/preflight-ownership.js +1 -41
  179. package/dist/core/extensions/registration-validation.js +1 -82
  180. package/dist/core/extensions/registration-values.js +1 -209
  181. package/dist/core/extensions/reserved-host-flags.js +1 -36
  182. package/dist/core/extensions/runtime-registrations.js +1 -67
  183. package/dist/core/extensions/service-ownership.js +1 -19
  184. package/dist/core/extensions/version-compat.js +1 -216
  185. package/dist/core/fs/fs-utils.js +2 -158
  186. package/dist/core/fs/host-environment-errors.js +1 -141
  187. package/dist/core/fs/index.js +1 -9
  188. package/dist/core/fs/path-utils.js +1 -17
  189. package/dist/core/governance/content-fields.js +1 -160
  190. package/dist/core/governance/issue-codes.js +1 -151
  191. package/dist/core/governance/metadata-coverage.js +1 -358
  192. package/dist/core/history/drift-cache.js +3 -72
  193. package/dist/core/history/drift-scan.js +1 -342
  194. package/dist/core/history/event-classification.js +1 -109
  195. package/dist/core/history/event-index.js +8 -784
  196. package/dist/core/history/history-compact-bulk.js +1 -104
  197. package/dist/core/history/history-diff.js +1 -158
  198. package/dist/core/history/history-rewrite.d.ts +6 -1
  199. package/dist/core/history/history-rewrite.js +1 -107
  200. package/dist/core/history/history-storage-stats.js +1 -102
  201. package/dist/core/history/history-stream-policy.js +1 -62
  202. package/dist/core/history/history.js +2 -617
  203. package/dist/core/history/identity.js +1 -30
  204. package/dist/core/history/index.js +1 -9
  205. package/dist/core/history/projection.js +1 -196
  206. package/dist/core/history/read.d.ts +9 -0
  207. package/dist/core/history/read.js +1 -57
  208. package/dist/core/history/replay.js +2 -439
  209. package/dist/core/history/version-address.js +1 -32
  210. package/dist/core/history/workspace-history.js +2 -433
  211. package/dist/core/io/body-file.js +1 -62
  212. package/dist/core/io/bulk-ids-input.js +1 -112
  213. package/dist/core/item/actionability.js +1 -327
  214. package/dist/core/item/dependency-reference.js +1 -20
  215. package/dist/core/item/id.js +1 -112
  216. package/dist/core/item/index.js +1 -12
  217. package/dist/core/item/item-format-version.js +1 -78
  218. package/dist/core/item/item-format.js +5 -1473
  219. package/dist/core/item/item-record.js +1 -23
  220. package/dist/core/item/item-type-definition.js +1 -133
  221. package/dist/core/item/parent-reference-policy.js +1 -57
  222. package/dist/core/item/parse.js +2 -603
  223. package/dist/core/item/plan-lifecycle.js +1 -19
  224. package/dist/core/item/priority.js +1 -61
  225. package/dist/core/item/sprint-release-format.js +1 -38
  226. package/dist/core/item/status-filter.js +1 -115
  227. package/dist/core/item/status.js +1 -43
  228. package/dist/core/item/toon-decode.js +1 -29
  229. package/dist/core/item/type-registry.js +1 -715
  230. package/dist/core/item/type-synonyms.js +1 -38
  231. package/dist/core/lock/index.js +1 -9
  232. package/dist/core/lock/lock-gc.js +1 -240
  233. package/dist/core/lock/lock.js +3 -590
  234. package/dist/core/output/mutation-projection.js +1 -217
  235. package/dist/core/output/output-control.js +1 -25
  236. package/dist/core/output/output.js +11 -494
  237. package/dist/core/output/query-summary.js +1 -58
  238. package/dist/core/output/tabular.js +1 -77
  239. package/dist/core/packages/manifest.js +1 -244
  240. package/dist/core/packages/root.js +1 -84
  241. package/dist/core/profile/profile-describe.js +1 -83
  242. package/dist/core/profile/profile-lint.js +1 -415
  243. package/dist/core/profile/profile-plan.js +0 -0
  244. package/dist/core/profile/profile-presets.js +1 -370
  245. package/dist/core/reproducibility/context.js +1 -82
  246. package/dist/core/schema/fields-file.js +2 -288
  247. package/dist/core/schema/item-types-file.js +2 -296
  248. package/dist/core/schema/runtime-field-filters.js +1 -49
  249. package/dist/core/schema/runtime-field-values.js +1 -313
  250. package/dist/core/schema/runtime-schema.js +2 -826
  251. package/dist/core/schema/status-defs-file.js +2 -227
  252. package/dist/core/schema/status-token.js +1 -31
  253. package/dist/core/schema/type-inference.js +1 -95
  254. package/dist/core/schema/type-presets.js +1 -87
  255. package/dist/core/schema/type-workflows.js +1 -104
  256. package/dist/core/search/background-refresh.js +2 -286
  257. package/dist/core/search/bm25.js +1 -146
  258. package/dist/core/search/cache.js +2 -534
  259. package/dist/core/search/corpus.js +1 -311
  260. package/dist/core/search/embedding-batches.js +1 -163
  261. package/dist/core/search/eval.js +1 -225
  262. package/dist/core/search/http-client.js +1 -75
  263. package/dist/core/search/providers.js +1 -242
  264. package/dist/core/search/relevance.js +1 -244
  265. package/dist/core/search/semantic-defaults.js +1 -199
  266. package/dist/core/search/staleness.js +1 -30
  267. package/dist/core/search/vector-stores.js +2 -664
  268. package/dist/core/search/vectorization-metadata.js +1 -81
  269. package/dist/core/sentry/helpers.js +1 -272
  270. package/dist/core/sentry/instrument.js +1 -387
  271. package/dist/core/session/session-state.js +1 -260
  272. package/dist/core/shared/agent-session-context.js +1 -133
  273. package/dist/core/shared/author.js +1 -1172
  274. package/dist/core/shared/command-types.js +1 -4
  275. package/dist/core/shared/conflict-markers.js +1 -31
  276. package/dist/core/shared/constants.js +1 -405
  277. package/dist/core/shared/errors.js +1 -20
  278. package/dist/core/shared/html-entity-decode.js +1 -131
  279. package/dist/core/shared/index.js +1 -12
  280. package/dist/core/shared/item-metadata-contract.js +1 -89
  281. package/dist/core/shared/lazy-module.js +1 -16
  282. package/dist/core/shared/levenshtein.js +1 -61
  283. package/dist/core/shared/memo.js +1 -19
  284. package/dist/core/shared/numeric-parsers.js +1 -20
  285. package/dist/core/shared/option-alias-visibility.js +1 -67
  286. package/dist/core/shared/primitives.js +1 -127
  287. package/dist/core/shared/serial-queue.js +1 -79
  288. package/dist/core/shared/serialization.js +1 -210
  289. package/dist/core/shared/split-comma-list.js +1 -30
  290. package/dist/core/shared/text-normalization.js +1 -38
  291. package/dist/core/shared/time.js +1 -306
  292. package/dist/core/store/index.js +1 -12
  293. package/dist/core/store/item-format-migration.js +1 -125
  294. package/dist/core/store/item-metadata-cache.js +1 -1116
  295. package/dist/core/store/item-metadata-query-index.js +9 -394
  296. package/dist/core/store/item-metadata-read-work.js +1 -43
  297. package/dist/core/store/item-store.js +1 -693
  298. package/dist/core/store/paths.d.ts +1 -1
  299. package/dist/core/store/paths.js +1 -214
  300. package/dist/core/store/settings-read-cache.js +1 -85
  301. package/dist/core/store/settings-validator.js +1 -421
  302. package/dist/core/store/settings.js +3 -1309
  303. package/dist/core/store/tracker-preflight.js +1 -141
  304. package/dist/core/telemetry/consent.js +5 -108
  305. package/dist/core/telemetry/observability.js +1 -246
  306. package/dist/core/telemetry/runtime.js +4 -1988
  307. package/dist/core/test/background-runs.js +4 -945
  308. package/dist/core/test/item-test-run-tracking.js +1 -63
  309. package/dist/core/test/run-selectors.js +1 -120
  310. package/dist/core/validate/estimate-defaults.js +1 -89
  311. package/dist/core/validate/fix-planning.js +1 -189
  312. package/dist/core/validate/linked-artifact-reference.js +1 -36
  313. package/dist/core/validate/missing-by-type.js +1 -34
  314. package/dist/core/validate/missing-link-owners.js +1 -95
  315. package/dist/core/validate/stale-file-classification.js +1 -82
  316. package/dist/mcp/http-server.js +5 -448
  317. package/dist/mcp/legacy-adapter.js +1 -77
  318. package/dist/mcp/runtime-capabilities.js +1 -200
  319. package/dist/mcp/server.js +4 -1233
  320. package/dist/mcp/tool-definitions.js +1 -804
  321. package/dist/sdk/actionability.js +1 -13
  322. package/dist/sdk/agent/closed-domain-contracts.js +1 -161
  323. package/dist/sdk/agent/command-recovery.js +1 -59
  324. package/dist/sdk/agent/command-suggestions.js +1 -66
  325. package/dist/sdk/agent/create-option-policy.js +1 -31
  326. package/dist/sdk/agent/identity-config.js +1 -106
  327. package/dist/sdk/agent/item-addressing.js +1 -207
  328. package/dist/sdk/agent/refusal-closure-census.js +1 -151
  329. package/dist/sdk/agent/refusal-closure.js +1 -133
  330. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
  331. package/dist/sdk/agent/refusal-reachability.js +1 -593
  332. package/dist/sdk/agent/subcommand-recovery.js +1 -83
  333. package/dist/sdk/agent/task-transcript-contracts.js +1 -197
  334. package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
  335. package/dist/sdk/agent-capability-contracts.js +1 -428
  336. package/dist/sdk/agent-session-context.js +1 -9
  337. package/dist/sdk/annotations.js +1 -448
  338. package/dist/sdk/author-attribution.js +1 -468
  339. package/dist/sdk/authoring.js +1 -20
  340. package/dist/sdk/cli-bootstrap.js +1 -838
  341. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
  342. package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
  343. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
  344. package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
  345. package/dist/sdk/cli-contracts/command-aliases.js +1 -107
  346. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
  347. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
  348. package/dist/sdk/cli-contracts/commander-types.js +1 -159
  349. package/dist/sdk/cli-contracts/completeness.js +1 -393
  350. package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
  351. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
  352. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
  353. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
  354. package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
  355. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
  356. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
  357. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
  358. package/dist/sdk/cli-contracts/string-lists.js +1 -16
  359. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
  360. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
  361. package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
  362. package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
  363. package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
  364. package/dist/sdk/cli-contracts.d.ts +1 -1
  365. package/dist/sdk/cli-contracts.js +1 -17
  366. package/dist/sdk/cli-program.js +1 -49
  367. package/dist/sdk/command-line.d.ts +2 -5
  368. package/dist/sdk/command-line.js +1 -78
  369. package/dist/sdk/comments.js +1 -133
  370. package/dist/sdk/compile-cache.js +1 -73
  371. package/dist/sdk/completion.js +157 -837
  372. package/dist/sdk/compose.js +1 -1090
  373. package/dist/sdk/config.js +1 -1204
  374. package/dist/sdk/context/recency.js +1 -33
  375. package/dist/sdk/context/semantic-session-attribution.js +1 -82
  376. package/dist/sdk/context/usage-egress.js +1 -29
  377. package/dist/sdk/context/usage-ledger.js +3 -185
  378. package/dist/sdk/context-intent-contracts.js +1 -709
  379. package/dist/sdk/context-intent-runtime.js +1 -115
  380. package/dist/sdk/context-packing.js +1 -218
  381. package/dist/sdk/context-relevance.js +1 -503
  382. package/dist/sdk/context-signal-store.js +2 -426
  383. package/dist/sdk/context-usage.js +1 -367
  384. package/dist/sdk/contracts.js +1 -23
  385. package/dist/sdk/core-governance.js +1 -14
  386. package/dist/sdk/core.js +1 -14
  387. package/dist/sdk/corpus-shape.js +1 -401
  388. package/dist/sdk/define.js +1 -220
  389. package/dist/sdk/dependencies.js +1 -718
  390. package/dist/sdk/dependency-flag-validation.js +1 -156
  391. package/dist/sdk/dependency-provenance.js +1 -135
  392. package/dist/sdk/docs.js +1 -14
  393. package/dist/sdk/duplicates.js +1 -40
  394. package/dist/sdk/environment/agent-environment.js +1 -466
  395. package/dist/sdk/environment/host-environment-errors.js +1 -8
  396. package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
  397. package/dist/sdk/environment/source-context.js +1 -28
  398. package/dist/sdk/environment/tracker-preflight.js +1 -9
  399. package/dist/sdk/error-code-catalog.js +1 -153
  400. package/dist/sdk/error-runtime.js +1 -58
  401. package/dist/sdk/errors.js +1 -58
  402. package/dist/sdk/eval.js +1 -190
  403. package/dist/sdk/extension/author-manifest.js +1 -92
  404. package/dist/sdk/extension/bundled-catalog.js +1 -332
  405. package/dist/sdk/extension/concurrency.js +1 -25
  406. package/dist/sdk/extension/copy-scope.d.ts +2 -0
  407. package/dist/sdk/extension/copy-scope.js +2 -0
  408. package/dist/sdk/extension/custom-field-collisions.js +1 -30
  409. package/dist/sdk/extension/describe.js +3 -189
  410. package/dist/sdk/extension/doctor.js +1 -606
  411. package/dist/sdk/extension/install-plan.d.ts +69 -0
  412. package/dist/sdk/extension/install-plan.js +2 -0
  413. package/dist/sdk/extension/install-receipts.d.ts +7 -0
  414. package/dist/sdk/extension/install-receipts.js +2 -0
  415. package/dist/sdk/extension/install-runtime.js +3 -313
  416. package/dist/sdk/extension/install-snapshot.js +1 -66
  417. package/dist/sdk/extension/install-sources.js +5 -1057
  418. package/dist/sdk/extension/managed-state.js +2 -252
  419. package/dist/sdk/extension/migrations.js +2 -174
  420. package/dist/sdk/extension/output-ownership.js +1 -25
  421. package/dist/sdk/extension/runtime-summary.js +1 -18
  422. package/dist/sdk/extension/scaffold.js +4 -2308
  423. package/dist/sdk/extension/shared.js +1 -147
  424. package/dist/sdk/extension/source-resolution.js +1 -65
  425. package/dist/sdk/extension/update-check.js +1 -67
  426. package/dist/sdk/extension-command-context.js +1 -44
  427. package/dist/sdk/extension-contracts.js +1 -73
  428. package/dist/sdk/extension.d.ts +7 -2
  429. package/dist/sdk/extension.js +1 -2196
  430. package/dist/sdk/files.js +1 -535
  431. package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
  432. package/dist/sdk/flag-invocation-contracts.js +1 -344
  433. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
  434. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
  435. package/dist/sdk/generated-error-code-catalog.js +1 -16
  436. package/dist/sdk/governance/assurance-action-contracts.js +1 -4
  437. package/dist/sdk/governance/assurance-action.js +1 -411
  438. package/dist/sdk/governance/assurance-limits.js +1 -10
  439. package/dist/sdk/governance/assurance-mutation-error.js +1 -81
  440. package/dist/sdk/governance/assurance-presets.js +1 -135
  441. package/dist/sdk/governance/assurance-runtime.js +1 -238
  442. package/dist/sdk/governance/assurance.js +4 -1182
  443. package/dist/sdk/governance/boundary-fixtures.js +1 -200
  444. package/dist/sdk/governance/coverage-assurance.js +1 -60
  445. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
  446. package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
  447. package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
  448. package/dist/sdk/governance/defect-recurrence.js +1 -623
  449. package/dist/sdk/governance/extension-host-version.js +1 -115
  450. package/dist/sdk/governance/gc.js +1 -368
  451. package/dist/sdk/governance/health.js +1 -2367
  452. package/dist/sdk/governance/hierarchy-validation.js +1 -108
  453. package/dist/sdk/governance/linked-file-report.js +1 -71
  454. package/dist/sdk/governance/merge-receipt-history.js +1 -206
  455. package/dist/sdk/governance/provenance-health.js +1 -282
  456. package/dist/sdk/governance/reindex.js +4 -761
  457. package/dist/sdk/governance/stale-work.js +1 -82
  458. package/dist/sdk/governance/status-role-diagnostics.js +1 -35
  459. package/dist/sdk/governance/storage-integrity.js +1 -280
  460. package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
  461. package/dist/sdk/governance/upgrade.js +2 -327
  462. package/dist/sdk/governance/validate-history-drift.js +1 -81
  463. package/dist/sdk/governance/validate-item-reader.js +1 -17
  464. package/dist/sdk/governance/validate-normalization.js +1 -36
  465. package/dist/sdk/governance/validate.js +1 -2261
  466. package/dist/sdk/governance/workspace-position.js +1 -163
  467. package/dist/sdk/governance.d.ts +1 -0
  468. package/dist/sdk/governance.js +1 -31
  469. package/dist/sdk/graph/adapter.js +1 -181
  470. package/dist/sdk/graph/analytics.js +1 -474
  471. package/dist/sdk/graph/assembly.js +1 -377
  472. package/dist/sdk/graph/cache.js +1 -160
  473. package/dist/sdk/graph/centrality.js +1 -258
  474. package/dist/sdk/graph/conformance.js +1 -130
  475. package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
  476. package/dist/sdk/graph/deadline-scheduling.js +2 -0
  477. package/dist/sdk/graph/durable-cache.d.ts +1 -1
  478. package/dist/sdk/graph/durable-cache.js +1 -361
  479. package/dist/sdk/graph/governance-contracts.js +1 -34
  480. package/dist/sdk/graph/governance.d.ts +13 -1
  481. package/dist/sdk/graph/governance.js +1 -735
  482. package/dist/sdk/graph/hierarchy-integrity.js +1 -310
  483. package/dist/sdk/graph/index.d.ts +3 -2
  484. package/dist/sdk/graph/index.js +1 -26
  485. package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
  486. package/dist/sdk/graph/lifecycle-coverage.js +2 -0
  487. package/dist/sdk/graph/mutation-advisory.js +1 -176
  488. package/dist/sdk/graph/remediation.js +1 -197
  489. package/dist/sdk/graph/run.d.ts +15 -1
  490. package/dist/sdk/graph/run.js +1 -768
  491. package/dist/sdk/graph/scheduling.js +1 -124
  492. package/dist/sdk/graph/traversal.js +1 -284
  493. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
  494. package/dist/sdk/graph.js +1 -15
  495. package/dist/sdk/guide-topics.js +1 -707
  496. package/dist/sdk/guide.js +1 -279
  497. package/dist/sdk/history/maintenance.d.ts +71 -0
  498. package/dist/sdk/history/maintenance.js +2 -0
  499. package/dist/sdk/history/salvage.js +2 -247
  500. package/dist/sdk/history/subject.d.ts +19 -0
  501. package/dist/sdk/history/subject.js +2 -0
  502. package/dist/sdk/history-analytics.js +1 -282
  503. package/dist/sdk/history-compact.js +1 -527
  504. package/dist/sdk/history-mcp.js +1 -68
  505. package/dist/sdk/history-provenance.js +1 -182
  506. package/dist/sdk/history-read.js +1 -96
  507. package/dist/sdk/history-redact.d.ts +1 -14
  508. package/dist/sdk/history-redact.js +1 -643
  509. package/dist/sdk/history-repair.d.ts +5 -0
  510. package/dist/sdk/history-repair.js +1 -657
  511. package/dist/sdk/improvement-ledger-validation.js +1 -62
  512. package/dist/sdk/improvement-ledger.js +2 -257
  513. package/dist/sdk/index.d.ts +4 -0
  514. package/dist/sdk/index.js +1 -183
  515. package/dist/sdk/init-agent-guidance.js +2 -496
  516. package/dist/sdk/init.js +2 -820
  517. package/dist/sdk/invocation-author.js +1 -39
  518. package/dist/sdk/item-children.js +1 -90
  519. package/dist/sdk/item-metadata-index.js +1 -15
  520. package/dist/sdk/item-schedule.js +1 -27
  521. package/dist/sdk/item-transaction.js +1 -396
  522. package/dist/sdk/learnings.js +1 -29
  523. package/dist/sdk/lifecycle/append.js +2 -53
  524. package/dist/sdk/lifecycle/claim.d.ts +2 -0
  525. package/dist/sdk/lifecycle/claim.js +1 -242
  526. package/dist/sdk/lifecycle/close-many.js +1 -438
  527. package/dist/sdk/lifecycle/close.js +1 -468
  528. package/dist/sdk/lifecycle/copy.js +1 -212
  529. package/dist/sdk/lifecycle/create.js +1 -1949
  530. package/dist/sdk/lifecycle/delete.js +1 -45
  531. package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
  532. package/dist/sdk/lifecycle/focus.js +1 -91
  533. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
  534. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
  535. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
  536. package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
  537. package/dist/sdk/lifecycle/mcp-actions.js +1 -51
  538. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
  539. package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
  540. package/dist/sdk/lifecycle/plan.js +1 -1606
  541. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
  542. package/dist/sdk/lifecycle/reopen.js +1 -68
  543. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
  544. package/dist/sdk/lifecycle/restore.d.ts +1 -0
  545. package/dist/sdk/lifecycle/restore.js +1 -330
  546. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
  547. package/dist/sdk/lifecycle/update-many.js +1 -861
  548. package/dist/sdk/lifecycle/update.js +1 -2136
  549. package/dist/sdk/lifecycle-completion.js +1 -92
  550. package/dist/sdk/lifecycle-policy.js +1 -120
  551. package/dist/sdk/linked-artifacts.js +1 -530
  552. package/dist/sdk/mcp/apps.js +4 -133
  553. package/dist/sdk/mcp/authorization.js +1 -404
  554. package/dist/sdk/mcp/discovery.js +1 -494
  555. package/dist/sdk/mcp/interactions.js +1 -336
  556. package/dist/sdk/mcp/protocol.d.ts +7 -0
  557. package/dist/sdk/mcp/protocol.js +1 -184
  558. package/dist/sdk/mcp/skills.js +1 -389
  559. package/dist/sdk/mcp/subscriptions.js +1 -211
  560. package/dist/sdk/mcp/tasks.js +2 -430
  561. package/dist/sdk/mcp/transport.js +1 -260
  562. package/dist/sdk/merge/abandoned-receipts.js +1 -46
  563. package/dist/sdk/merge/driver.js +1 -212
  564. package/dist/sdk/merge/index.js +1 -16
  565. package/dist/sdk/merge/install.js +3 -561
  566. package/dist/sdk/merge/receipt-file-boundary.js +1 -46
  567. package/dist/sdk/merge/receipt-operation.js +1 -96
  568. package/dist/sdk/merge/receipt-schema.js +1 -397
  569. package/dist/sdk/merge/receipts.js +4 -525
  570. package/dist/sdk/merge/reconcile.js +1 -352
  571. package/dist/sdk/merge/three-way.js +3 -775
  572. package/dist/sdk/merge.js +1 -10
  573. package/dist/sdk/mutation-events.js +1 -292
  574. package/dist/sdk/mutation-guard.js +1 -216
  575. package/dist/sdk/notes.js +1 -139
  576. package/dist/sdk/output-contracts.js +1 -172
  577. package/dist/sdk/output-projection.js +1 -430
  578. package/dist/sdk/output-token-accounting.js +1 -140
  579. package/dist/sdk/output.js +1 -64
  580. package/dist/sdk/ownership-source.js +1 -21
  581. package/dist/sdk/package-import-adapters.js +1 -442
  582. package/dist/sdk/package-migrations.js +1 -20
  583. package/dist/sdk/package-runtime-options.js +1 -80
  584. package/dist/sdk/pagination.js +1 -162
  585. package/dist/sdk/profile.js +1 -454
  586. package/dist/sdk/provenance.js +1 -258
  587. package/dist/sdk/public-surface.json +1 -1
  588. package/dist/sdk/query/activity.js +1 -401
  589. package/dist/sdk/query/aggregate.d.ts +16 -0
  590. package/dist/sdk/query/aggregate.js +1 -390
  591. package/dist/sdk/query/calendar.js +1 -964
  592. package/dist/sdk/query/complete-list.js +1 -215
  593. package/dist/sdk/query/context.js +1 -1702
  594. package/dist/sdk/query/duplicate-candidates.js +1 -70
  595. package/dist/sdk/query/get.js +1 -450
  596. package/dist/sdk/query/history.js +1 -186
  597. package/dist/sdk/query/item-filter-options.js +1 -9
  598. package/dist/sdk/query/light-metadata.js +1 -18
  599. package/dist/sdk/query/list-filter-shared.js +1 -81
  600. package/dist/sdk/query/list.js +1 -1304
  601. package/dist/sdk/query/multi-value-filters.js +1 -78
  602. package/dist/sdk/query/next.js +1 -513
  603. package/dist/sdk/query/parsers.js +1 -44
  604. package/dist/sdk/query/projection-contracts.js +1 -184
  605. package/dist/sdk/query/search-contracts.js +1 -230
  606. package/dist/sdk/query/search-pagination.js +1 -35
  607. package/dist/sdk/query/search-rendering.js +1 -105
  608. package/dist/sdk/query/search.js +2 -1987
  609. package/dist/sdk/query.js +1 -35
  610. package/dist/sdk/read-output/continuation.js +1 -194
  611. package/dist/sdk/read-output-budget.js +1 -135
  612. package/dist/sdk/read-output-contracts.js +1 -1225
  613. package/dist/sdk/read-output-rows.js +1 -186
  614. package/dist/sdk/read-output-session.js +1 -208
  615. package/dist/sdk/relationship-analytics.js +1 -410
  616. package/dist/sdk/relationship-context.js +1 -284
  617. package/dist/sdk/relationship-history.js +4 -519
  618. package/dist/sdk/relationship-kinds/contract.js +1 -22
  619. package/dist/sdk/relationship-migration.js +1 -77
  620. package/dist/sdk/relationships.js +1 -579
  621. package/dist/sdk/reproducibility/process.js +1 -87
  622. package/dist/sdk/runtime-action-aliases.js +1 -59
  623. package/dist/sdk/runtime-extended-actions.js +1 -177
  624. package/dist/sdk/runtime-input.js +1 -614
  625. package/dist/sdk/runtime-primitives.js +1 -84
  626. package/dist/sdk/runtime-public-contracts.js +1 -4
  627. package/dist/sdk/runtime-stats-options.js +1 -38
  628. package/dist/sdk/runtime.js +1 -1928
  629. package/dist/sdk/scheduling-shortcuts.js +1 -63
  630. package/dist/sdk/schema-migration.js +3 -856
  631. package/dist/sdk/schema.js +1 -1376
  632. package/dist/sdk/search-refresh-worker.js +1 -18
  633. package/dist/sdk/similarity-scoring.js +1 -53
  634. package/dist/sdk/similarity.js +1 -326
  635. package/dist/sdk/start-task-status.js +1 -14
  636. package/dist/sdk/stats.js +1 -270
  637. package/dist/sdk/structured-mutations.js +1 -580
  638. package/dist/sdk/telemetry-flush.js +1 -13
  639. package/dist/sdk/telemetry.js +1 -405
  640. package/dist/sdk/templates.js +2 -292
  641. package/dist/sdk/test/batch.js +2 -509
  642. package/dist/sdk/test/entry.js +1 -70
  643. package/dist/sdk/test/execution.js +6 -2211
  644. package/dist/sdk/test/linked-command-detection.js +1 -546
  645. package/dist/sdk/test/measurements.js +1 -91
  646. package/dist/sdk/test/parsers.js +1 -545
  647. package/dist/sdk/test/runs.js +1 -193
  648. package/dist/sdk/test/trust.js +2 -206
  649. package/dist/sdk/testing.js +4 -1391
  650. package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
  651. package/dist/sdk/traceability/source-traceability.js +1 -292
  652. package/dist/sdk/tracker-root-discovery.js +1 -9
  653. package/dist/sdk/workspace-contracts-cache.js +1 -28
  654. package/dist/sdk/workspace-contracts.js +1 -33
  655. package/dist/sdk/workspace-memory.js +2 -318
  656. package/dist/sdk/workspace-recipe.js +1 -71
  657. package/dist/sdk/workspace-snapshot.js +4 -613
  658. package/dist/sdk/workspace-transaction-gc.js +1 -149
  659. package/dist/sdk/workspace-transaction.js +2 -363
  660. package/dist/sdk/workspace.js +3 -127
  661. package/dist/types/index.js +1 -9
  662. package/dist/types.js +1 -245
  663. package/docs/AGENT_GUIDE.md +1 -1
  664. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
  665. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
  666. package/docs/EXTENSIONS.md +1 -0
  667. package/docs/HISTORY_MAINTENANCE.md +125 -0
  668. package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
  669. package/docs/PACKAGE_EVIDENCE.md +92 -0
  670. package/docs/PLANNING_MEASUREMENTS.md +183 -0
  671. package/docs/README.md +3 -0
  672. package/docs/RELEASING.md +1 -0
  673. package/docs/SCRIPTING.md +21 -0
  674. package/docs/TESTING.md +23 -0
  675. package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -5
  676. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
  677. package/marketplace.json +2 -2
  678. package/package.json +1 -1
  679. package/packages/pm-beads/package.json +1 -1
  680. package/packages/pm-calendar/package.json +1 -1
  681. package/packages/pm-command-kit/package.json +1 -1
  682. package/packages/pm-digital-twin/package.json +1 -1
  683. package/packages/pm-governance-audit/package.json +1 -1
  684. package/packages/pm-guide-shell/package.json +1 -1
  685. package/packages/pm-kanban/package.json +1 -1
  686. package/packages/pm-lifecycle-hooks/package.json +1 -1
  687. package/packages/pm-linked-test-adapters/package.json +1 -1
  688. package/packages/pm-search-advanced/package.json +1 -1
  689. package/packages/pm-templates/package.json +1 -1
  690. package/packages/pm-todos/package.json +1 -1
  691. package/packages/pm-vcs/package.json +1 -1
  692. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  693. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  694. package/scripts/finalize-build.mjs +45 -3
  695. package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
  696. package/dist/cli-bundle/chunks/chunk-BAX2BYUW.js +0 -2111
  697. package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
  698. package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
  699. package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
  700. package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
  701. package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
  702. package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
  703. package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
  704. package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
  705. package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
  706. package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
  707. package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
  708. package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
  709. package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
  710. package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
  711. package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
  712. package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
  713. package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
  714. package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
  715. package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
  716. package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
  717. package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
  718. package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
  719. package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +0 -2
@@ -1,1354 +1,2 @@
1
-
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ca79853d-468c-5522-b5f9-6509c66e3d9b")}catch(e){}}();
3
- import { resolveRecoveryCommandName } from "../sdk/agent/command-recovery.js";
4
- import { projectPmDiagnosticOutput, projectPmDiagnosticText, } from "../sdk/cli-contracts/agent-output-contracts.js";
5
- import { renderPmCommand } from "./argv-utils.js";
6
- import { discoverNearbyPmRoot } from "../sdk/tracker-root-discovery.js";
7
- import { stripGlobalBootstrapTokens } from "../sdk/cli-bootstrap.js";
8
- /** Compact an error envelope to fields that change the caller's next action. */
9
- export function projectLeanErrorEnvelope(envelope) {
10
- const { why: _why, title: _title, ...actionable } = envelope;
11
- return actionable;
12
- }
13
- // JSON/classification payloads are consumed heavily by agents; suppress common
14
- // boilerplate rationale text there to reduce token overhead. Human display
15
- // guidance still renders "Why" unchanged.
16
- const STRUCTURED_WHY_SUPPRESSION_CODES = new Set([
17
- "unknown_command",
18
- "unknown_option",
19
- "missing_required_option",
20
- "missing_required_argument",
21
- "invalid_argument_value",
22
- "invalid_command_usage",
23
- "command_failed",
24
- ]);
25
- function includeWhyInStructuredGuidance(message) {
26
- if (!message.why) {
27
- return false;
28
- }
29
- if (message.recovery?.recovery_mode === "compact") {
30
- return false;
31
- }
32
- return !STRUCTURED_WHY_SUPPRESSION_CODES.has(message.code);
33
- }
34
- function errorType(code) {
35
- return `urn:pm-cli:error:${code}`;
36
- }
37
- function makeGuidanceMessage(params) {
38
- return {
39
- ...params,
40
- type: errorType(params.code),
41
- };
42
- }
43
- // Catalog of command tokens that are provided by optional first-party packages
44
- // rather than core. When an unknown-command error names one of these, we surface
45
- // a concrete install hint so agents/humans aren't left guessing. The install
46
- // command uses the bundled alias accepted by `pm install <alias>` (see
47
- // packages/pm-*/package.json `pm.aliases` and extension.ts install_command).
48
- const GUIDE_SHELL_HINT = {
49
- packageName: "@unbrained/pm-guide-shell",
50
- installCommand: "pm install guide-shell",
51
- };
52
- const CALENDAR_HINT = {
53
- packageName: "@unbrained/pm-calendar",
54
- installCommand: "pm install calendar",
55
- };
56
- const SEARCH_ADVANCED_HINT = {
57
- packageName: "@unbrained/pm-search-advanced",
58
- installCommand: "pm install search-advanced",
59
- };
60
- const GOVERNANCE_AUDIT_HINT = {
61
- packageName: "@unbrained/pm-governance-audit",
62
- installCommand: "pm install audit",
63
- };
64
- const KNOWN_PACKAGE_COMMAND_HINTS = {
65
- guide: GUIDE_SHELL_HINT,
66
- shell: GUIDE_SHELL_HINT,
67
- completion: GUIDE_SHELL_HINT,
68
- "completion-statuses": GUIDE_SHELL_HINT,
69
- "completion-tags": GUIDE_SHELL_HINT,
70
- "completion-types": GUIDE_SHELL_HINT,
71
- templates: {
72
- packageName: "@unbrained/pm-templates",
73
- installCommand: "pm install templates",
74
- },
75
- calendar: CALENDAR_HINT,
76
- cal: CALENDAR_HINT,
77
- reindex: SEARCH_ADVANCED_HINT,
78
- "search-advanced": SEARCH_ADVANCED_HINT,
79
- "test-runs": {
80
- packageName: "@unbrained/pm-linked-test-adapters",
81
- installCommand: "pm install linked-test-adapters",
82
- },
83
- "comments-audit": GOVERNANCE_AUDIT_HINT,
84
- "dedupe-audit": GOVERNANCE_AUDIT_HINT,
85
- "dedupe-merge": GOVERNANCE_AUDIT_HINT,
86
- normalize: GOVERNANCE_AUDIT_HINT,
87
- };
88
- function resolveKnownPackageCommandHint(commandToken) {
89
- const primary = commandToken.trim().split(/\s+/)[0]?.toLowerCase();
90
- if (!primary) {
91
- return undefined;
92
- }
93
- return KNOWN_PACKAGE_COMMAND_HINTS[primary];
94
- }
95
- function renderList(title, entries) {
96
- if (entries.length === 0) {
97
- return [];
98
- }
99
- return [title, ...entries.map((entry) => ` - ${entry}`)];
100
- }
101
- function normalizeStringArray(values) {
102
- if (!Array.isArray(values)) {
103
- return undefined;
104
- }
105
- const normalized = values
106
- .filter((entry) => typeof entry === "string")
107
- .map((entry) => entry.trim())
108
- .filter((entry) => entry.length > 0);
109
- return normalized.length > 0 ? normalized : undefined;
110
- }
111
- function normalizeRecoveryCandidates(candidates) {
112
- if (!Array.isArray(candidates)) {
113
- return undefined;
114
- }
115
- const normalized = candidates
116
- .map((entry) => ({
117
- source: typeof entry?.source === "string" ? entry.source.trim() : "",
118
- command: typeof entry?.command === "string" ? entry.command.trim() : "",
119
- reason: typeof entry?.reason === "string" ? entry.reason.trim() : "",
120
- }))
121
- .filter((entry) => entry.source.length > 0 &&
122
- entry.command.length > 0 &&
123
- entry.reason.length > 0);
124
- return normalized.length > 0 ? normalized : undefined;
125
- }
126
- function assignRecoveryString(normalized, key, value) {
127
- if (typeof value === "string" && value.trim().length > 0) {
128
- normalized[key] = value.trim();
129
- }
130
- }
131
- function assignRecoveryCollection(normalized, key, value) {
132
- if (key === "parsed_positionals") {
133
- if (!Array.isArray(value))
134
- return;
135
- const parsedPositionals = value
136
- .map((entry) => ({
137
- role: typeof entry?.role === "string" ? entry.role.trim() : "",
138
- value: typeof entry?.value === "string" ? entry.value.trim() : "",
139
- }))
140
- .filter((entry) => entry.role.length > 0 && entry.value.length > 0);
141
- if (parsedPositionals.length > 0) {
142
- normalized.parsed_positionals = parsedPositionals;
143
- }
144
- return;
145
- }
146
- const values = normalizeStringArray(value);
147
- if (values) {
148
- normalized[key] = values;
149
- }
150
- }
151
- function normalizeRecoveryPayload(payload) {
152
- if (!payload || typeof payload !== "object") {
153
- return undefined;
154
- }
155
- const normalized = {};
156
- if (payload.recovery_mode === "compact") {
157
- normalized.recovery_mode = "compact";
158
- }
159
- assignRecoveryString(normalized, "attempted_command", payload.attempted_command);
160
- assignRecoveryCollection(normalized, "normalized_args", payload.normalized_args);
161
- assignRecoveryCollection(normalized, "parsed_positionals", payload.parsed_positionals);
162
- assignRecoveryCollection(normalized, "provided_fields", payload.provided_fields);
163
- assignRecoveryCollection(normalized, "missing", payload.missing);
164
- assignRecoveryCollection(normalized, "missing_required_fields", payload.missing_required_fields);
165
- assignRecoveryCollection(normalized, "suggested_flags", payload.suggested_flags);
166
- assignRecoveryCollection(normalized, "allowed_values", payload.allowed_values);
167
- assignRecoveryCollection(normalized, "candidate_commands", payload.candidate_commands);
168
- if (typeof payload.candidate_commands_total === "number" &&
169
- Number.isSafeInteger(payload.candidate_commands_total) &&
170
- payload.candidate_commands_total >= 0) {
171
- normalized.candidate_commands_total = payload.candidate_commands_total;
172
- }
173
- if (payload.candidate_commands_truncated === true) {
174
- normalized.candidate_commands_truncated = true;
175
- }
176
- if (payload.option_scope === "declared_on_path" ||
177
- payload.option_scope === "declared_elsewhere" ||
178
- payload.option_scope === "declared_nowhere") {
179
- normalized.option_scope = payload.option_scope;
180
- }
181
- assignRecoveryString(normalized, "suggested_retry", payload.suggested_retry);
182
- assignRecoveryCollection(normalized, "suggested_retry_args", payload.suggested_retry_args);
183
- if (typeof payload.retry_after_ms === "number" &&
184
- Number.isSafeInteger(payload.retry_after_ms) &&
185
- payload.retry_after_ms >= 0) {
186
- normalized.retry_after_ms = payload.retry_after_ms;
187
- }
188
- const fallbackCandidates = normalizeRecoveryCandidates(payload.fallback_candidates);
189
- if (fallbackCandidates) {
190
- normalized.fallback_candidates = fallbackCandidates;
191
- }
192
- assignRecoveryString(normalized, "next_best_command", payload.next_best_command);
193
- return Object.keys(normalized).length > 0 ? normalized : undefined;
194
- }
195
- function appendRecoveryTextLine(lines, label, value) {
196
- if (value) {
197
- lines.push(` ${label}: ${value}`);
198
- }
199
- }
200
- function appendRecoveryListLine(lines, label, values, separator) {
201
- if (values && values.length > 0) {
202
- lines.push(` ${label}: ${values.join(separator)}`);
203
- }
204
- }
205
- function renderRecoveryBundle(recovery) {
206
- const normalized = normalizeRecoveryPayload(recovery);
207
- if (!normalized) {
208
- return [];
209
- }
210
- const lines = ["Recovery bundle:"];
211
- appendRecoveryTextLine(lines, "suggested_retry", normalized.suggested_retry);
212
- appendRecoveryTextLine(lines, "attempted_command", normalized.attempted_command);
213
- appendRecoveryListLine(lines, "normalized_args", normalized.normalized_args, " ");
214
- if (normalized.parsed_positionals &&
215
- normalized.parsed_positionals.length > 0) {
216
- lines.push(" parsed_positionals:");
217
- for (const positional of normalized.parsed_positionals) {
218
- lines.push(` - ${positional.role}: ${positional.value}`);
219
- }
220
- }
221
- appendRecoveryListLine(lines, "provided_fields", normalized.provided_fields, ", ");
222
- appendRecoveryListLine(lines, "missing", normalized.missing, ", ");
223
- appendRecoveryListLine(lines, "missing_required_fields", normalized.missing_required_fields, ", ");
224
- appendRecoveryListLine(lines, "suggested_flags", normalized.suggested_flags, ", ");
225
- appendRecoveryListLine(lines, "allowed_values", normalized.allowed_values, ", ");
226
- appendRecoveryListLine(lines, "candidate_commands", normalized.candidate_commands, ", ");
227
- if (typeof normalized.candidate_commands_total === "number") {
228
- lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`);
229
- }
230
- if (normalized.candidate_commands_truncated === true) {
231
- lines.push(" candidate_commands_truncated: true");
232
- }
233
- if (normalized.option_scope !== undefined) {
234
- lines.push(` option_scope: ${normalized.option_scope}`);
235
- }
236
- if (typeof normalized.retry_after_ms === "number") {
237
- lines.push(` retry_after_ms: ${normalized.retry_after_ms}`);
238
- }
239
- appendRecoveryTextLine(lines, "next_best_command", normalized.next_best_command);
240
- if (normalized.fallback_candidates &&
241
- normalized.fallback_candidates.length > 0) {
242
- lines.push(" fallback_candidates:");
243
- for (const candidate of normalized.fallback_candidates) {
244
- lines.push(` - ${candidate.source}: ${candidate.command} (${candidate.reason})`);
245
- }
246
- }
247
- return lines;
248
- }
249
- /** Implements render guidance message for the public runtime surface of this module. */
250
- export function renderGuidanceMessage(message) {
251
- const lines = [
252
- `Error: ${message.title}`,
253
- "",
254
- "What is required:",
255
- ` ${message.required}`,
256
- ];
257
- if (message.nextSteps && message.nextSteps.length > 0) {
258
- lines.push("");
259
- lines.push(...renderList("Next steps:", message.nextSteps));
260
- }
261
- lines.push("", "What happened:", ` ${message.happened}`);
262
- if (message.why) {
263
- lines.push("", "Why:");
264
- lines.push(` ${message.why}`);
265
- }
266
- if (message.examples && message.examples.length > 0) {
267
- lines.push("");
268
- lines.push(...renderList("Examples:", message.examples));
269
- }
270
- if (message.verificationErrors && message.verificationErrors.length > 0) {
271
- lines.push("");
272
- lines.push(...renderList("Verification errors:", message.verificationErrors));
273
- }
274
- const recoveryLines = renderRecoveryBundle(message.recovery);
275
- if (recoveryLines.length > 0) {
276
- lines.push("");
277
- lines.push(...recoveryLines);
278
- }
279
- return lines.join("\n");
280
- }
281
- /** Attach optional actionable fields shared by JSON and classification envelopes. */
282
- function attachStructuredGuidanceDetails(payload, message) {
283
- if (includeWhyInStructuredGuidance(message)) {
284
- payload.why = message.why;
285
- }
286
- if (message.examples && message.examples.length > 0) {
287
- payload.examples = message.examples;
288
- }
289
- if (message.nextSteps && message.nextSteps.length > 0) {
290
- payload.next_steps = message.nextSteps;
291
- }
292
- if (message.verificationErrors && message.verificationErrors.length > 0) {
293
- payload.verification_errors = message.verificationErrors;
294
- }
295
- if (message.flag !== undefined)
296
- payload.flag = message.flag;
297
- if (message.value !== undefined)
298
- payload.value = message.value;
299
- if (message.unmatchedSelectors !== undefined)
300
- payload.unmatched_selectors = message.unmatchedSelectors;
301
- if (message.availableDependencies !== undefined)
302
- payload.available_dependencies = message.availableDependencies;
303
- if (message.recovery) {
304
- payload.recovery = message.recovery;
305
- }
306
- return payload;
307
- }
308
- function resolveRefusalCandidateFlag(message, normalizedArgs) {
309
- if (message.flag)
310
- return message.flag;
311
- const isAdmissibleCandidate = (flag) => {
312
- const canonicalFlag = flag.split("=", 1)[0];
313
- return (stripGlobalBootstrapTokens([canonicalFlag]).length > 0 &&
314
- !["--help", "--no-changed-fields", "--version"].includes(canonicalFlag) &&
315
- normalizedArgs.some((argument) => argument === canonicalFlag ||
316
- argument.startsWith(`${canonicalFlag}=`)));
317
- };
318
- const mentionedFlag = [
319
- ...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu),
320
- ]
321
- .map((match) => match[0])
322
- .find((flag) => isAdmissibleCandidate(flag));
323
- if (mentionedFlag)
324
- return mentionedFlag;
325
- return message.recovery?.provided_fields
326
- ?.map((field) => field.split("=", 1)[0])
327
- .find((field) => isAdmissibleCandidate(field));
328
- }
329
- function resolveRefusalRejectedValue(message, normalizedArgs, candidateFlag) {
330
- if (message.value !== undefined)
331
- return message.value;
332
- if (candidateFlag) {
333
- const candidateArgument = normalizedArgs.find((argument) => argument === candidateFlag || argument.startsWith(`${candidateFlag}=`));
334
- if (candidateArgument?.startsWith(`${candidateFlag}=`)) {
335
- return candidateArgument.slice(candidateFlag.length + 1);
336
- }
337
- const candidateIndex = normalizedArgs.indexOf(candidateFlag);
338
- return candidateIndex >= 0
339
- ? normalizedArgs[candidateIndex + 1]
340
- : undefined;
341
- }
342
- const allowedValues = message.recovery?.allowed_values;
343
- if (!allowedValues?.length)
344
- return undefined;
345
- return normalizedArgs.find((argument, index) => index > 0 &&
346
- !argument.startsWith("-") &&
347
- !allowedValues.includes(argument));
348
- }
349
- function buildRefusalEnvelope(message, exitCode) {
350
- const normalizedArgs = message.recovery?.normalized_args ?? [];
351
- const candidateFlag = resolveRefusalCandidateFlag(message, normalizedArgs);
352
- const rejectedValue = resolveRefusalRejectedValue(message, normalizedArgs, candidateFlag);
353
- return {
354
- surface: candidateFlag ??
355
- message.recovery?.missing?.[0] ??
356
- inferCommandNameFromRecovery(message.recovery) ??
357
- "command",
358
- ...(rejectedValue !== undefined ? { rejected_value: rejectedValue } : {}),
359
- ...(message.recovery?.allowed_values?.length
360
- ? { legal_domain: message.recovery.allowed_values }
361
- : {}),
362
- exit_code: exitCode,
363
- };
364
- }
365
- function guidanceToJsonEnvelope(message, exitCode) {
366
- return attachStructuredGuidanceDetails({
367
- type: message.type,
368
- code: message.code,
369
- title: message.title,
370
- detail: message.happened,
371
- required: message.required,
372
- exit_code: exitCode,
373
- refusal: buildRefusalEnvelope(message, exitCode),
374
- }, message);
375
- }
376
- function projectJsonErrorGuidance(guidance, exitCode) {
377
- const recovery = guidance.recovery;
378
- const hasActionableRecovery = Boolean(recovery?.suggested_retry) ||
379
- Boolean(recovery?.suggested_retry_args?.length) ||
380
- Boolean(recovery?.allowed_values?.length) ||
381
- Boolean(recovery?.candidate_commands?.length) ||
382
- Boolean(guidance.nextSteps?.length);
383
- return projectPmDiagnosticOutput(guidanceToJsonEnvelope(guidance, exitCode), {
384
- diagnosticClass: hasActionableRecovery ? "recovery_bundle" : "error",
385
- });
386
- }
387
- function guidanceToClassification(message) {
388
- return attachStructuredGuidanceDetails({
389
- type: message.type,
390
- code: message.code,
391
- title: message.title,
392
- detail: message.happened,
393
- required: message.required,
394
- }, message);
395
- }
396
- function normalizeMessage(message) {
397
- return message.replace(/\(outputHelp\)/g, "").trim();
398
- }
399
- function isModuleResolutionErrorMessage(message) {
400
- const normalized = message.toLowerCase();
401
- return (normalized.includes("cannot find module") ||
402
- normalized.includes("cannot find package") ||
403
- normalized.includes("err_module_not_found") ||
404
- normalized.includes("module_not_found"));
405
- }
406
- function normalizeContextList(values) {
407
- if (!Array.isArray(values)) {
408
- return undefined;
409
- }
410
- const normalized = values
411
- .map((value) => value.trim())
412
- .filter((value) => value.length > 0);
413
- return normalized.length > 0 ? normalized : undefined;
414
- }
415
- function dedupeStrings(values) {
416
- const seen = new Set();
417
- const result = [];
418
- for (const value of values) {
419
- if (seen.has(value)) {
420
- continue;
421
- }
422
- seen.add(value);
423
- result.push(value);
424
- }
425
- return result;
426
- }
427
- function inferCommandNameFromRecovery(recovery) {
428
- return resolveRecoveryCommandName(recovery?.normalized_args);
429
- }
430
- function inferAllowedValuesFromMessage(message) {
431
- const match = message.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);
432
- if (!match) {
433
- return [];
434
- }
435
- return match[1]
436
- .split(/[|,]/)
437
- .map((entry) => entry.trim())
438
- .filter((entry) => /^[A-Za-z0-9_.-]+$/.test(entry));
439
- }
440
- function buildAllowedValueRetryCommand(recovery, allowedValues) {
441
- const args = recovery?.normalized_args;
442
- const fields = recovery?.provided_fields;
443
- const replacement = allowedValues[0];
444
- if (!Array.isArray(args) || !Array.isArray(fields) || !replacement) {
445
- return undefined;
446
- }
447
- for (const field of fields) {
448
- const index = args.findIndex((arg) => arg === field);
449
- if (index >= 0 &&
450
- index < args.length - 1 &&
451
- !args[index + 1]?.startsWith("-")) {
452
- const nextArgs = [...args];
453
- nextArgs[index + 1] = replacement;
454
- return renderPmCommand(nextArgs);
455
- }
456
- }
457
- return undefined;
458
- }
459
- function buildFallbackTitleFromMessage(message) {
460
- const firstLine = message.split(/\r?\n/)[0].trim();
461
- if (firstLine.length === 0) {
462
- return undefined;
463
- }
464
- if (firstLine.length <= 120) {
465
- return firstLine;
466
- }
467
- return `${firstLine.slice(0, 117)}...`;
468
- }
469
- function normalizeContextValue(value, fallback) {
470
- return typeof value === "string" && value.trim().length > 0
471
- ? value.trim()
472
- : fallback;
473
- }
474
- function applyPmCliErrorContext(guidance, rawMessage, context) {
475
- if (!context) {
476
- return guidance;
477
- }
478
- const normalizedRawMessage = normalizeMessage(rawMessage);
479
- const code = normalizeContextValue(context.code, guidance.code);
480
- const type = normalizeContextValue(context.type, errorType(code));
481
- const examples = normalizeContextList(context.examples) ?? guidance.examples;
482
- const nextSteps = normalizeContextList(context.nextSteps) ?? guidance.nextSteps;
483
- const verificationErrors = normalizeContextList(context.verification_errors) ??
484
- guidance.verificationErrors;
485
- const fallbackTitle = guidance.code === "command_failed" && context.code
486
- ? buildFallbackTitleFromMessage(normalizedRawMessage)
487
- : undefined;
488
- const contextRecovery = normalizeRecoveryPayload(context.recovery);
489
- const recovery = contextRecovery && guidance.recovery
490
- ? normalizeRecoveryPayload({ ...guidance.recovery, ...contextRecovery })
491
- : (contextRecovery ?? guidance.recovery);
492
- return {
493
- ...guidance,
494
- code,
495
- type,
496
- title: fallbackTitle ?? guidance.title,
497
- happened: normalizedRawMessage.length > 0
498
- ? normalizedRawMessage
499
- : guidance.happened,
500
- required: normalizeContextValue(context.required, guidance.required),
501
- why: normalizeContextValue(context.why, guidance.why),
502
- examples,
503
- nextSteps,
504
- verificationErrors,
505
- flag: context.flag,
506
- value: context.value,
507
- unmatchedSelectors: context.unmatched_selectors,
508
- availableDependencies: context.available_dependencies,
509
- recovery,
510
- };
511
- }
512
- function buildTrackerNotInitializedGuidance(rawMessage, message, context) {
513
- const trackerNotInitialized = message.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);
514
- if (!trackerNotInitialized) {
515
- return null;
516
- }
517
- const attemptedRoot = trackerNotInitialized[1];
518
- const nearbyRoot = discoverNearbyPmRoot(process.cwd(), attemptedRoot);
519
- if (nearbyRoot) {
520
- return applyPmCliErrorContext(makeGuidanceMessage({
521
- code: "tracker_not_initialized",
522
- title: "Tracker exists at a custom path",
523
- happened: `pm did not find initialized metadata at ${attemptedRoot}, but found a tracker at ${nearbyRoot}.`,
524
- required: "Select the existing tracker root explicitly.",
525
- why: "Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",
526
- examples: [
527
- `pm --pm-path ${nearbyRoot} <command>`,
528
- `PM_PATH=${nearbyRoot} pm <command>`,
529
- ],
530
- nextSteps: [
531
- `Re-run with "--pm-path ${nearbyRoot}" or export PM_PATH=${nearbyRoot}.`,
532
- ],
533
- }), rawMessage, context);
534
- }
535
- return applyPmCliErrorContext(makeGuidanceMessage({
536
- code: "tracker_not_initialized",
537
- title: "Tracker is not initialized",
538
- happened: `pm data path does not contain initialized tracker metadata (${trackerNotInitialized[1]}).`,
539
- required: "Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",
540
- why: "Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",
541
- examples: ["pm init", "pm init acme"],
542
- nextSteps: ['Run "pm init", then rerun your original command.'],
543
- }), rawMessage, context);
544
- }
545
- function buildItemNotFoundGuidance(rawMessage, message, context) {
546
- const itemNotFound = message.match(/^Item ([^ ]+) not found$/);
547
- if (!itemNotFound) {
548
- return null;
549
- }
550
- const badId = itemNotFound[1];
551
- const isPlaceholder = /^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId);
552
- const happened = isPlaceholder
553
- ? `The item ID "${badId}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`
554
- : `No item with id "${badId}" exists in the active tracker scope.`;
555
- const nextSteps = isPlaceholder
556
- ? [
557
- "Check that the variable holding the item ID is defined before passing it to pm.",
558
- 'Use "pm list --status open --limit 20" to find valid IDs.',
559
- ]
560
- : ["Confirm the active --path/PM_PATH scope, then retry with a valid id."];
561
- return applyPmCliErrorContext(makeGuidanceMessage({
562
- code: "item_not_found",
563
- title: "Item ID not found",
564
- happened,
565
- required: "Use an existing item ID from current tracker data.",
566
- why: "Mutation and read commands operate only on known IDs.",
567
- examples: [
568
- "pm list --status open --limit 20",
569
- 'pm search "<keyword>" --limit 10',
570
- ],
571
- nextSteps,
572
- }), rawMessage, context);
573
- }
574
- function buildOwnershipConflictGuidance(rawMessage, message, context) {
575
- if (!message.includes("is assigned to") ||
576
- !message.includes("Use --force to override")) {
577
- return null;
578
- }
579
- return applyPmCliErrorContext(makeGuidanceMessage({
580
- code: "ownership_conflict",
581
- title: "Ownership conflict",
582
- happened: message,
583
- required: "Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",
584
- why: "Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",
585
- examples: [
586
- "pm claim pm-a1b2",
587
- "pm update pm-a1b2 --status in_progress --force",
588
- ],
589
- nextSteps: [
590
- "Use --force for approved systematic metadata updates performed by leads or maintainers.",
591
- "Use --force when correcting known stale metadata after coordinating ownership changes.",
592
- 'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.',
593
- ],
594
- }), rawMessage, context);
595
- }
596
- function buildLockConflictGuidance(rawMessage, message, context) {
597
- if (!message.includes("is locked")) {
598
- return null;
599
- }
600
- return applyPmCliErrorContext(makeGuidanceMessage({
601
- code: "lock_conflict",
602
- title: "Lock conflict",
603
- happened: message,
604
- required: "Wait for lock release, or use --force where supported if lock is stale and safe to override.",
605
- why: "Locking protects item files from concurrent write races.",
606
- examples: ["pm update pm-a1b2 --status in_progress --force"],
607
- }), rawMessage, context);
608
- }
609
- function buildPmMissingRequiredOptionGuidance(rawMessage, message, context) {
610
- const missingRequiredOption = message.match(/^Missing required option /);
611
- const missingRequiredOptions = message.match(/^Missing required options /);
612
- if (!missingRequiredOption && !missingRequiredOptions) {
613
- return null;
614
- }
615
- const plural = Boolean(missingRequiredOptions);
616
- const missingOptionFlag = !plural
617
- ? message.replace(/^Missing required option\s+/, "").trim()
618
- : null;
619
- const missingOptionLabel = missingOptionFlag ?? "";
620
- const missingOptionRequired = missingOptionFlag
621
- ? `Pass ${missingOptionFlag} with a valid value before running the command.`
622
- : "Provide the required option for this command invocation.";
623
- return applyPmCliErrorContext(makeGuidanceMessage({
624
- code: "missing_required_option",
625
- title: plural
626
- ? "Missing required options"
627
- : `Missing required option ${missingOptionLabel}`,
628
- happened: message,
629
- required: plural
630
- ? "Provide every required option for this command invocation."
631
- : missingOptionRequired,
632
- why: "Required options define command intent and enforce deterministic write contracts.",
633
- examples: [
634
- 'pm create --title "Task title" --description "Task details" --type Task --create-mode progressive',
635
- '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"',
636
- ],
637
- nextSteps: [
638
- 'Run "pm <command> --help" to view required and recommended flags.',
639
- "For staged triage without placeholder linkage values, use --create-mode progressive.",
640
- ],
641
- }), rawMessage, context);
642
- }
643
- function buildNoUpdateFieldsGuidance(rawMessage, message, context) {
644
- if (!message.startsWith("No update flags provided")) {
645
- return null;
646
- }
647
- return applyPmCliErrorContext(makeGuidanceMessage({
648
- code: "no_update_fields",
649
- title: "No update fields supplied",
650
- happened: "The update command was called without any field-changing flags.",
651
- 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.",
652
- why: "pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",
653
- examples: [
654
- 'pm update pm-a1b2 --status in_progress --message "Start implementation"',
655
- 'pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"',
656
- 'pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"',
657
- ],
658
- nextSteps: [
659
- "Choose the item field you intend to change, then pair that change with --message for history context.",
660
- "Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context.",
661
- ],
662
- }), rawMessage, context);
663
- }
664
- function buildInvalidArgumentGuidance(rawMessage, message, context) {
665
- if (!message.startsWith("Invalid ") &&
666
- !message.includes(" must be ") &&
667
- !message.includes(" requires ")) {
668
- return null;
669
- }
670
- const recovery = normalizeRecoveryPayload(context?.recovery);
671
- const commandName = inferCommandNameFromRecovery(recovery);
672
- const helpExample = commandName
673
- ? `pm ${commandName} --help`
674
- : "pm <command> --help";
675
- const allowedValues = inferAllowedValuesFromMessage(message);
676
- const enrichedRecovery = normalizeRecoveryPayload({
677
- ...recovery,
678
- allowed_values: recovery?.allowed_values ?? allowedValues,
679
- });
680
- const retryExample = buildAllowedValueRetryCommand(recovery, allowedValues);
681
- const examples = retryExample
682
- ? [retryExample, helpExample]
683
- : [helpExample, "pm contracts --command <command> --flags-only --json"];
684
- const nextSteps = allowedValues.length > 0
685
- ? [
686
- `Allowed values: ${allowedValues.join("|")}`,
687
- `Run "${helpExample}" to confirm command-specific constraints.`,
688
- ]
689
- : [
690
- "Check allowed values in command help, then rerun with corrected input.",
691
- ];
692
- return applyPmCliErrorContext(makeGuidanceMessage({
693
- code: "invalid_argument_value",
694
- title: "Invalid argument value",
695
- happened: message,
696
- required: "Use values that match documented command constraints.",
697
- why: "Validation protects data consistency and deterministic behavior across commands.",
698
- examples,
699
- nextSteps,
700
- recovery: enrichedRecovery,
701
- }), rawMessage, context);
702
- }
703
- function buildPmCliErrorGuidance(rawMessage, context) {
704
- const message = normalizeMessage(rawMessage);
705
- const guidance = buildTrackerNotInitializedGuidance(rawMessage, message, context) ??
706
- buildItemNotFoundGuidance(rawMessage, message, context) ??
707
- buildOwnershipConflictGuidance(rawMessage, message, context) ??
708
- buildLockConflictGuidance(rawMessage, message, context) ??
709
- buildPmMissingRequiredOptionGuidance(rawMessage, message, context) ??
710
- buildNoUpdateFieldsGuidance(rawMessage, message, context) ??
711
- buildInvalidArgumentGuidance(rawMessage, message, context);
712
- if (guidance) {
713
- return guidance;
714
- }
715
- return applyPmCliErrorContext(makeGuidanceMessage({
716
- code: "command_failed",
717
- title: "Command failed",
718
- happened: message,
719
- required: "Adjust command input or tracker state and retry.",
720
- why: "pm enforces explicit, deterministic contracts for data and command semantics.",
721
- examples: ["pm --help", "pm <command> --help"],
722
- }), rawMessage, context);
723
- }
724
- function commandExampleForRequiredOption(commandName, optionFlag, allowedTypes) {
725
- if (commandName === "create" && optionFlag.startsWith("--type")) {
726
- const firstAllowed = allowedTypes.split("|")[0] || "Task";
727
- return [
728
- `pm create --title "Example title" --description "Example description" --type ${firstAllowed} --status open --priority 1 --message "Create item" --create-mode progressive`,
729
- ];
730
- }
731
- if (commandName === "update") {
732
- return [
733
- 'pm update pm-a1b2 --status in_progress --message "Start implementation"',
734
- ];
735
- }
736
- return [`pm ${commandName ?? "<command>"} --help`];
737
- }
738
- function normalizeRequiredOptionLabel(rawValue) {
739
- const normalized = rawValue.trim();
740
- const firstLongFlag = normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0];
741
- return firstLongFlag ?? normalized;
742
- }
743
- function renderPmCommandFromArgs(argv) {
744
- if (!Array.isArray(argv) || argv.length === 0) {
745
- return undefined;
746
- }
747
- return renderPmCommand(argv);
748
- }
749
- function normalizeOptionFlags(values) {
750
- if (!Array.isArray(values)) {
751
- return undefined;
752
- }
753
- const normalized = values
754
- .map((value) => value.trim())
755
- .filter((value) => value.length > 0);
756
- return normalized.length > 0 ? normalized : undefined;
757
- }
758
- function buildCommanderRecoveryPayload(context, overrides = {}) {
759
- const providedFields = normalizeOptionFlags(context?.providedOptionFlags);
760
- const normalizedArgs = Array.isArray(context?.normalizedInvocationArgs) &&
761
- context?.normalizedInvocationArgs.length > 0
762
- ? context.normalizedInvocationArgs
763
- : undefined;
764
- const attemptedCommand = typeof context?.attemptedCommand === "string"
765
- ? context.attemptedCommand
766
- : renderPmCommandFromArgs(normalizedArgs);
767
- const retryCommand = typeof context?.suggestedRetryCommand === "string"
768
- ? context.suggestedRetryCommand
769
- : undefined;
770
- return normalizeRecoveryPayload({
771
- attempted_command: attemptedCommand,
772
- normalized_args: normalizedArgs,
773
- provided_fields: providedFields,
774
- suggested_retry: retryCommand,
775
- ...overrides,
776
- });
777
- }
778
- function appendIfMissing(entries, value) {
779
- if (!value || entries.includes(value)) {
780
- return entries;
781
- }
782
- return [...entries, value];
783
- }
784
- // Linked-test mutation flags on `pm test` whose values commonly contain spaces and
785
- // nested "--" tokens (GH-191). Used to recognise the "too many arguments" failure
786
- // shape produced when such a value is not quoted into a single shell token.
787
- const LINKED_TEST_MUTATION_FLAGS = new Set(["--add", "--add-json", "--remove"]);
788
- // Entry-identity keys eligible for the two-token form; mirrors
789
- // LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG in bootstrap-args.ts.
790
- const LINKED_TEST_RETRY_KEYS = new Set(["command", "cmd", "path"]);
791
- function findLinkedTestMutationFlag(argv) {
792
- if (!Array.isArray(argv)) {
793
- return undefined;
794
- }
795
- for (const token of argv) {
796
- if (!token.startsWith("--")) {
797
- continue;
798
- }
799
- const equalsIndex = token.indexOf("=");
800
- const flag = equalsIndex >= 0 ? token.slice(0, equalsIndex) : token;
801
- if (LINKED_TEST_MUTATION_FLAGS.has(flag)) {
802
- return flag;
803
- }
804
- }
805
- return undefined;
806
- }
807
- /** Synthesize a copy-pasteable retry for the unquoted linked-test value shape `pm test <id> --add command npm test -- parser` by re-joining the shell-split value tokens into the documented quoted `key=value` form. Only fires when the item id already precedes the flag (so trailing tokens unambiguously belong to the value) and the token after `--add`/`--remove` is an entry-identity key. */
808
- export function buildLinkedTestQuotedRetryCommand(argv) {
809
- if (!Array.isArray(argv)) {
810
- return undefined;
811
- }
812
- const commandIndex = argv.indexOf("test");
813
- if (commandIndex < 0) {
814
- return undefined;
815
- }
816
- const idToken = argv[commandIndex + 1];
817
- if (typeof idToken !== "string" || idToken.startsWith("-")) {
818
- return undefined;
819
- }
820
- for (let index = commandIndex + 2; index < argv.length; index += 1) {
821
- const token = argv[index];
822
- if (token !== "--add" && token !== "--remove") {
823
- continue;
824
- }
825
- const key = argv[index + 1];
826
- if (typeof key !== "string" || !LINKED_TEST_RETRY_KEYS.has(key)) {
827
- return undefined;
828
- }
829
- const valueTokens = [];
830
- for (let cursor = index + 2; cursor < argv.length; cursor += 1) {
831
- const candidate = argv[cursor];
832
- // A bare "--" belongs to the re-joined command value; real long flags end it.
833
- if (candidate.startsWith("--") && candidate.length > 2) {
834
- break;
835
- }
836
- valueTokens.push(candidate);
837
- }
838
- if (valueTokens.length < 2) {
839
- // Single-token values are auto-merged at bootstrap; nothing to repair here.
840
- return undefined;
841
- }
842
- const merged = `${key}=${valueTokens.join(" ")}`;
843
- const rewritten = [
844
- ...argv.slice(0, index + 1),
845
- merged,
846
- ...argv.slice(index + 2 + valueTokens.length),
847
- ];
848
- return renderPmCommand(rewritten);
849
- }
850
- return undefined;
851
- }
852
- function buildMissingRequiredOptionGuidance(message, commandName, allowedTypes, context) {
853
- const requiredOption = message.match(/required option '([^']+)' not specified/);
854
- if (!requiredOption) {
855
- return null;
856
- }
857
- const optionFlag = normalizeRequiredOptionLabel(requiredOption[1]);
858
- const isType = optionFlag.startsWith("--type");
859
- const retryCommand = context?.suggestedRetryCommand;
860
- const providedFlags = normalizeOptionFlags(context?.providedOptionFlags);
861
- const missing = [optionFlag];
862
- const examples = commandExampleForRequiredOption(commandName, optionFlag, allowedTypes);
863
- const examplesWithRetry = retryCommand
864
- ? appendIfMissing(examples, retryCommand)
865
- : examples;
866
- const nextStepsBase = isType
867
- ? [
868
- `Allowed type values: ${allowedTypes}`,
869
- `Run "pm ${commandName ?? "create"} --help --type <value>" for type-aware policy details.`,
870
- ]
871
- : [
872
- `Run "pm ${commandName ?? "<command>"} --help" for required option guidance.`,
873
- ];
874
- const nextStepsWithRetry = retryCommand
875
- ? appendIfMissing(nextStepsBase, `Replay with preserved arguments: ${retryCommand}`)
876
- : nextStepsBase;
877
- const nextSteps = providedFlags && providedFlags.length > 0
878
- ? appendIfMissing(nextStepsWithRetry, `Already provided options: ${providedFlags.join(", ")}`)
879
- : nextStepsWithRetry;
880
- return makeGuidanceMessage({
881
- code: "missing_required_option",
882
- title: `Missing required option ${optionFlag}`,
883
- happened: `Commander rejected the command because ${optionFlag} was not provided.`,
884
- required: `Pass ${optionFlag} with a valid value before running the command.`,
885
- why: isType
886
- ? "--type selects item contract and policy routing, including required/disabled option rules."
887
- : "Required flags define mandatory command intent and prevent ambiguous execution.",
888
- examples: examplesWithRetry,
889
- nextSteps,
890
- recovery: buildCommanderRecoveryPayload(context, { missing }),
891
- });
892
- }
893
- function buildMissingRequiredArgumentGuidance(message, commandName, context) {
894
- const missingArgument = message.match(/missing required argument '([^']+)'/);
895
- if (!missingArgument) {
896
- return null;
897
- }
898
- const argumentName = missingArgument[1];
899
- return makeGuidanceMessage({
900
- code: "missing_required_argument",
901
- title: `Missing required argument ${argumentName}`,
902
- happened: `Command invocation omitted positional argument ${argumentName}.`,
903
- required: `Provide ${argumentName} in the expected command position.`,
904
- why: "Positional arguments identify the target entity or action context for the command.",
905
- examples: [`pm ${commandName ?? "<command>"} --help`],
906
- recovery: buildCommanderRecoveryPayload(context, {
907
- missing: [argumentName],
908
- }),
909
- });
910
- }
911
- function buildUnsupportedUpdateOptionGuidance(optionName, context, suggestions) {
912
- return makeGuidanceMessage({
913
- code: "unsupported_update_option",
914
- title: `Unsupported option ${optionName} for update`,
915
- happened: `pm update does not accept ${optionName} for linked artifact mutations.`,
916
- required: "Use dedicated linked-artifact commands instead of pm update for files/docs changes.",
917
- why: "pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",
918
- examples: [
919
- 'pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"',
920
- 'pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"',
921
- ],
922
- nextSteps: [
923
- 'Run "pm files --help" and "pm docs --help" for add/remove payload formats.',
924
- ],
925
- recovery: buildCommanderRecoveryPayload(context, {
926
- suggested_flags: suggestions,
927
- }),
928
- });
929
- }
930
- const UNKNOWN_OPTION_REQUIRED_BY_SCOPE = {
931
- declared_elsewhere: "Use an option declared on this path, or move the declared option to one of its accepting command paths.",
932
- declared_on_path: "Use the option with the value and syntax declared by this command path.",
933
- declared_nowhere: "Use a declared option on this command path; this spelling exists nowhere in the command lexicon.",
934
- };
935
- function resolveUnknownOptionCandidateContext(context) {
936
- const otherCommands = normalizeContextList(context.unknownOptionOtherCommands) ?? [];
937
- return {
938
- otherCommands,
939
- optionScope: context.unknownOptionScope ??
940
- (otherCommands.length > 0 ? "declared_elsewhere" : "declared_nowhere"),
941
- candidateTotal: context.unknownOptionOtherCommandsTotal ?? otherCommands.length,
942
- };
943
- }
944
- function buildUnknownOptionNextSteps(optionName, commandName, suggestions, candidateContext, retryCommand) {
945
- const proseCommands = candidateContext.otherCommands.slice(0, 3);
946
- const proseRemainder = candidateContext.candidateTotal - proseCommands.length;
947
- const proseRemainderText = proseRemainder > 0
948
- ? ` and ${String(proseRemainder)} more command path(s)`
949
- : "";
950
- return [
951
- "Run command help to confirm the exact option contracts for this command path.",
952
- suggestions.length
953
- ? `Nearest supported options: ${suggestions.join(", ")}`
954
- : undefined,
955
- proseCommands.length
956
- ? `${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`
957
- : undefined,
958
- candidateContext.optionScope === "declared_nowhere"
959
- ? `${optionName} is not declared on any command path. Use a nearest supported option on ${commandName ?? "the attempted command"}, or inspect that command's help.`
960
- : undefined,
961
- retryCommand
962
- ? `Replay with suggested correction: ${retryCommand}`
963
- : undefined,
964
- ].filter((entry) => typeof entry === "string");
965
- }
966
- /**
967
- * Publish a shell-free correction only when removing the unknown token leaves
968
- * positional ownership unambiguous; explicit producer guidance stays authoritative.
969
- */
970
- function resolveUnknownOptionRetry(context, optionName) {
971
- if (context.suggestedRetryCommand !== undefined) {
972
- return { retryCommand: context.suggestedRetryCommand };
973
- }
974
- const normalizedArgs = context.normalizedInvocationArgs;
975
- if (normalizedArgs === undefined)
976
- return {};
977
- if (normalizedArgs.filter((argument) => argument === optionName || argument.startsWith(`${optionName}=`)).length !== 1) {
978
- return {};
979
- }
980
- const optionIndex = normalizedArgs.findIndex((argument) => argument === optionName || argument.startsWith(`${optionName}=`));
981
- if (optionIndex < 0 ||
982
- normalizedArgs.includes("--") ||
983
- (!normalizedArgs[optionIndex]?.includes("=") &&
984
- optionIndex !== normalizedArgs.length - 1 &&
985
- normalizedArgs[optionIndex + 1]?.startsWith("-") !== true)) {
986
- return {};
987
- }
988
- const suggestedRetryArgs = stripGlobalBootstrapTokens(normalizedArgs.filter((_, index) => index !== optionIndex));
989
- return {
990
- retryCommand: renderPmCommand(suggestedRetryArgs),
991
- suggestedRetryArgs,
992
- };
993
- }
994
- function buildUnknownOptionGuidance(message, commandName, context) {
995
- const unknownOption = message.match(/unknown option '([^']+)'/);
996
- if (!unknownOption) {
997
- return null;
998
- }
999
- const guidanceContext = context ?? {};
1000
- const optionName = unknownOption[1];
1001
- const suggestions = normalizeOptionFlags(guidanceContext.unknownOptionSuggestions) ?? [];
1002
- const { retryCommand, suggestedRetryArgs } = resolveUnknownOptionRetry(guidanceContext, optionName);
1003
- if (commandName === "update" &&
1004
- (optionName === "--file" || optionName === "--doc")) {
1005
- return buildUnsupportedUpdateOptionGuidance(optionName, context, suggestions);
1006
- }
1007
- const candidateContext = resolveUnknownOptionCandidateContext(guidanceContext);
1008
- const nextSteps = buildUnknownOptionNextSteps(optionName, commandName, suggestions, candidateContext, retryCommand);
1009
- const examples = [
1010
- retryCommand,
1011
- `pm ${commandName ?? "<command>"} --help`,
1012
- ].filter((entry) => typeof entry === "string");
1013
- return makeGuidanceMessage({
1014
- code: "unknown_option",
1015
- title: `Unknown option ${optionName}`,
1016
- happened: `Commander does not recognize option ${optionName} for this command path.`,
1017
- required: UNKNOWN_OPTION_REQUIRED_BY_SCOPE[candidateContext.optionScope],
1018
- why: "Option contracts are command-specific and intentionally validated.",
1019
- flag: optionName,
1020
- value: optionName,
1021
- examples,
1022
- nextSteps,
1023
- recovery: buildCommanderRecoveryPayload(context, {
1024
- suggested_flags: suggestions.length > 0 ? suggestions : undefined,
1025
- suggested_retry: retryCommand,
1026
- suggested_retry_args: suggestedRetryArgs,
1027
- candidate_commands: candidateContext.otherCommands,
1028
- candidate_commands_total: candidateContext.candidateTotal || undefined,
1029
- candidate_commands_truncated: guidanceContext.unknownOptionOtherCommandsTruncated,
1030
- option_scope: candidateContext.optionScope,
1031
- }),
1032
- });
1033
- }
1034
- function buildKnownPackageCommandGuidance(commandToken, packageHint, baseExamples, baseNextSteps, context) {
1035
- const installStep = `"${commandToken}" is provided by the ${packageHint.packageName} package. Install it with: ${packageHint.installCommand}`;
1036
- // commander-usage may already append its generic "If this command comes from
1037
- // an optional package…" step for the same alias; keep only the specific one.
1038
- const nextSteps = baseNextSteps.filter((step) => !step.endsWith(`: ${packageHint.installCommand}`));
1039
- return makeGuidanceMessage({
1040
- code: "unknown_command",
1041
- title: `Unknown command ${commandToken}`,
1042
- happened: `pm does not expose command path "${commandToken}" in current runtime configuration. It is shipped by the optional ${packageHint.packageName} package.`,
1043
- required: `Install the ${packageHint.packageName} package, or use a valid command name or subcommand path.`,
1044
- why: "Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",
1045
- examples: dedupeStrings([packageHint.installCommand, ...baseExamples]),
1046
- nextSteps: dedupeStrings([installStep, ...nextSteps]),
1047
- recovery: buildCommanderRecoveryPayload(context),
1048
- });
1049
- }
1050
- function buildUnknownCommandGuidance(message, context) {
1051
- const unknownCommand = message.match(/unknown command '([^']+)'/);
1052
- if (!unknownCommand) {
1053
- return null;
1054
- }
1055
- const commandToken = unknownCommand[1];
1056
- const runtimeExamples = normalizeContextList(context?.unknownCommandExamples);
1057
- const runtimeNextSteps = normalizeContextList(context?.unknownCommandNextSteps);
1058
- const packageHint = resolveKnownPackageCommandHint(commandToken);
1059
- const baseExamples = runtimeExamples ?? ["pm --help"];
1060
- const baseNextSteps = runtimeNextSteps ?? [
1061
- "Verify spelling and active extensions, then rerun.",
1062
- ];
1063
- const failedExtensionNames = new Set(context?.failedExtensions?.map((entry) => entry.name.trim().toLowerCase()));
1064
- const hintedExtensionName = packageHint?.packageName
1065
- .replace(/^@unbrained\/pm-/, "")
1066
- .toLowerCase();
1067
- if (packageHint &&
1068
- (!hintedExtensionName || !failedExtensionNames.has(hintedExtensionName))) {
1069
- return buildKnownPackageCommandGuidance(commandToken, packageHint, baseExamples, baseNextSteps, context);
1070
- }
1071
- return makeGuidanceMessage({
1072
- code: "unknown_command",
1073
- title: `Unknown command ${commandToken}`,
1074
- happened: `pm does not expose command path "${commandToken}" in current runtime configuration.`,
1075
- required: "Use a valid command name or subcommand path.",
1076
- why: "Command registry includes core commands plus active extension command handlers.",
1077
- examples: baseExamples,
1078
- nextSteps: baseNextSteps,
1079
- recovery: buildCommanderRecoveryPayload(context),
1080
- });
1081
- }
1082
- function buildUnknownSubcommandGuidance(context) {
1083
- const commandPath = context?.unknownSubcommandPath?.trim();
1084
- const token = context?.unknownSubcommandToken?.trim();
1085
- const allowed = normalizeContextList(context?.unknownSubcommandAllowedValues);
1086
- if (!commandPath || !token || !allowed) {
1087
- return null;
1088
- }
1089
- const retryCommand = context?.suggestedRetryCommand;
1090
- return makeGuidanceMessage({
1091
- code: "unknown_subcommand",
1092
- title: `Unknown ${commandPath} subcommand ${token}`,
1093
- happened: `The positional token sequence "${token}" is not a declared ${commandPath} subcommand.`,
1094
- required: `Use one of: ${allowed.join(", ")}.`,
1095
- why: "Subcommands are single positional tokens; multi-word action names use hyphens.",
1096
- examples: [
1097
- ...(retryCommand ? [retryCommand] : []),
1098
- `pm ${commandPath} --help`,
1099
- ],
1100
- nextSteps: retryCommand
1101
- ? [`Retry with the declared hyphenated action: ${retryCommand}`]
1102
- : ["Choose one value from recovery.allowed_values."],
1103
- recovery: buildCommanderRecoveryPayload(context, {
1104
- allowed_values: allowed,
1105
- suggested_retry: retryCommand,
1106
- }),
1107
- });
1108
- }
1109
- function buildLinkedTestValueNotQuotedGuidance(message, commandName, context) {
1110
- if (!/too many arguments/i.test(message) || commandName !== "test") {
1111
- return null;
1112
- }
1113
- const argv = context?.normalizedInvocationArgs;
1114
- const mutationFlag = findLinkedTestMutationFlag(argv);
1115
- if (!mutationFlag) {
1116
- return null;
1117
- }
1118
- const retryCommand = buildLinkedTestQuotedRetryCommand(argv);
1119
- return makeGuidanceMessage({
1120
- code: "linked_test_value_not_quoted",
1121
- title: `Linked-test ${mutationFlag} value must be one argument`,
1122
- happened: `Commander saw extra positional tokens after the item id — usually a ${mutationFlag} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,
1123
- 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.`,
1124
- why: "The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",
1125
- examples: [
1126
- ...(retryCommand ? [retryCommand] : []),
1127
- 'pm test pm-a1b2 --add "command=npm test -- parser"',
1128
- 'pm test pm-a1b2 --add command "npm test -- parser"',
1129
- `pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`,
1130
- ],
1131
- nextSteps: [
1132
- ...(retryCommand
1133
- ? [`Replay with the value re-joined into one argument: ${retryCommand}`]
1134
- : []),
1135
- "Prefer --add-json for commands containing commas, equals signs, or quotes.",
1136
- 'Run "pm test --help" for linked-test entry contracts.',
1137
- ],
1138
- recovery: buildCommanderRecoveryPayload(context, retryCommand ? { suggested_retry: retryCommand } : {}),
1139
- });
1140
- }
1141
- const TRANSPOSED_COLLECTION_COMMANDS = new Set([
1142
- "comments",
1143
- "docs",
1144
- "files",
1145
- "learnings",
1146
- "notes",
1147
- "test",
1148
- ]);
1149
- function buildTransposedCollectionActionGuidance(message, commandName, context) {
1150
- if (!/too many arguments/i.test(message) ||
1151
- !TRANSPOSED_COLLECTION_COMMANDS.has(commandName ?? "")) {
1152
- return null;
1153
- }
1154
- const argv = context?.normalizedInvocationArgs ?? [];
1155
- const commandIndex = argv.findIndex((token) => token === commandName);
1156
- const action = argv[commandIndex + 1];
1157
- const parsedItemId = argv[commandIndex + 2];
1158
- const itemId = context?.verifiedCollectionItemId?.trim();
1159
- if (action?.toLowerCase() !== "add" ||
1160
- !parsedItemId ||
1161
- parsedItemId.startsWith("-") ||
1162
- !itemId ||
1163
- itemId.toLowerCase() !== parsedItemId.toLowerCase()) {
1164
- return null;
1165
- }
1166
- const suggestedRetry = `pm ${commandName} ${itemId} --add <value>`;
1167
- return makeGuidanceMessage({
1168
- code: "collection_transposed_subcommand",
1169
- title: `Transposed ${commandName} add syntax`,
1170
- 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.`,
1171
- required: `Place the item id immediately after ${commandName}, then use --add for the value.`,
1172
- why: "Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",
1173
- examples: [suggestedRetry, `pm ${commandName} --help`],
1174
- recovery: buildCommanderRecoveryPayload(context, {
1175
- parsed_positionals: [
1176
- { role: "transposed_subcommand", value: action },
1177
- { role: "item_id", value: itemId },
1178
- ],
1179
- suggested_retry: suggestedRetry,
1180
- }),
1181
- });
1182
- }
1183
- const CONTEXT_GUIDANCE_VALUE_FLAGS = new Set([
1184
- "--activity-limit",
1185
- "--assignee",
1186
- "--assignee-filter",
1187
- "--date",
1188
- "--depth",
1189
- "--fields",
1190
- "--format",
1191
- "--from",
1192
- "--limit",
1193
- "--parent",
1194
- "--path",
1195
- "--pm-path",
1196
- "--priority",
1197
- "--release",
1198
- "--section",
1199
- "--sprint",
1200
- "--stale-threshold",
1201
- "--tag",
1202
- "--to",
1203
- "--type",
1204
- ]);
1205
- const CONTEXT_GUIDANCE_COMMAND_NAMES = new Set(["context", "ctx"]);
1206
- function buildContextItemArgumentGuidance(message, commandName, context) {
1207
- if (!/too many arguments/i.test(message) ||
1208
- !CONTEXT_GUIDANCE_COMMAND_NAMES.has(commandName ?? "")) {
1209
- return null;
1210
- }
1211
- const argv = context?.normalizedInvocationArgs ?? [];
1212
- const commandIndex = argv.findIndex((token) => CONTEXT_GUIDANCE_COMMAND_NAMES.has(token));
1213
- const searchIndex = commandIndex === -1 ? 1 : commandIndex + 1;
1214
- const match = message.match(/got \d+:\s*(\S+)/i);
1215
- let positional = match ? match[1].replace(/\.$/, "") : undefined;
1216
- if (positional === undefined) {
1217
- let skipFlagValue = false;
1218
- for (const token of argv.slice(searchIndex)) {
1219
- if (skipFlagValue) {
1220
- skipFlagValue = false;
1221
- continue;
1222
- }
1223
- const flagName = token.split("=")[0];
1224
- if (CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)) {
1225
- skipFlagValue = !token.includes("=");
1226
- continue;
1227
- }
1228
- if (token.startsWith("-")) {
1229
- continue;
1230
- }
1231
- positional = token;
1232
- break;
1233
- }
1234
- }
1235
- if (!positional) {
1236
- return null;
1237
- }
1238
- const getCommand = `pm get ${positional}`;
1239
- return makeGuidanceMessage({
1240
- code: "context_takes_no_item_argument",
1241
- title: "pm context takes no item argument",
1242
- happened: `pm context renders a workspace-level snapshot and received the positional argument "${positional}".`,
1243
- required: `Use ${getCommand} for one item's full details, or pm context --parent ${positional} to scope the snapshot to that item's subtree.`,
1244
- why: "Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",
1245
- examples: [getCommand, `pm context --parent ${positional}`],
1246
- recovery: buildCommanderRecoveryPayload(context, {
1247
- suggested_retry: getCommand,
1248
- }),
1249
- });
1250
- }
1251
- function buildCommanderErrorGuidance(rawMessage, commandName, allowedTypes, context) {
1252
- const message = normalizeMessage(rawMessage);
1253
- const guidance = buildMissingRequiredOptionGuidance(message, commandName, allowedTypes, context) ??
1254
- buildMissingRequiredArgumentGuidance(message, commandName, context) ??
1255
- buildUnknownOptionGuidance(message, commandName, context) ??
1256
- buildUnknownCommandGuidance(message, context) ??
1257
- buildUnknownSubcommandGuidance(context) ??
1258
- buildTransposedCollectionActionGuidance(message, commandName, context) ??
1259
- buildLinkedTestValueNotQuotedGuidance(message, commandName, context) ??
1260
- buildContextItemArgumentGuidance(message, commandName, context);
1261
- if (guidance) {
1262
- return guidance;
1263
- }
1264
- return makeGuidanceMessage({
1265
- code: "invalid_command_usage",
1266
- title: "Invalid command usage",
1267
- happened: message,
1268
- required: "Use the command with valid arguments and options.",
1269
- why: "Commander validates CLI contracts before execution.",
1270
- examples: ["pm --help", `pm ${commandName ?? "<command>"} --help`],
1271
- recovery: buildCommanderRecoveryPayload(context),
1272
- });
1273
- }
1274
- /** Implements format pm cli error for display for the public runtime surface of this module. */
1275
- export function formatPmCliErrorForDisplay(rawMessage, context) {
1276
- const guidance = buildPmCliErrorGuidance(rawMessage, context);
1277
- return projectPmDiagnosticText(renderGuidanceMessage(guidance), guidance.required).output;
1278
- }
1279
- /** Implements classify pm cli error for the public runtime surface of this module. */
1280
- export function classifyPmCliError(rawMessage, context) {
1281
- return guidanceToClassification(buildPmCliErrorGuidance(rawMessage, context));
1282
- }
1283
- /** Implements format pm cli error for json for the public runtime surface of this module. */
1284
- export function formatPmCliErrorForJson(rawMessage, exitCode, context) {
1285
- return projectJsonErrorGuidance(buildPmCliErrorGuidance(rawMessage, context), exitCode);
1286
- }
1287
- /** Implements format commander error for display for the public runtime surface of this module. */
1288
- export function formatCommanderErrorForDisplay(rawMessage, commandName, allowedTypes, context) {
1289
- const guidance = buildCommanderErrorGuidance(rawMessage, commandName, allowedTypes, context);
1290
- return projectPmDiagnosticText(renderGuidanceMessage(guidance), guidance.required).output;
1291
- }
1292
- /** Implements classify commander error for the public runtime surface of this module. */
1293
- export function classifyCommanderError(rawMessage, commandName, allowedTypes, context) {
1294
- return guidanceToClassification(buildCommanderErrorGuidance(rawMessage, commandName, allowedTypes, context));
1295
- }
1296
- /** Implements format commander error for json for the public runtime surface of this module. */
1297
- export function formatCommanderErrorForJson(rawMessage, commandName, allowedTypes, exitCode, context) {
1298
- return projectJsonErrorGuidance(buildCommanderErrorGuidance(rawMessage, commandName, allowedTypes, context), exitCode);
1299
- }
1300
- /** Implements format unknown error for json for the public runtime surface of this module. */
1301
- export function formatUnknownErrorForJson(rawMessage, exitCode) {
1302
- const guidance = buildUnknownErrorGuidance(rawMessage);
1303
- return projectJsonErrorGuidance(guidance, exitCode);
1304
- }
1305
- function buildUnknownErrorGuidance(rawMessage) {
1306
- const message = normalizeMessage(rawMessage);
1307
- if (isModuleResolutionErrorMessage(message)) {
1308
- return makeGuidanceMessage({
1309
- code: "module_import_failed",
1310
- title: "Module import failed",
1311
- happened: message,
1312
- required: "Ensure the active checkout is built and any package or extension entry file exists before retrying.",
1313
- 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.",
1314
- examples: [
1315
- "pnpm build",
1316
- "pm package manage --doctor --project",
1317
- "pm health --check-only --json",
1318
- ],
1319
- nextSteps: [
1320
- "Rebuild the checkout or package that provides the missing module.",
1321
- "Run package doctor for installed extensions when the failure follows package installation or activation.",
1322
- "Rerun the original pm command after the runtime files are present.",
1323
- ],
1324
- });
1325
- }
1326
- return makeGuidanceMessage({
1327
- code: "unknown_error",
1328
- title: "Unhandled error",
1329
- happened: message,
1330
- required: "Inspect command input and runtime state, then retry.",
1331
- why: "Unexpected runtime failures can occur from environment or extension-level issues.",
1332
- examples: ["pm --help", "pm health --json"],
1333
- });
1334
- }
1335
- /** Implements classify unknown error for the public runtime surface of this module. */
1336
- export function classifyUnknownError(rawMessage) {
1337
- return guidanceToClassification(buildUnknownErrorGuidance(rawMessage));
1338
- }
1339
- /** Public contract for test only, shared by SDK and presentation-layer consumers. */
1340
- export const _testOnly = {
1341
- applyPmCliErrorContext,
1342
- appendIfMissing,
1343
- buildCommanderRecoveryPayload,
1344
- buildFallbackTitleFromMessage,
1345
- commandExampleForRequiredOption,
1346
- dedupeStrings,
1347
- guidanceToClassification,
1348
- guidanceToJsonEnvelope,
1349
- normalizeRecoveryPayload,
1350
- renderList,
1351
- resolveKnownPackageCommandHint,
1352
- };
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a2919889-aa1a-54a6-8a2f-95d4484b9e65")}catch(e2){}})();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";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){if(!message.why){return false}if(message.recovery?.recovery_mode==="compact"){return false}return!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"};const CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"};const SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"};const GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"};const 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 void 0}return KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){if(entries.length===0){return[]}return[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values)){return void 0}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 void 0}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){if(typeof value==="string"&&value.trim().length>0){normalized[key]=value.trim()}}function assignRecoveryCollection(normalized,key,value){if(key==="parsed_positionals"){if(!Array.isArray(value))return;const parsedPositionals=value.map(entry=>({role:typeof entry?.role==="string"?entry.role.trim():"",value:typeof entry?.value==="string"?entry.value.trim():""})).filter(entry=>entry.role.length>0&&entry.value.length>0);if(parsedPositionals.length>0){normalized.parsed_positionals=parsedPositionals}return}const values=normalizeStringArray(value);if(values){normalized[key]=values}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!=="object"){return void 0}const normalized={};if(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);if(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}if(payload.candidate_commands_truncated===true){normalized.candidate_commands_truncated=true}if(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);if(typeof payload.retry_after_ms==="number"&&Number.isSafeInteger(payload.retry_after_ms)&&payload.retry_after_ms>=0){normalized.retry_after_ms=payload.retry_after_ms}const fallbackCandidates=normalizeRecoveryCandidates(payload.fallback_candidates);if(fallbackCandidates){normalized.fallback_candidates=fallbackCandidates}assignRecoveryString(normalized,"next_best_command",payload.next_best_command);return Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){if(value){lines.push(` ${label}: ${value}`)}}function appendRecoveryListLine(lines,label,values,separator){if(values&&values.length>0){lines.push(` ${label}: ${values.join(separator)}`)}}function renderRecoveryBundle(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized){return[]}const lines=["Recovery bundle:"];appendRecoveryTextLine(lines,"suggested_retry",normalized.suggested_retry);appendRecoveryTextLine(lines,"attempted_command",normalized.attempted_command);appendRecoveryListLine(lines,"normalized_args",normalized.normalized_args," ");if(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}`)}}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,", ");if(typeof normalized.candidate_commands_total==="number"){lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`)}if(normalized.candidate_commands_truncated===true){lines.push(" candidate_commands_truncated: true")}if(normalized.option_scope!==void 0){lines.push(` option_scope: ${normalized.option_scope}`)}if(typeof normalized.retry_after_ms==="number"){lines.push(` retry_after_ms: ${normalized.retry_after_ms}`)}appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command);if(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}`];if(message.nextSteps&&message.nextSteps.length>0){lines.push("");lines.push(...renderList("Next steps:",message.nextSteps))}lines.push("","What happened:",` ${message.happened}`);if(message.why){lines.push("","Why:");lines.push(` ${message.why}`)}if(message.examples&&message.examples.length>0){lines.push("");lines.push(...renderList("Examples:",message.examples))}if(message.verificationErrors&&message.verificationErrors.length>0){lines.push("");lines.push(...renderList("Verification errors:",message.verificationErrors))}const recoveryLines=renderRecoveryBundle(message.recovery);if(recoveryLines.length>0){lines.push("");lines.push(...recoveryLines)}return lines.join("\n")}function attachStructuredGuidanceDetails(payload,message){if(includeWhyInStructuredGuidance(message)){payload.why=message.why}if(message.examples&&message.examples.length>0){payload.examples=message.examples}if(message.nextSteps&&message.nextSteps.length>0){payload.next_steps=message.nextSteps}if(message.verificationErrors&&message.verificationErrors.length>0){payload.verification_errors=message.verificationErrors}if(message.flag!==void 0)payload.flag=message.flag;if(message.value!==void 0)payload.value=message.value;if(message.unmatchedSelectors!==void 0)payload.unmatched_selectors=message.unmatchedSelectors;if(message.availableDependencies!==void 0)payload.available_dependencies=message.availableDependencies;if(message.recovery){payload.recovery=message.recovery}return 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}=`))};const mentionedFlag=[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag));if(mentionedFlag)return mentionedFlag;return message.recovery?.provided_fields?.map(field=>field.split("=",1)[0]).find(field=>isAdmissibleCandidate(field))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(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 candidateIndex>=0?normalizedArgs[candidateIndex+1]:void 0}const allowedValues=message.recovery?.allowed_values;if(!allowedValues?.length)return void 0;return normalizedArgs.find((argument,index)=>index>0&&!argument.startsWith("-")&&!allowedValues.includes(argument))}function buildRefusalEnvelope(message,exitCode){const normalizedArgs=message.recovery?.normalized_args??[];const candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs);const rejectedValue=resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag);return{surface:candidateFlag??message.recovery?.missing?.[0]??inferCommandNameFromRecovery(message.recovery)??"command",...rejectedValue!==void 0?{rejected_value:rejectedValue}:{},...message.recovery?.allowed_values?.length?{legal_domain:message.recovery.allowed_values}:{},exit_code:exitCode}}function guidanceToJsonEnvelope(message,exitCode){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,exit_code:exitCode,refusal:buildRefusalEnvelope(message,exitCode)},message)}function projectJsonErrorGuidance(guidance,exitCode){const recovery=guidance.recovery;const hasActionableRecovery=Boolean(recovery?.suggested_retry)||Boolean(recovery?.suggested_retry_args?.length)||Boolean(recovery?.allowed_values?.length)||Boolean(recovery?.candidate_commands?.length)||Boolean(guidance.nextSteps?.length);return projectPmDiagnosticOutput(guidanceToJsonEnvelope(guidance,exitCode),{diagnosticClass:hasActionableRecovery?"recovery_bundle":"error"})}function guidanceToClassification(message){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required},message)}function normalizeMessage(message){return message.replace(/\(outputHelp\)/g,"").trim()}function isModuleResolutionErrorMessage(message){const normalized=message.toLowerCase();return normalized.includes("cannot find module")||normalized.includes("cannot find package")||normalized.includes("err_module_not_found")||normalized.includes("module_not_found")}function normalizeContextList(values){if(!Array.isArray(values)){return void 0}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;const result=[];for(const value of values){if(seen.has(value)){continue}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);if(!match){return[]}return match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry))}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args;const fields=recovery?.provided_fields;const replacement=allowedValues[0];if(!Array.isArray(args)||!Array.isArray(fields)||!replacement){return void 0}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];nextArgs[index+1]=replacement;return renderPmCommand(nextArgs)}}return void 0}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length===0){return void 0}if(firstLine.length<=120){return firstLine}return`${firstLine.slice(0,117)}...`}function normalizeContextValue(value,fallback){return typeof value==="string"&&value.trim().length>0?value.trim():fallback}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context){return guidance}const normalizedRawMessage=normalizeMessage(rawMessage);const code=normalizeContextValue(context.code,guidance.code);const type=normalizeContextValue(context.type,errorType(code));const examples=normalizeContextList(context.examples)??guidance.examples;const nextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps;const verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors;const fallbackTitle=guidance.code==="command_failed"&&context.code?buildFallbackTitleFromMessage(normalizedRawMessage):void 0;const contextRecovery=normalizeRecoveryPayload(context.recovery);const recovery=contextRecovery&&guidance.recovery?normalizeRecoveryPayload({...guidance.recovery,...contextRecovery}):contextRecovery??guidance.recovery;return{...guidance,code,type,title:fallbackTitle??guidance.title,happened:normalizedRawMessage.length>0?normalizedRawMessage:guidance.happened,required:normalizeContextValue(context.required,guidance.required),why:normalizeContextValue(context.why,guidance.why),examples,nextSteps,verificationErrors,flag:context.flag,value:context.value,unmatchedSelectors:context.unmatched_selectors,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];const nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);if(nearbyRoot){return applyPmCliErrorContext(makeGuidanceMessage({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}.`]}),rawMessage,context)}return applyPmCliErrorContext(makeGuidanceMessage({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];const isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId);const 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.`;const 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."];return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",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}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){if(!message.includes("is assigned to")||!message.includes("Use --force to override")){return null}return 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}return applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),rawMessage,context)}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /);const missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions){return null}const plural=Boolean(missingRequiredOptions);const missingOptionFlag=!plural?message.replace(/^Missing required option\s+/,"").trim():null;const missingOptionLabel=missingOptionFlag??"";const 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){if(!message.startsWith("No update flags provided")){return null}return 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)}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!message.startsWith("Invalid ")&&!message.includes(" must be ")&&!message.includes(" requires ")){return null}const recovery=normalizeRecoveryPayload(context?.recovery);const commandName=inferCommandNameFromRecovery(recovery);const helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help";const allowedValues=inferAllowedValuesFromMessage(message);const enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues});const retryExample=buildAllowedValueRetryCommand(recovery,allowedValues);const examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"];const 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);const guidance=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);if(guidance){return guidance}return 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){if(commandName==="create"&&optionFlag.startsWith("--type")){const firstAllowed=allowedTypes.split("|")[0]||"Task";return[`pm create --title "Example title" --description "Example description" --type ${firstAllowed} --status open --priority 1 --message "Create item" --create-mode progressive`]}if(commandName==="update"){return['pm update pm-a1b2 --status in_progress --message "Start implementation"']}return[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();const firstLongFlag=normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0];return firstLongFlag??normalized}function renderPmCommandFromArgs(argv){if(!Array.isArray(argv)||argv.length===0){return void 0}return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values)){return void 0}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);const normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0;const attemptedCommand=typeof context?.attemptedCommand==="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs);const retryCommand=typeof context?.suggestedRetryCommand==="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,...overrides})}function appendIfMissing(entries,value){if(!value||entries.includes(value)){return entries}return[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]);const LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(!Array.isArray(argv)){return void 0}for(const token of argv){if(!token.startsWith("--")){continue}const equalsIndex=token.indexOf("=");const flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag)){return flag}}return void 0}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv)){return void 0}const commandIndex=argv.indexOf("test");if(commandIndex<0){return void 0}const idToken=argv[commandIndex+1];if(typeof idToken!=="string"||idToken.startsWith("-")){return void 0}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 void 0}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 void 0}const merged=`${key}=${valueTokens.join(" ")}`;const rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}return void 0}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption){return null}const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]);const isType=optionFlag.startsWith("--type");const retryCommand=context?.suggestedRetryCommand;const providedFlags=normalizeOptionFlags(context?.providedOptionFlags);const missing=[optionFlag];const examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes);const examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples;const 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.`];const nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase;const 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);const proseRemainder=candidateContext.candidateTotal-proseCommands.length;const proseRemainderText=proseRemainder>0?` and ${String(proseRemainder)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",suggestions.length?`Nearest supported options: ${suggestions.join(", ")}`:void 0,proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,candidateContext.optionScope==="declared_nowhere"?`${optionName} is not declared on any command path. Use a nearest supported option on ${commandName??"the attempted command"}, or inspect that command's help.`:void 0,retryCommand?`Replay with suggested correction: ${retryCommand}`:void 0].filter(entry=>typeof entry==="string")}function resolveUnknownOptionRetry(context,optionName){if(context.suggestedRetryCommand!==void 0){return{retryCommand:context.suggestedRetryCommand}}const normalizedArgs=context.normalizedInvocationArgs;if(normalizedArgs===void 0)return{};if(normalizedArgs.filter(argument=>argument===optionName||argument.startsWith(`${optionName}=`)).length!==1){return{}}const optionIndex=normalizedArgs.findIndex(argument=>argument===optionName||argument.startsWith(`${optionName}=`));if(optionIndex<0||normalizedArgs.includes("--")||!normalizedArgs[optionIndex]?.includes("=")&&optionIndex!==normalizedArgs.length-1&&normalizedArgs[optionIndex+1]?.startsWith("-")!==true){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??{};const optionName=unknownOption[1];const suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[];const{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc")){return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions)}const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext);const nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);const examples=[retryCommand,`pm ${commandName??"<command>"} --help`].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}`;const 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];const runtimeExamples=normalizeContextList(context?.unknownCommandExamples);const runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps);const packageHint=resolveKnownPackageCommandHint(commandToken);const baseExamples=runtimeExamples??["pm --help"];const baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."];const failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase()));const hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();if(packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))){return buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context)}return 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();const token=context?.unknownSubcommandToken?.trim();const allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed){return null}const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${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 ${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;const mutationFlag=findLinkedTestMutationFlag(argv);if(!mutationFlag){return null}const retryCommand=buildLinkedTestQuotedRetryCommand(argv);return makeGuidanceMessage({code:"linked_test_value_not_quoted",title:`Linked-test ${mutationFlag} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${mutationFlag} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${mutationFlag} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...retryCommand?[retryCommand]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...retryCommand?[`Replay with the value re-joined into one argument: ${retryCommand}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:buildCommanderRecoveryPayload(context,retryCommand?{suggested_retry:retryCommand}:{})})}const TRANSPOSED_COLLECTION_COMMANDS=new Set(["comments","docs","files","learnings","notes","test"]);function buildTransposedCollectionActionGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!TRANSPOSED_COLLECTION_COMMANDS.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>token===commandName);const action=argv[commandIndex+1];const parsedItemId=argv[commandIndex+2];const 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"]);const 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??[];const commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token));const searchIndex=commandIndex===-1?1:commandIndex+1;const match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=false;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=false;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(token.startsWith("-")){continue}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);const guidance=buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context)??buildMissingRequiredArgumentGuidance(message,commandName,context)??buildUnknownOptionGuidance(message,commandName,context)??buildUnknownCommandGuidance(message,context)??buildUnknownSubcommandGuidance(context)??buildTransposedCollectionActionGuidance(message,commandName,context)??buildLinkedTestValueNotQuotedGuidance(message,commandName,context)??buildContextItemArgumentGuidance(message,commandName,context);if(guidance){return guidance}return 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 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);if(isModuleResolutionErrorMessage(message)){return 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."]})}return 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};
1353
2
  //# sourceMappingURL=error-guidance.js.map
1354
- //# debugId=ca79853d-468c-5522-b5f9-6509c66e3d9b