@unbrained/pm-cli 2026.9.7 → 2026.9.9

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 (746) 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 +7 -2
  6. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
  7. package/.claude-plugin/marketplace.json +2 -2
  8. package/CHANGELOG.md +231 -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.d.ts +0 -5
  92. package/dist/cli/register-mutation.js +19 -1893
  93. package/dist/cli/register-operations.js +1 -920
  94. package/dist/cli/register-setup.js +1 -716
  95. package/dist/cli/register-structured-mutation.js +1 -196
  96. package/dist/cli/registration-helpers.js +1 -5
  97. package/dist/cli/runtime-compatibility-boundary.js +4 -42
  98. package/dist/cli/schema-registration-helpers.js +1 -73
  99. package/dist/cli/search-refresh.js +1 -13
  100. package/dist/cli/stats-analytics-json.js +1 -68
  101. package/dist/cli/telemetry-flush.js +1 -10
  102. package/dist/cli-bundle/bundle-manifest.json +164 -156
  103. package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-3IPRM75M.js} +3 -3
  104. package/dist/cli-bundle/chunks/chunk-4VL5P22L.js +2 -0
  105. package/dist/cli-bundle/chunks/chunk-AAFBV3U3.js +29 -0
  106. package/dist/cli-bundle/chunks/chunk-D3YVILJJ.js +20 -0
  107. package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
  108. package/dist/cli-bundle/chunks/chunk-ECBLPN7B.js +3 -0
  109. package/dist/cli-bundle/chunks/chunk-J6ERHBV2.js +235 -0
  110. package/dist/cli-bundle/chunks/chunk-JUNJ5EKI.js +2 -0
  111. package/dist/cli-bundle/chunks/chunk-L5RCDKQ2.js +2 -0
  112. package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
  113. package/dist/cli-bundle/chunks/chunk-OHNLSGGV.js +79 -0
  114. package/dist/cli-bundle/chunks/chunk-WQKMSFBV.js +5 -0
  115. package/dist/cli-bundle/chunks/{chunk-BAX2BYUW.js → chunk-XZ6T7YPP.js} +256 -150
  116. package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-Z3XVXUVF.js} +4 -4
  117. package/dist/cli-bundle/chunks/register-list-query-UIHRCS6D.js +11 -0
  118. package/dist/cli-bundle/chunks/register-mutation-WHWMGRVX.js +20 -0
  119. package/dist/cli-bundle/chunks/register-operations-64YZYTC5.js +2 -0
  120. package/dist/cli-bundle/chunks/register-setup-PERI45EM.js +2 -0
  121. package/dist/cli-bundle/focused-chunks/chunk-2W4XIYOB.js +2 -0
  122. package/dist/cli-bundle/focused-chunks/chunk-2WSBXIGF.js +12 -0
  123. package/dist/cli-bundle/focused-chunks/chunk-5FHTCOHS.js +3 -0
  124. package/dist/cli-bundle/focused-chunks/chunk-7N6DOREF.js +26 -0
  125. package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-7PC4R5QB.js} +2 -2
  126. package/dist/cli-bundle/focused-chunks/chunk-BUCJUZVG.js +6 -0
  127. package/dist/cli-bundle/focused-chunks/chunk-FE3BABLJ.js +2 -0
  128. package/dist/cli-bundle/focused-chunks/chunk-IWITF53W.js +2 -0
  129. package/dist/cli-bundle/focused-chunks/chunk-OQUGRHKV.js +10 -0
  130. package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-PNKIANFZ.js} +2 -2
  131. package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-QQQ4SAUO.js} +3 -3
  132. package/dist/cli-bundle/focused-chunks/chunk-TTYXF5YD.js +177 -0
  133. package/dist/cli-bundle/focused-chunks/chunk-XNR3DM6J.js +2 -0
  134. package/dist/cli-bundle/focused-chunks/chunk-XSS3APUF.js +9 -0
  135. package/dist/cli-bundle/focused-chunks/chunk-YCDQ2N23.js +8 -0
  136. package/dist/cli-bundle/focused-chunks/chunk-YJUXGS57.js +20 -0
  137. package/dist/cli-bundle/focused-chunks/chunk-ZTCE4UO6.js +58 -0
  138. package/dist/cli-bundle/main.js +20 -20
  139. package/dist/cli-bundle/sdk-authoring.js +1 -1
  140. package/dist/cli-bundle/sdk-contracts.js +2 -2
  141. package/dist/cli-bundle/sdk-core.js +37 -37
  142. package/dist/cli-bundle/sdk-governance.js +1 -1
  143. package/dist/cli-bundle/sdk-graph.js +1 -1
  144. package/dist/cli-bundle/sdk-merge.js +42 -42
  145. package/dist/cli-bundle/sdk-query.js +1 -1
  146. package/dist/cli-bundle/sdk-runtime.js +1 -1
  147. package/dist/cli-bundle/sdk-testing.js +1 -1
  148. package/dist/cli-bundle/sdk.js +11 -11
  149. package/dist/cli.js +1 -104
  150. package/dist/core/checkpoint/checkpoint-gc.js +1 -169
  151. package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
  152. package/dist/core/config/nested-settings.js +1 -534
  153. package/dist/core/config/positional-value.js +1 -109
  154. package/dist/core/diagnostics/remediation.js +1 -506
  155. package/dist/core/extensions/activation-summary-markdown.js +2 -145
  156. package/dist/core/extensions/activation-summary.js +1 -92
  157. package/dist/core/extensions/activation-transaction.js +1 -46
  158. package/dist/core/extensions/capability-usage.js +1 -173
  159. package/dist/core/extensions/command-hook-context.js +1 -13
  160. package/dist/core/extensions/command-metadata-contract.js +1 -22
  161. package/dist/core/extensions/command-visibility-tier.js +1 -29
  162. package/dist/core/extensions/contribution-inventory.js +1 -173
  163. package/dist/core/extensions/exporter-output-contract.js +1 -66
  164. package/dist/core/extensions/extension-candidate.js +1 -18
  165. package/dist/core/extensions/extension-capability-aliases.js +1 -158
  166. package/dist/core/extensions/extension-hook-runtime.js +1 -699
  167. package/dist/core/extensions/extension-policy.js +1 -599
  168. package/dist/core/extensions/extension-registries.js +1 -62
  169. package/dist/core/extensions/extension-runtime-helpers.js +1 -33
  170. package/dist/core/extensions/extension-types.js +1 -102
  171. package/dist/core/extensions/flag-definition-validation.js +1 -52
  172. package/dist/core/extensions/flag-value-types.js +1 -64
  173. package/dist/core/extensions/index.js +1 -526
  174. package/dist/core/extensions/item-field-types.js +1 -39
  175. package/dist/core/extensions/item-fields.js +1 -261
  176. package/dist/core/extensions/loader.js +1 -2223
  177. package/dist/core/extensions/manifest-schema.js +1 -69
  178. package/dist/core/extensions/module-graph-snapshot.js +1 -33
  179. package/dist/core/extensions/preflight-ownership.js +1 -41
  180. package/dist/core/extensions/registration-validation.js +1 -82
  181. package/dist/core/extensions/registration-values.js +1 -209
  182. package/dist/core/extensions/reserved-host-flags.js +1 -36
  183. package/dist/core/extensions/runtime-registrations.js +1 -67
  184. package/dist/core/extensions/service-ownership.js +1 -19
  185. package/dist/core/extensions/version-compat.js +1 -216
  186. package/dist/core/fs/fs-utils.js +2 -158
  187. package/dist/core/fs/host-environment-errors.js +1 -141
  188. package/dist/core/fs/index.js +1 -9
  189. package/dist/core/fs/path-utils.js +1 -17
  190. package/dist/core/governance/content-fields.js +1 -160
  191. package/dist/core/governance/issue-codes.js +1 -151
  192. package/dist/core/governance/metadata-coverage.js +1 -358
  193. package/dist/core/history/drift-cache.js +3 -72
  194. package/dist/core/history/drift-scan.js +1 -342
  195. package/dist/core/history/event-classification.js +1 -109
  196. package/dist/core/history/event-index.js +8 -784
  197. package/dist/core/history/history-compact-bulk.js +1 -104
  198. package/dist/core/history/history-diff.js +1 -158
  199. package/dist/core/history/history-rewrite.d.ts +6 -1
  200. package/dist/core/history/history-rewrite.js +1 -107
  201. package/dist/core/history/history-storage-stats.js +1 -102
  202. package/dist/core/history/history-stream-policy.js +1 -62
  203. package/dist/core/history/history.js +2 -617
  204. package/dist/core/history/identity.js +1 -30
  205. package/dist/core/history/index.js +1 -9
  206. package/dist/core/history/projection.js +1 -196
  207. package/dist/core/history/read.d.ts +9 -0
  208. package/dist/core/history/read.js +1 -57
  209. package/dist/core/history/replay.js +2 -439
  210. package/dist/core/history/version-address.js +1 -32
  211. package/dist/core/history/workspace-history.js +2 -433
  212. package/dist/core/io/body-file.js +1 -62
  213. package/dist/core/io/bulk-ids-input.js +1 -112
  214. package/dist/core/item/actionability.js +1 -327
  215. package/dist/core/item/dependency-reference.js +1 -20
  216. package/dist/core/item/id.js +1 -112
  217. package/dist/core/item/index.js +1 -12
  218. package/dist/core/item/item-format-version.js +1 -78
  219. package/dist/core/item/item-format.js +5 -1473
  220. package/dist/core/item/item-record.js +1 -23
  221. package/dist/core/item/item-type-definition.js +1 -133
  222. package/dist/core/item/parent-reference-policy.js +1 -57
  223. package/dist/core/item/parse.js +2 -603
  224. package/dist/core/item/plan-lifecycle.js +1 -19
  225. package/dist/core/item/priority.js +1 -61
  226. package/dist/core/item/sprint-release-format.js +1 -38
  227. package/dist/core/item/status-filter.js +1 -115
  228. package/dist/core/item/status.js +1 -43
  229. package/dist/core/item/toon-decode.js +1 -29
  230. package/dist/core/item/type-registry.js +1 -715
  231. package/dist/core/item/type-synonyms.js +1 -38
  232. package/dist/core/lock/index.js +1 -9
  233. package/dist/core/lock/lock-gc.js +1 -240
  234. package/dist/core/lock/lock.js +3 -590
  235. package/dist/core/output/mutation-projection.js +1 -217
  236. package/dist/core/output/output-control.js +1 -25
  237. package/dist/core/output/output.js +11 -494
  238. package/dist/core/output/query-summary.js +1 -58
  239. package/dist/core/output/tabular.js +1 -77
  240. package/dist/core/packages/manifest.js +1 -244
  241. package/dist/core/packages/root.js +1 -84
  242. package/dist/core/policy/workflow-policy-schema.d.ts +312 -0
  243. package/dist/core/policy/workflow-policy-schema.js +2 -0
  244. package/dist/core/policy/workflow-policy-store.d.ts +24 -0
  245. package/dist/core/policy/workflow-policy-store.js +2 -0
  246. package/dist/core/policy/workflow-policy.d.ts +139 -0
  247. package/dist/core/policy/workflow-policy.js +2 -0
  248. package/dist/core/profile/profile-describe.js +1 -83
  249. package/dist/core/profile/profile-lint.js +1 -415
  250. package/dist/core/profile/profile-plan.js +0 -0
  251. package/dist/core/profile/profile-presets.js +1 -370
  252. package/dist/core/reproducibility/context.js +1 -82
  253. package/dist/core/schema/fields-file.js +2 -288
  254. package/dist/core/schema/item-types-file.js +2 -296
  255. package/dist/core/schema/runtime-field-filters.js +1 -49
  256. package/dist/core/schema/runtime-field-values.js +1 -313
  257. package/dist/core/schema/runtime-schema.js +2 -826
  258. package/dist/core/schema/status-defs-file.js +2 -227
  259. package/dist/core/schema/status-token.js +1 -31
  260. package/dist/core/schema/type-inference.js +1 -95
  261. package/dist/core/schema/type-presets.js +1 -87
  262. package/dist/core/schema/type-workflows.js +1 -104
  263. package/dist/core/search/background-refresh.js +2 -286
  264. package/dist/core/search/bm25.js +1 -146
  265. package/dist/core/search/cache.js +2 -534
  266. package/dist/core/search/corpus.js +1 -311
  267. package/dist/core/search/embedding-batches.js +1 -163
  268. package/dist/core/search/eval.js +1 -225
  269. package/dist/core/search/http-client.js +1 -75
  270. package/dist/core/search/providers.js +1 -242
  271. package/dist/core/search/relevance.js +1 -244
  272. package/dist/core/search/semantic-defaults.js +1 -199
  273. package/dist/core/search/staleness.js +1 -30
  274. package/dist/core/search/vector-stores.js +2 -664
  275. package/dist/core/search/vectorization-metadata.js +1 -81
  276. package/dist/core/sentry/helpers.js +1 -272
  277. package/dist/core/sentry/instrument.js +1 -387
  278. package/dist/core/session/session-state.js +1 -260
  279. package/dist/core/shared/agent-session-context.js +1 -133
  280. package/dist/core/shared/author.js +1 -1172
  281. package/dist/core/shared/command-types.js +1 -4
  282. package/dist/core/shared/conflict-markers.js +1 -31
  283. package/dist/core/shared/constants.js +1 -405
  284. package/dist/core/shared/errors.js +1 -20
  285. package/dist/core/shared/html-entity-decode.js +1 -131
  286. package/dist/core/shared/index.js +1 -12
  287. package/dist/core/shared/item-metadata-contract.js +1 -89
  288. package/dist/core/shared/lazy-module.js +1 -16
  289. package/dist/core/shared/levenshtein.js +1 -61
  290. package/dist/core/shared/memo.js +1 -19
  291. package/dist/core/shared/numeric-parsers.js +1 -20
  292. package/dist/core/shared/option-alias-visibility.js +1 -67
  293. package/dist/core/shared/primitives.js +1 -127
  294. package/dist/core/shared/serial-queue.js +1 -79
  295. package/dist/core/shared/serialization.js +1 -210
  296. package/dist/core/shared/split-comma-list.js +1 -30
  297. package/dist/core/shared/text-normalization.js +1 -38
  298. package/dist/core/shared/time.js +1 -306
  299. package/dist/core/store/index.js +1 -12
  300. package/dist/core/store/item-format-migration.js +1 -125
  301. package/dist/core/store/item-metadata-cache.js +1 -1116
  302. package/dist/core/store/item-metadata-query-index.js +9 -394
  303. package/dist/core/store/item-metadata-read-work.js +1 -43
  304. package/dist/core/store/item-store.js +1 -693
  305. package/dist/core/store/paths.d.ts +1 -1
  306. package/dist/core/store/paths.js +1 -214
  307. package/dist/core/store/settings-read-cache.js +1 -85
  308. package/dist/core/store/settings-validator.d.ts +1 -0
  309. package/dist/core/store/settings-validator.js +1 -421
  310. package/dist/core/store/settings.js +3 -1309
  311. package/dist/core/store/tracker-preflight.js +1 -141
  312. package/dist/core/telemetry/consent.js +5 -108
  313. package/dist/core/telemetry/observability.js +1 -246
  314. package/dist/core/telemetry/runtime.js +4 -1988
  315. package/dist/core/test/background-runs.js +4 -945
  316. package/dist/core/test/item-test-run-tracking.js +1 -63
  317. package/dist/core/test/run-selectors.js +1 -120
  318. package/dist/core/validate/estimate-defaults.js +1 -89
  319. package/dist/core/validate/fix-planning.js +1 -189
  320. package/dist/core/validate/linked-artifact-reference.js +1 -36
  321. package/dist/core/validate/missing-by-type.js +1 -34
  322. package/dist/core/validate/missing-link-owners.js +1 -95
  323. package/dist/core/validate/stale-file-classification.js +1 -82
  324. package/dist/mcp/http-server.js +5 -448
  325. package/dist/mcp/legacy-adapter.js +1 -77
  326. package/dist/mcp/runtime-capabilities.js +1 -200
  327. package/dist/mcp/server.js +4 -1233
  328. package/dist/mcp/tool-definitions.js +1 -804
  329. package/dist/sdk/actionability.js +1 -13
  330. package/dist/sdk/agent/closed-domain-contracts.js +1 -161
  331. package/dist/sdk/agent/command-recovery.js +1 -59
  332. package/dist/sdk/agent/command-suggestions.js +1 -66
  333. package/dist/sdk/agent/create-option-policy.js +1 -31
  334. package/dist/sdk/agent/identity-config.js +1 -106
  335. package/dist/sdk/agent/item-addressing.js +1 -207
  336. package/dist/sdk/agent/refusal-closure-census.js +1 -151
  337. package/dist/sdk/agent/refusal-closure.js +1 -133
  338. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
  339. package/dist/sdk/agent/refusal-reachability.js +1 -593
  340. package/dist/sdk/agent/subcommand-recovery.js +1 -83
  341. package/dist/sdk/agent/task-transcript-contracts.js +1 -197
  342. package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
  343. package/dist/sdk/agent-capability-contracts.js +1 -428
  344. package/dist/sdk/agent-session-context.js +1 -9
  345. package/dist/sdk/annotations.js +1 -448
  346. package/dist/sdk/author-attribution.js +1 -468
  347. package/dist/sdk/authoring.js +1 -20
  348. package/dist/sdk/cli-bootstrap.js +1 -838
  349. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
  350. package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
  351. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
  352. package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
  353. package/dist/sdk/cli-contracts/command-aliases.js +1 -107
  354. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
  355. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
  356. package/dist/sdk/cli-contracts/commander-types.js +1 -159
  357. package/dist/sdk/cli-contracts/completeness.js +1 -393
  358. package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
  359. package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
  360. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
  361. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
  362. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
  363. package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
  364. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
  365. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
  366. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
  367. package/dist/sdk/cli-contracts/string-lists.js +1 -16
  368. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
  369. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
  370. package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
  371. package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
  372. package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
  373. package/dist/sdk/cli-contracts.d.ts +1 -1
  374. package/dist/sdk/cli-contracts.js +1 -17
  375. package/dist/sdk/cli-program.js +1 -49
  376. package/dist/sdk/command-line.d.ts +2 -5
  377. package/dist/sdk/command-line.js +1 -78
  378. package/dist/sdk/comments.js +1 -133
  379. package/dist/sdk/compile-cache.js +1 -73
  380. package/dist/sdk/completion.js +174 -839
  381. package/dist/sdk/compose.js +1 -1090
  382. package/dist/sdk/config.js +1 -1204
  383. package/dist/sdk/context/recency.js +1 -33
  384. package/dist/sdk/context/semantic-session-attribution.js +1 -82
  385. package/dist/sdk/context/usage-egress.js +1 -29
  386. package/dist/sdk/context/usage-ledger.js +3 -185
  387. package/dist/sdk/context-intent-contracts.js +1 -709
  388. package/dist/sdk/context-intent-runtime.js +1 -115
  389. package/dist/sdk/context-packing.js +1 -218
  390. package/dist/sdk/context-relevance.js +1 -503
  391. package/dist/sdk/context-signal-store.js +2 -426
  392. package/dist/sdk/context-usage.js +1 -367
  393. package/dist/sdk/contracts.js +1 -23
  394. package/dist/sdk/core-governance.js +1 -14
  395. package/dist/sdk/core.js +1 -14
  396. package/dist/sdk/corpus-shape.js +1 -401
  397. package/dist/sdk/define.js +1 -220
  398. package/dist/sdk/dependencies.js +1 -718
  399. package/dist/sdk/dependency-flag-validation.js +1 -156
  400. package/dist/sdk/dependency-provenance.js +1 -135
  401. package/dist/sdk/docs.js +1 -14
  402. package/dist/sdk/duplicates.js +1 -40
  403. package/dist/sdk/environment/agent-environment.js +1 -466
  404. package/dist/sdk/environment/host-environment-errors.js +1 -8
  405. package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
  406. package/dist/sdk/environment/source-context.js +1 -28
  407. package/dist/sdk/environment/tracker-preflight.js +1 -9
  408. package/dist/sdk/error-code-catalog.js +1 -153
  409. package/dist/sdk/error-runtime.js +1 -58
  410. package/dist/sdk/errors.js +1 -58
  411. package/dist/sdk/eval.js +1 -190
  412. package/dist/sdk/extension/author-manifest.js +1 -92
  413. package/dist/sdk/extension/bundled-catalog.js +1 -332
  414. package/dist/sdk/extension/concurrency.js +1 -25
  415. package/dist/sdk/extension/copy-scope.d.ts +2 -0
  416. package/dist/sdk/extension/copy-scope.js +2 -0
  417. package/dist/sdk/extension/custom-field-collisions.js +1 -30
  418. package/dist/sdk/extension/describe.js +3 -189
  419. package/dist/sdk/extension/doctor.js +1 -606
  420. package/dist/sdk/extension/install-plan.d.ts +69 -0
  421. package/dist/sdk/extension/install-plan.js +2 -0
  422. package/dist/sdk/extension/install-receipts.d.ts +7 -0
  423. package/dist/sdk/extension/install-receipts.js +2 -0
  424. package/dist/sdk/extension/install-runtime.js +3 -313
  425. package/dist/sdk/extension/install-snapshot.js +1 -66
  426. package/dist/sdk/extension/install-sources.js +5 -1057
  427. package/dist/sdk/extension/managed-state.js +2 -252
  428. package/dist/sdk/extension/migrations.js +2 -174
  429. package/dist/sdk/extension/output-ownership.js +1 -25
  430. package/dist/sdk/extension/runtime-summary.js +1 -18
  431. package/dist/sdk/extension/scaffold.js +4 -2308
  432. package/dist/sdk/extension/shared.js +1 -147
  433. package/dist/sdk/extension/source-resolution.js +1 -65
  434. package/dist/sdk/extension/update-check.js +1 -67
  435. package/dist/sdk/extension-command-context.js +1 -44
  436. package/dist/sdk/extension-contracts.js +1 -73
  437. package/dist/sdk/extension.d.ts +7 -2
  438. package/dist/sdk/extension.js +1 -2196
  439. package/dist/sdk/files.js +1 -535
  440. package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
  441. package/dist/sdk/flag-invocation-contracts.js +1 -344
  442. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
  443. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
  444. package/dist/sdk/generated-error-code-catalog.js +1 -16
  445. package/dist/sdk/governance/assurance-action-contracts.js +1 -4
  446. package/dist/sdk/governance/assurance-action.js +1 -411
  447. package/dist/sdk/governance/assurance-limits.js +1 -10
  448. package/dist/sdk/governance/assurance-mutation-error.js +1 -81
  449. package/dist/sdk/governance/assurance-presets.js +1 -135
  450. package/dist/sdk/governance/assurance-runtime.js +1 -238
  451. package/dist/sdk/governance/assurance.js +4 -1182
  452. package/dist/sdk/governance/boundary-fixtures.js +1 -200
  453. package/dist/sdk/governance/coverage-assurance.js +1 -60
  454. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
  455. package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
  456. package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
  457. package/dist/sdk/governance/defect-recurrence.js +1 -623
  458. package/dist/sdk/governance/extension-host-version.js +1 -115
  459. package/dist/sdk/governance/gc.js +1 -368
  460. package/dist/sdk/governance/health.js +1 -2367
  461. package/dist/sdk/governance/hierarchy-validation.js +1 -108
  462. package/dist/sdk/governance/linked-file-report.js +1 -71
  463. package/dist/sdk/governance/merge-receipt-history.js +1 -206
  464. package/dist/sdk/governance/provenance-health.js +1 -282
  465. package/dist/sdk/governance/reindex.js +4 -761
  466. package/dist/sdk/governance/stale-work.js +1 -82
  467. package/dist/sdk/governance/status-role-diagnostics.js +1 -35
  468. package/dist/sdk/governance/storage-integrity.js +1 -280
  469. package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
  470. package/dist/sdk/governance/upgrade.js +2 -327
  471. package/dist/sdk/governance/validate-history-drift.js +1 -81
  472. package/dist/sdk/governance/validate-item-reader.js +1 -17
  473. package/dist/sdk/governance/validate-normalization.js +1 -36
  474. package/dist/sdk/governance/validate.d.ts +3 -1
  475. package/dist/sdk/governance/validate.js +1 -2261
  476. package/dist/sdk/governance/workflow-completeness.d.ts +32 -0
  477. package/dist/sdk/governance/workflow-completeness.js +2 -0
  478. package/dist/sdk/governance/workflow-policy.d.ts +47 -0
  479. package/dist/sdk/governance/workflow-policy.js +4 -0
  480. package/dist/sdk/governance/workspace-position.js +1 -163
  481. package/dist/sdk/governance.d.ts +2 -0
  482. package/dist/sdk/governance.js +1 -31
  483. package/dist/sdk/graph/adapter.js +1 -181
  484. package/dist/sdk/graph/analytics.js +1 -474
  485. package/dist/sdk/graph/assembly.js +1 -377
  486. package/dist/sdk/graph/cache.js +1 -160
  487. package/dist/sdk/graph/centrality.js +1 -258
  488. package/dist/sdk/graph/conformance.js +1 -130
  489. package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
  490. package/dist/sdk/graph/deadline-scheduling.js +2 -0
  491. package/dist/sdk/graph/durable-cache.d.ts +1 -1
  492. package/dist/sdk/graph/durable-cache.js +1 -361
  493. package/dist/sdk/graph/governance-contracts.js +1 -34
  494. package/dist/sdk/graph/governance.d.ts +13 -1
  495. package/dist/sdk/graph/governance.js +1 -735
  496. package/dist/sdk/graph/hierarchy-integrity.js +1 -310
  497. package/dist/sdk/graph/index.d.ts +3 -2
  498. package/dist/sdk/graph/index.js +1 -26
  499. package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
  500. package/dist/sdk/graph/lifecycle-coverage.js +2 -0
  501. package/dist/sdk/graph/mutation-advisory.js +1 -176
  502. package/dist/sdk/graph/remediation.js +1 -197
  503. package/dist/sdk/graph/run.d.ts +15 -1
  504. package/dist/sdk/graph/run.js +1 -768
  505. package/dist/sdk/graph/scheduling.js +1 -124
  506. package/dist/sdk/graph/traversal.js +1 -284
  507. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
  508. package/dist/sdk/graph.js +1 -15
  509. package/dist/sdk/guide-topics.js +1 -707
  510. package/dist/sdk/guide.js +1 -279
  511. package/dist/sdk/history/maintenance.d.ts +71 -0
  512. package/dist/sdk/history/maintenance.js +2 -0
  513. package/dist/sdk/history/salvage.js +2 -247
  514. package/dist/sdk/history/subject.d.ts +19 -0
  515. package/dist/sdk/history/subject.js +2 -0
  516. package/dist/sdk/history-analytics.js +1 -282
  517. package/dist/sdk/history-compact.js +1 -527
  518. package/dist/sdk/history-mcp.js +1 -68
  519. package/dist/sdk/history-provenance.js +1 -182
  520. package/dist/sdk/history-read.js +1 -96
  521. package/dist/sdk/history-redact.d.ts +1 -14
  522. package/dist/sdk/history-redact.js +1 -643
  523. package/dist/sdk/history-repair.d.ts +5 -0
  524. package/dist/sdk/history-repair.js +1 -657
  525. package/dist/sdk/improvement-ledger-validation.js +1 -62
  526. package/dist/sdk/improvement-ledger.js +2 -257
  527. package/dist/sdk/index.d.ts +4 -1
  528. package/dist/sdk/index.js +1 -183
  529. package/dist/sdk/init-agent-guidance.js +2 -496
  530. package/dist/sdk/init.js +2 -820
  531. package/dist/sdk/invocation-author.js +1 -39
  532. package/dist/sdk/item-children.js +1 -90
  533. package/dist/sdk/item-metadata-index.js +1 -15
  534. package/dist/sdk/item-schedule.js +1 -27
  535. package/dist/sdk/item-transaction.js +1 -396
  536. package/dist/sdk/learnings.js +1 -29
  537. package/dist/sdk/lifecycle/append.js +2 -53
  538. package/dist/sdk/lifecycle/claim.d.ts +2 -0
  539. package/dist/sdk/lifecycle/claim.js +1 -242
  540. package/dist/sdk/lifecycle/close-many.js +1 -438
  541. package/dist/sdk/lifecycle/close.js +1 -468
  542. package/dist/sdk/lifecycle/copy.js +1 -212
  543. package/dist/sdk/lifecycle/create.js +1 -1949
  544. package/dist/sdk/lifecycle/delete.js +1 -45
  545. package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
  546. package/dist/sdk/lifecycle/focus.js +1 -91
  547. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
  548. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
  549. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
  550. package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
  551. package/dist/sdk/lifecycle/mcp-actions.js +1 -51
  552. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
  553. package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
  554. package/dist/sdk/lifecycle/plan.js +1 -1606
  555. package/dist/sdk/lifecycle/recurrence-parsers.d.ts +1 -1
  556. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
  557. package/dist/sdk/lifecycle/reopen.js +1 -68
  558. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
  559. package/dist/sdk/lifecycle/restore.d.ts +1 -0
  560. package/dist/sdk/lifecycle/restore.js +1 -330
  561. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
  562. package/dist/sdk/lifecycle/update-many.js +1 -861
  563. package/dist/sdk/lifecycle/update.js +1 -2136
  564. package/dist/sdk/lifecycle-completion.js +1 -92
  565. package/dist/sdk/lifecycle-policy.js +1 -120
  566. package/dist/sdk/linked-artifacts.js +1 -530
  567. package/dist/sdk/mcp/apps.js +4 -133
  568. package/dist/sdk/mcp/authorization.js +1 -404
  569. package/dist/sdk/mcp/discovery.js +1 -494
  570. package/dist/sdk/mcp/interactions.js +1 -336
  571. package/dist/sdk/mcp/protocol.d.ts +7 -0
  572. package/dist/sdk/mcp/protocol.js +1 -184
  573. package/dist/sdk/mcp/skills.js +1 -389
  574. package/dist/sdk/mcp/subscriptions.js +1 -211
  575. package/dist/sdk/mcp/tasks.js +2 -430
  576. package/dist/sdk/mcp/transport.js +1 -260
  577. package/dist/sdk/merge/abandoned-receipts.js +1 -46
  578. package/dist/sdk/merge/driver.js +1 -212
  579. package/dist/sdk/merge/index.js +1 -16
  580. package/dist/sdk/merge/install.js +3 -561
  581. package/dist/sdk/merge/receipt-file-boundary.js +1 -46
  582. package/dist/sdk/merge/receipt-operation.js +1 -96
  583. package/dist/sdk/merge/receipt-schema.js +1 -397
  584. package/dist/sdk/merge/receipts.js +4 -525
  585. package/dist/sdk/merge/reconcile.js +1 -352
  586. package/dist/sdk/merge/three-way.js +3 -775
  587. package/dist/sdk/merge.js +1 -10
  588. package/dist/sdk/mutation-events.js +1 -292
  589. package/dist/sdk/mutation-guard.js +1 -216
  590. package/dist/sdk/notes.js +1 -139
  591. package/dist/sdk/output-contracts.js +1 -172
  592. package/dist/sdk/output-projection.js +1 -430
  593. package/dist/sdk/output-token-accounting.js +1 -140
  594. package/dist/sdk/output.js +1 -64
  595. package/dist/sdk/ownership-source.js +1 -21
  596. package/dist/sdk/package-import-adapters.js +1 -442
  597. package/dist/sdk/package-migrations.js +1 -20
  598. package/dist/sdk/package-runtime-options.js +1 -80
  599. package/dist/sdk/pagination.js +1 -162
  600. package/dist/sdk/profile.js +1 -454
  601. package/dist/sdk/provenance.js +1 -258
  602. package/dist/sdk/public-surface.json +1 -1
  603. package/dist/sdk/query/activity.js +1 -401
  604. package/dist/sdk/query/aggregate.d.ts +16 -0
  605. package/dist/sdk/query/aggregate.js +1 -390
  606. package/dist/sdk/query/calendar.js +1 -964
  607. package/dist/sdk/query/complete-list.js +1 -215
  608. package/dist/sdk/query/context.js +1 -1702
  609. package/dist/sdk/query/duplicate-candidates.js +1 -70
  610. package/dist/sdk/query/get.js +1 -450
  611. package/dist/sdk/query/history.js +1 -186
  612. package/dist/sdk/query/item-filter-options.js +1 -9
  613. package/dist/sdk/query/light-metadata.js +1 -18
  614. package/dist/sdk/query/list-filter-shared.js +1 -81
  615. package/dist/sdk/query/list.js +1 -1304
  616. package/dist/sdk/query/multi-value-filters.js +1 -78
  617. package/dist/sdk/query/next.js +1 -513
  618. package/dist/sdk/query/parsers.js +1 -44
  619. package/dist/sdk/query/projection-contracts.js +1 -184
  620. package/dist/sdk/query/search-contracts.d.ts +27 -0
  621. package/dist/sdk/query/search-contracts.js +1 -230
  622. package/dist/sdk/query/search-pagination.js +1 -35
  623. package/dist/sdk/query/search-rendering.js +1 -105
  624. package/dist/sdk/query/search.d.ts +6 -4
  625. package/dist/sdk/query/search.js +2 -1987
  626. package/dist/sdk/query.js +1 -35
  627. package/dist/sdk/read-output/continuation.js +1 -194
  628. package/dist/sdk/read-output-budget.js +1 -135
  629. package/dist/sdk/read-output-contracts.d.ts +1 -1
  630. package/dist/sdk/read-output-contracts.js +1 -1225
  631. package/dist/sdk/read-output-rows.js +1 -186
  632. package/dist/sdk/read-output-session.js +1 -208
  633. package/dist/sdk/relationship-analytics.js +1 -410
  634. package/dist/sdk/relationship-context.js +1 -284
  635. package/dist/sdk/relationship-history.js +4 -519
  636. package/dist/sdk/relationship-kinds/contract.js +1 -22
  637. package/dist/sdk/relationship-migration.js +1 -77
  638. package/dist/sdk/relationships.js +1 -579
  639. package/dist/sdk/reproducibility/process.js +1 -87
  640. package/dist/sdk/runtime-action-aliases.js +1 -59
  641. package/dist/sdk/runtime-extended-actions.js +1 -177
  642. package/dist/sdk/runtime-input.js +1 -614
  643. package/dist/sdk/runtime-primitives.js +1 -84
  644. package/dist/sdk/runtime-public-contracts.d.ts +2 -1
  645. package/dist/sdk/runtime-public-contracts.js +1 -4
  646. package/dist/sdk/runtime-stats-options.js +1 -38
  647. package/dist/sdk/runtime.d.ts +4 -0
  648. package/dist/sdk/runtime.js +1 -1928
  649. package/dist/sdk/scheduling-shortcuts.js +1 -63
  650. package/dist/sdk/schema-migration.js +3 -856
  651. package/dist/sdk/schema.d.ts +2 -1
  652. package/dist/sdk/schema.js +1 -1376
  653. package/dist/sdk/search-refresh-worker.js +1 -18
  654. package/dist/sdk/similarity-scoring.js +1 -53
  655. package/dist/sdk/similarity.js +1 -326
  656. package/dist/sdk/start-task-status.js +1 -14
  657. package/dist/sdk/stats.js +1 -270
  658. package/dist/sdk/structured-mutations.js +1 -580
  659. package/dist/sdk/telemetry-flush.js +1 -13
  660. package/dist/sdk/telemetry.js +1 -405
  661. package/dist/sdk/templates.js +2 -292
  662. package/dist/sdk/test/batch.js +2 -509
  663. package/dist/sdk/test/entry.js +1 -70
  664. package/dist/sdk/test/execution.js +6 -2211
  665. package/dist/sdk/test/linked-command-detection.js +1 -546
  666. package/dist/sdk/test/measurements.js +1 -91
  667. package/dist/sdk/test/parsers.js +1 -545
  668. package/dist/sdk/test/runs.js +1 -193
  669. package/dist/sdk/test/trust.js +2 -206
  670. package/dist/sdk/testing.js +4 -1391
  671. package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
  672. package/dist/sdk/traceability/source-traceability.js +1 -292
  673. package/dist/sdk/tracker-root-discovery.js +1 -9
  674. package/dist/sdk/workspace-contracts-cache.js +1 -28
  675. package/dist/sdk/workspace-contracts.js +1 -33
  676. package/dist/sdk/workspace-memory.js +2 -318
  677. package/dist/sdk/workspace-recipe.js +1 -71
  678. package/dist/sdk/workspace-snapshot.js +4 -613
  679. package/dist/sdk/workspace-transaction-gc.js +1 -149
  680. package/dist/sdk/workspace-transaction.js +2 -363
  681. package/dist/sdk/workspace.js +3 -127
  682. package/dist/types/index.js +1 -9
  683. package/dist/types.d.ts +4 -0
  684. package/dist/types.js +1 -245
  685. package/docs/AGENT_GUIDE.md +1 -1
  686. package/docs/COMMANDS.md +10 -0
  687. package/docs/CONFIGURATION.md +12 -1
  688. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
  689. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
  690. package/docs/EXTENSIONS.md +1 -0
  691. package/docs/HISTORY_MAINTENANCE.md +125 -0
  692. package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
  693. package/docs/PACKAGE_EVIDENCE.md +92 -0
  694. package/docs/PLANNING_MEASUREMENTS.md +183 -0
  695. package/docs/README.md +4 -0
  696. package/docs/READ_OUTPUT_CONTRACTS.md +5 -0
  697. package/docs/SCRIPTING.md +21 -0
  698. package/docs/TESTING.md +33 -0
  699. package/docs/WORKFLOW_POLICIES.md +129 -0
  700. package/docs/generated/FLAG_LEXICON_BUDGETS.md +7 -7
  701. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +11 -5
  702. package/marketplace.json +2 -2
  703. package/package.json +5 -5
  704. package/packages/pm-beads/package.json +1 -1
  705. package/packages/pm-calendar/package.json +1 -1
  706. package/packages/pm-command-kit/package.json +1 -1
  707. package/packages/pm-digital-twin/package.json +1 -1
  708. package/packages/pm-governance-audit/package.json +1 -1
  709. package/packages/pm-guide-shell/package.json +1 -1
  710. package/packages/pm-kanban/package.json +1 -1
  711. package/packages/pm-lifecycle-hooks/package.json +1 -1
  712. package/packages/pm-linked-test-adapters/package.json +1 -1
  713. package/packages/pm-search-advanced/package.json +1 -1
  714. package/packages/pm-templates/package.json +1 -1
  715. package/packages/pm-todos/package.json +1 -1
  716. package/packages/pm-vcs/package.json +1 -1
  717. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  718. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  719. package/scripts/finalize-build.mjs +45 -3
  720. package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
  721. package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
  722. package/dist/cli-bundle/chunks/chunk-JX4DH4WC.js +0 -3
  723. package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
  724. package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
  725. package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
  726. package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
  727. package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
  728. package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
  729. package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
  730. package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
  731. package/dist/cli-bundle/chunks/register-operations-I5W3KMGB.js +0 -2
  732. package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
  733. package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
  734. package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
  735. package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
  736. package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
  737. package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
  738. package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
  739. package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
  740. package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
  741. package/dist/cli-bundle/focused-chunks/chunk-PEFABF7E.js +0 -26
  742. package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
  743. package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
  744. package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
  745. package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
  746. 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