@unbrained/pm-cli 2026.9.7 → 2026.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (718) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +12 -4
  2. package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +19 -10
  3. package/.agents/skills/pm-extensions/SKILL.md +6 -0
  4. package/.agents/skills/pm-sdk/SKILL.md +11 -2
  5. package/.agents/skills/pm-user/SKILL.md +5 -0
  6. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
  7. package/.claude-plugin/marketplace.json +2 -2
  8. package/CHANGELOG.md +211 -181
  9. package/dist/cli/after-command-context-usage.js +1 -48
  10. package/dist/cli/argv-utils.js +1 -40
  11. package/dist/cli/bootstrap-args.js +1 -9
  12. package/dist/cli/bundle-integrity.js +2 -110
  13. package/dist/cli/commander-usage.js +11 -771
  14. package/dist/cli/commands/activity.js +1 -9
  15. package/dist/cli/commands/aggregate.js +1 -5
  16. package/dist/cli/commands/append.js +1 -5
  17. package/dist/cli/commands/claim.js +1 -5
  18. package/dist/cli/commands/close-many.js +1 -5
  19. package/dist/cli/commands/close.js +1 -9
  20. package/dist/cli/commands/comments.js +1 -5
  21. package/dist/cli/commands/config.js +1 -9
  22. package/dist/cli/commands/context.js +1 -9
  23. package/dist/cli/commands/contracts.js +1 -5
  24. package/dist/cli/commands/copy.js +1 -9
  25. package/dist/cli/commands/create.js +1 -9
  26. package/dist/cli/commands/delete.js +1 -9
  27. package/dist/cli/commands/deps.js +1 -9
  28. package/dist/cli/commands/docs.js +1 -9
  29. package/dist/cli/commands/duplicates.js +1 -9
  30. package/dist/cli/commands/eval.js +1 -9
  31. package/dist/cli/commands/extension/describe.js +1 -5
  32. package/dist/cli/commands/extension/scaffold.js +1 -5
  33. package/dist/cli/commands/extension/shared.js +1 -5
  34. package/dist/cli/commands/extension.js +1 -9
  35. package/dist/cli/commands/files.js +1 -9
  36. package/dist/cli/commands/focus.js +1 -9
  37. package/dist/cli/commands/gc.js +1 -9
  38. package/dist/cli/commands/get.js +1 -9
  39. package/dist/cli/commands/graph.js +1 -10
  40. package/dist/cli/commands/health.js +1 -9
  41. package/dist/cli/commands/history-compact.js +1 -10
  42. package/dist/cli/commands/history-redact.js +1 -11
  43. package/dist/cli/commands/history-repair.js +1 -10
  44. package/dist/cli/commands/history.js +1 -5
  45. package/dist/cli/commands/index.js +1 -58
  46. package/dist/cli/commands/init-agent-guidance.js +1 -9
  47. package/dist/cli/commands/init.js +1 -9
  48. package/dist/cli/commands/learnings.js +1 -5
  49. package/dist/cli/commands/lifecycle-transitions.js +1 -5
  50. package/dist/cli/commands/list.js +1 -9
  51. package/dist/cli/commands/merge.js +1 -11
  52. package/dist/cli/commands/next.js +1 -9
  53. package/dist/cli/commands/notes.js +1 -5
  54. package/dist/cli/commands/plan.js +1 -9
  55. package/dist/cli/commands/profile.js +1 -9
  56. package/dist/cli/commands/restore.js +1 -9
  57. package/dist/cli/commands/scheduling-shortcuts.js +1 -9
  58. package/dist/cli/commands/schema.js +1 -10
  59. package/dist/cli/commands/search.js +1 -9
  60. package/dist/cli/commands/stats.js +1 -9
  61. package/dist/cli/commands/telemetry.js +1 -9
  62. package/dist/cli/commands/test-all.js +1 -9
  63. package/dist/cli/commands/test-runs.js +1 -9
  64. package/dist/cli/commands/test.js +1 -9
  65. package/dist/cli/commands/update-many.js +1 -5
  66. package/dist/cli/commands/update.js +1 -9
  67. package/dist/cli/commands/upgrade.js +1 -5
  68. package/dist/cli/commands/validate.js +1 -15
  69. package/dist/cli/context-intent-invocation.js +1 -20
  70. package/dist/cli/description-stdin.js +1 -17
  71. package/dist/cli/error-guidance.js +1 -1353
  72. package/dist/cli/extension-command-help.js +5 -636
  73. package/dist/cli/extension-command-options.js +1 -427
  74. package/dist/cli/extension-recovery.js +1 -126
  75. package/dist/cli/help-content.js +2 -1001
  76. package/dist/cli/help-json-payload.js +4 -570
  77. package/dist/cli/main.d.ts +4 -0
  78. package/dist/cli/main.js +5 -2573
  79. package/dist/cli/migration-gates.js +1 -289
  80. package/dist/cli/public.js +1 -20
  81. package/dist/cli/register-annotations.js +1 -270
  82. package/dist/cli/register-assurance.js +1 -62
  83. package/dist/cli/register-files-lookup.js +1 -56
  84. package/dist/cli/register-history-activity.d.ts +8 -0
  85. package/dist/cli/register-history-activity.js +2 -0
  86. package/dist/cli/register-history-author.js +1 -38
  87. package/dist/cli/register-history-maintenance.d.ts +9 -0
  88. package/dist/cli/register-history-maintenance.js +2 -0
  89. package/dist/cli/register-list-query.js +10 -943
  90. package/dist/cli/register-mutation-options.js +1 -9
  91. package/dist/cli/register-mutation.js +19 -1893
  92. package/dist/cli/register-operations.js +1 -920
  93. package/dist/cli/register-setup.js +1 -716
  94. package/dist/cli/register-structured-mutation.js +1 -196
  95. package/dist/cli/registration-helpers.js +1 -5
  96. package/dist/cli/runtime-compatibility-boundary.js +4 -42
  97. package/dist/cli/schema-registration-helpers.js +1 -73
  98. package/dist/cli/search-refresh.js +1 -13
  99. package/dist/cli/stats-analytics-json.js +1 -68
  100. package/dist/cli/telemetry-flush.js +1 -10
  101. package/dist/cli-bundle/bundle-manifest.json +164 -156
  102. package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +5 -0
  103. package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +235 -0
  104. package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +2202 -0
  105. package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
  106. package/dist/cli-bundle/chunks/chunk-FLDWYEND.js +77 -0
  107. package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-G5ADGQ2D.js} +3 -3
  108. package/dist/cli-bundle/chunks/chunk-JAAEYHUA.js +2 -0
  109. package/dist/cli-bundle/chunks/{chunk-JX4DH4WC.js → chunk-KR3RP4FH.js} +3 -3
  110. package/dist/cli-bundle/chunks/chunk-LEZOUXG6.js +2 -0
  111. package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
  112. package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +29 -0
  113. package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +2 -0
  114. package/dist/cli-bundle/chunks/chunk-XOD2PCB6.js +20 -0
  115. package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-YVEQ2AMO.js} +4 -4
  116. package/dist/cli-bundle/chunks/register-list-query-KSK3R63M.js +11 -0
  117. package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +20 -0
  118. package/dist/cli-bundle/chunks/{register-operations-I5W3KMGB.js → register-operations-DWVHR2NC.js} +2 -2
  119. package/dist/cli-bundle/chunks/register-setup-BQ5SVD4B.js +2 -0
  120. package/dist/cli-bundle/focused-chunks/chunk-3WRPWLA7.js +3 -0
  121. package/dist/cli-bundle/focused-chunks/chunk-7MBUII7U.js +2 -0
  122. package/dist/cli-bundle/focused-chunks/chunk-COPBO5HW.js +8 -0
  123. package/dist/cli-bundle/focused-chunks/chunk-DUN4IXYN.js +20 -0
  124. package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-EE5QSM4Z.js} +3 -3
  125. package/dist/cli-bundle/focused-chunks/chunk-HJVARYM3.js +6 -0
  126. package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +177 -0
  127. package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +2 -0
  128. package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +56 -0
  129. package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-OPFHFGDD.js} +2 -2
  130. package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +9 -0
  131. package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-RMWES4M6.js} +2 -2
  132. package/dist/cli-bundle/focused-chunks/chunk-RXT4P5QH.js +10 -0
  133. package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +12 -0
  134. package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +2 -0
  135. package/dist/cli-bundle/focused-chunks/{chunk-PEFABF7E.js → chunk-WE3IUNIW.js} +3 -3
  136. package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +2 -0
  137. package/dist/cli-bundle/main.js +20 -20
  138. package/dist/cli-bundle/sdk-authoring.js +1 -1
  139. package/dist/cli-bundle/sdk-contracts.js +2 -2
  140. package/dist/cli-bundle/sdk-core.js +29 -29
  141. package/dist/cli-bundle/sdk-governance.js +1 -1
  142. package/dist/cli-bundle/sdk-graph.js +1 -1
  143. package/dist/cli-bundle/sdk-merge.js +42 -42
  144. package/dist/cli-bundle/sdk-query.js +1 -1
  145. package/dist/cli-bundle/sdk-runtime.js +1 -1
  146. package/dist/cli-bundle/sdk-testing.js +1 -1
  147. package/dist/cli-bundle/sdk.js +11 -11
  148. package/dist/cli.js +1 -104
  149. package/dist/core/checkpoint/checkpoint-gc.js +1 -169
  150. package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
  151. package/dist/core/config/nested-settings.js +1 -534
  152. package/dist/core/config/positional-value.js +1 -109
  153. package/dist/core/diagnostics/remediation.js +1 -506
  154. package/dist/core/extensions/activation-summary-markdown.js +2 -145
  155. package/dist/core/extensions/activation-summary.js +1 -92
  156. package/dist/core/extensions/activation-transaction.js +1 -46
  157. package/dist/core/extensions/capability-usage.js +1 -173
  158. package/dist/core/extensions/command-hook-context.js +1 -13
  159. package/dist/core/extensions/command-metadata-contract.js +1 -22
  160. package/dist/core/extensions/command-visibility-tier.js +1 -29
  161. package/dist/core/extensions/contribution-inventory.js +1 -173
  162. package/dist/core/extensions/exporter-output-contract.js +1 -66
  163. package/dist/core/extensions/extension-candidate.js +1 -18
  164. package/dist/core/extensions/extension-capability-aliases.js +1 -158
  165. package/dist/core/extensions/extension-hook-runtime.js +1 -699
  166. package/dist/core/extensions/extension-policy.js +1 -599
  167. package/dist/core/extensions/extension-registries.js +1 -62
  168. package/dist/core/extensions/extension-runtime-helpers.js +1 -33
  169. package/dist/core/extensions/extension-types.js +1 -102
  170. package/dist/core/extensions/flag-definition-validation.js +1 -52
  171. package/dist/core/extensions/flag-value-types.js +1 -64
  172. package/dist/core/extensions/index.js +1 -526
  173. package/dist/core/extensions/item-field-types.js +1 -39
  174. package/dist/core/extensions/item-fields.js +1 -261
  175. package/dist/core/extensions/loader.js +1 -2223
  176. package/dist/core/extensions/manifest-schema.js +1 -69
  177. package/dist/core/extensions/module-graph-snapshot.js +1 -33
  178. package/dist/core/extensions/preflight-ownership.js +1 -41
  179. package/dist/core/extensions/registration-validation.js +1 -82
  180. package/dist/core/extensions/registration-values.js +1 -209
  181. package/dist/core/extensions/reserved-host-flags.js +1 -36
  182. package/dist/core/extensions/runtime-registrations.js +1 -67
  183. package/dist/core/extensions/service-ownership.js +1 -19
  184. package/dist/core/extensions/version-compat.js +1 -216
  185. package/dist/core/fs/fs-utils.js +2 -158
  186. package/dist/core/fs/host-environment-errors.js +1 -141
  187. package/dist/core/fs/index.js +1 -9
  188. package/dist/core/fs/path-utils.js +1 -17
  189. package/dist/core/governance/content-fields.js +1 -160
  190. package/dist/core/governance/issue-codes.js +1 -151
  191. package/dist/core/governance/metadata-coverage.js +1 -358
  192. package/dist/core/history/drift-cache.js +3 -72
  193. package/dist/core/history/drift-scan.js +1 -342
  194. package/dist/core/history/event-classification.js +1 -109
  195. package/dist/core/history/event-index.js +8 -784
  196. package/dist/core/history/history-compact-bulk.js +1 -104
  197. package/dist/core/history/history-diff.js +1 -158
  198. package/dist/core/history/history-rewrite.d.ts +6 -1
  199. package/dist/core/history/history-rewrite.js +1 -107
  200. package/dist/core/history/history-storage-stats.js +1 -102
  201. package/dist/core/history/history-stream-policy.js +1 -62
  202. package/dist/core/history/history.js +2 -617
  203. package/dist/core/history/identity.js +1 -30
  204. package/dist/core/history/index.js +1 -9
  205. package/dist/core/history/projection.js +1 -196
  206. package/dist/core/history/read.d.ts +9 -0
  207. package/dist/core/history/read.js +1 -57
  208. package/dist/core/history/replay.js +2 -439
  209. package/dist/core/history/version-address.js +1 -32
  210. package/dist/core/history/workspace-history.js +2 -433
  211. package/dist/core/io/body-file.js +1 -62
  212. package/dist/core/io/bulk-ids-input.js +1 -112
  213. package/dist/core/item/actionability.js +1 -327
  214. package/dist/core/item/dependency-reference.js +1 -20
  215. package/dist/core/item/id.js +1 -112
  216. package/dist/core/item/index.js +1 -12
  217. package/dist/core/item/item-format-version.js +1 -78
  218. package/dist/core/item/item-format.js +5 -1473
  219. package/dist/core/item/item-record.js +1 -23
  220. package/dist/core/item/item-type-definition.js +1 -133
  221. package/dist/core/item/parent-reference-policy.js +1 -57
  222. package/dist/core/item/parse.js +2 -603
  223. package/dist/core/item/plan-lifecycle.js +1 -19
  224. package/dist/core/item/priority.js +1 -61
  225. package/dist/core/item/sprint-release-format.js +1 -38
  226. package/dist/core/item/status-filter.js +1 -115
  227. package/dist/core/item/status.js +1 -43
  228. package/dist/core/item/toon-decode.js +1 -29
  229. package/dist/core/item/type-registry.js +1 -715
  230. package/dist/core/item/type-synonyms.js +1 -38
  231. package/dist/core/lock/index.js +1 -9
  232. package/dist/core/lock/lock-gc.js +1 -240
  233. package/dist/core/lock/lock.js +3 -590
  234. package/dist/core/output/mutation-projection.js +1 -217
  235. package/dist/core/output/output-control.js +1 -25
  236. package/dist/core/output/output.js +11 -494
  237. package/dist/core/output/query-summary.js +1 -58
  238. package/dist/core/output/tabular.js +1 -77
  239. package/dist/core/packages/manifest.js +1 -244
  240. package/dist/core/packages/root.js +1 -84
  241. package/dist/core/profile/profile-describe.js +1 -83
  242. package/dist/core/profile/profile-lint.js +1 -415
  243. package/dist/core/profile/profile-plan.js +0 -0
  244. package/dist/core/profile/profile-presets.js +1 -370
  245. package/dist/core/reproducibility/context.js +1 -82
  246. package/dist/core/schema/fields-file.js +2 -288
  247. package/dist/core/schema/item-types-file.js +2 -296
  248. package/dist/core/schema/runtime-field-filters.js +1 -49
  249. package/dist/core/schema/runtime-field-values.js +1 -313
  250. package/dist/core/schema/runtime-schema.js +2 -826
  251. package/dist/core/schema/status-defs-file.js +2 -227
  252. package/dist/core/schema/status-token.js +1 -31
  253. package/dist/core/schema/type-inference.js +1 -95
  254. package/dist/core/schema/type-presets.js +1 -87
  255. package/dist/core/schema/type-workflows.js +1 -104
  256. package/dist/core/search/background-refresh.js +2 -286
  257. package/dist/core/search/bm25.js +1 -146
  258. package/dist/core/search/cache.js +2 -534
  259. package/dist/core/search/corpus.js +1 -311
  260. package/dist/core/search/embedding-batches.js +1 -163
  261. package/dist/core/search/eval.js +1 -225
  262. package/dist/core/search/http-client.js +1 -75
  263. package/dist/core/search/providers.js +1 -242
  264. package/dist/core/search/relevance.js +1 -244
  265. package/dist/core/search/semantic-defaults.js +1 -199
  266. package/dist/core/search/staleness.js +1 -30
  267. package/dist/core/search/vector-stores.js +2 -664
  268. package/dist/core/search/vectorization-metadata.js +1 -81
  269. package/dist/core/sentry/helpers.js +1 -272
  270. package/dist/core/sentry/instrument.js +1 -387
  271. package/dist/core/session/session-state.js +1 -260
  272. package/dist/core/shared/agent-session-context.js +1 -133
  273. package/dist/core/shared/author.js +1 -1172
  274. package/dist/core/shared/command-types.js +1 -4
  275. package/dist/core/shared/conflict-markers.js +1 -31
  276. package/dist/core/shared/constants.js +1 -405
  277. package/dist/core/shared/errors.js +1 -20
  278. package/dist/core/shared/html-entity-decode.js +1 -131
  279. package/dist/core/shared/index.js +1 -12
  280. package/dist/core/shared/item-metadata-contract.js +1 -89
  281. package/dist/core/shared/lazy-module.js +1 -16
  282. package/dist/core/shared/levenshtein.js +1 -61
  283. package/dist/core/shared/memo.js +1 -19
  284. package/dist/core/shared/numeric-parsers.js +1 -20
  285. package/dist/core/shared/option-alias-visibility.js +1 -67
  286. package/dist/core/shared/primitives.js +1 -127
  287. package/dist/core/shared/serial-queue.js +1 -79
  288. package/dist/core/shared/serialization.js +1 -210
  289. package/dist/core/shared/split-comma-list.js +1 -30
  290. package/dist/core/shared/text-normalization.js +1 -38
  291. package/dist/core/shared/time.js +1 -306
  292. package/dist/core/store/index.js +1 -12
  293. package/dist/core/store/item-format-migration.js +1 -125
  294. package/dist/core/store/item-metadata-cache.js +1 -1116
  295. package/dist/core/store/item-metadata-query-index.js +9 -394
  296. package/dist/core/store/item-metadata-read-work.js +1 -43
  297. package/dist/core/store/item-store.js +1 -693
  298. package/dist/core/store/paths.d.ts +1 -1
  299. package/dist/core/store/paths.js +1 -214
  300. package/dist/core/store/settings-read-cache.js +1 -85
  301. package/dist/core/store/settings-validator.js +1 -421
  302. package/dist/core/store/settings.js +3 -1309
  303. package/dist/core/store/tracker-preflight.js +1 -141
  304. package/dist/core/telemetry/consent.js +5 -108
  305. package/dist/core/telemetry/observability.js +1 -246
  306. package/dist/core/telemetry/runtime.js +4 -1988
  307. package/dist/core/test/background-runs.js +4 -945
  308. package/dist/core/test/item-test-run-tracking.js +1 -63
  309. package/dist/core/test/run-selectors.js +1 -120
  310. package/dist/core/validate/estimate-defaults.js +1 -89
  311. package/dist/core/validate/fix-planning.js +1 -189
  312. package/dist/core/validate/linked-artifact-reference.js +1 -36
  313. package/dist/core/validate/missing-by-type.js +1 -34
  314. package/dist/core/validate/missing-link-owners.js +1 -95
  315. package/dist/core/validate/stale-file-classification.js +1 -82
  316. package/dist/mcp/http-server.js +5 -448
  317. package/dist/mcp/legacy-adapter.js +1 -77
  318. package/dist/mcp/runtime-capabilities.js +1 -200
  319. package/dist/mcp/server.js +4 -1233
  320. package/dist/mcp/tool-definitions.js +1 -804
  321. package/dist/sdk/actionability.js +1 -13
  322. package/dist/sdk/agent/closed-domain-contracts.js +1 -161
  323. package/dist/sdk/agent/command-recovery.js +1 -59
  324. package/dist/sdk/agent/command-suggestions.js +1 -66
  325. package/dist/sdk/agent/create-option-policy.js +1 -31
  326. package/dist/sdk/agent/identity-config.js +1 -106
  327. package/dist/sdk/agent/item-addressing.js +1 -207
  328. package/dist/sdk/agent/refusal-closure-census.js +1 -151
  329. package/dist/sdk/agent/refusal-closure.js +1 -133
  330. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
  331. package/dist/sdk/agent/refusal-reachability.js +1 -593
  332. package/dist/sdk/agent/subcommand-recovery.js +1 -83
  333. package/dist/sdk/agent/task-transcript-contracts.js +1 -197
  334. package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
  335. package/dist/sdk/agent-capability-contracts.js +1 -428
  336. package/dist/sdk/agent-session-context.js +1 -9
  337. package/dist/sdk/annotations.js +1 -448
  338. package/dist/sdk/author-attribution.js +1 -468
  339. package/dist/sdk/authoring.js +1 -20
  340. package/dist/sdk/cli-bootstrap.js +1 -838
  341. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
  342. package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
  343. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
  344. package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
  345. package/dist/sdk/cli-contracts/command-aliases.js +1 -107
  346. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
  347. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
  348. package/dist/sdk/cli-contracts/commander-types.js +1 -159
  349. package/dist/sdk/cli-contracts/completeness.js +1 -393
  350. package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
  351. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
  352. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
  353. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
  354. package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
  355. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
  356. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
  357. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
  358. package/dist/sdk/cli-contracts/string-lists.js +1 -16
  359. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
  360. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
  361. package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
  362. package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
  363. package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
  364. package/dist/sdk/cli-contracts.d.ts +1 -1
  365. package/dist/sdk/cli-contracts.js +1 -17
  366. package/dist/sdk/cli-program.js +1 -49
  367. package/dist/sdk/command-line.d.ts +2 -5
  368. package/dist/sdk/command-line.js +1 -78
  369. package/dist/sdk/comments.js +1 -133
  370. package/dist/sdk/compile-cache.js +1 -73
  371. package/dist/sdk/completion.js +157 -837
  372. package/dist/sdk/compose.js +1 -1090
  373. package/dist/sdk/config.js +1 -1204
  374. package/dist/sdk/context/recency.js +1 -33
  375. package/dist/sdk/context/semantic-session-attribution.js +1 -82
  376. package/dist/sdk/context/usage-egress.js +1 -29
  377. package/dist/sdk/context/usage-ledger.js +3 -185
  378. package/dist/sdk/context-intent-contracts.js +1 -709
  379. package/dist/sdk/context-intent-runtime.js +1 -115
  380. package/dist/sdk/context-packing.js +1 -218
  381. package/dist/sdk/context-relevance.js +1 -503
  382. package/dist/sdk/context-signal-store.js +2 -426
  383. package/dist/sdk/context-usage.js +1 -367
  384. package/dist/sdk/contracts.js +1 -23
  385. package/dist/sdk/core-governance.js +1 -14
  386. package/dist/sdk/core.js +1 -14
  387. package/dist/sdk/corpus-shape.js +1 -401
  388. package/dist/sdk/define.js +1 -220
  389. package/dist/sdk/dependencies.js +1 -718
  390. package/dist/sdk/dependency-flag-validation.js +1 -156
  391. package/dist/sdk/dependency-provenance.js +1 -135
  392. package/dist/sdk/docs.js +1 -14
  393. package/dist/sdk/duplicates.js +1 -40
  394. package/dist/sdk/environment/agent-environment.js +1 -466
  395. package/dist/sdk/environment/host-environment-errors.js +1 -8
  396. package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
  397. package/dist/sdk/environment/source-context.js +1 -28
  398. package/dist/sdk/environment/tracker-preflight.js +1 -9
  399. package/dist/sdk/error-code-catalog.js +1 -153
  400. package/dist/sdk/error-runtime.js +1 -58
  401. package/dist/sdk/errors.js +1 -58
  402. package/dist/sdk/eval.js +1 -190
  403. package/dist/sdk/extension/author-manifest.js +1 -92
  404. package/dist/sdk/extension/bundled-catalog.js +1 -332
  405. package/dist/sdk/extension/concurrency.js +1 -25
  406. package/dist/sdk/extension/copy-scope.d.ts +2 -0
  407. package/dist/sdk/extension/copy-scope.js +2 -0
  408. package/dist/sdk/extension/custom-field-collisions.js +1 -30
  409. package/dist/sdk/extension/describe.js +3 -189
  410. package/dist/sdk/extension/doctor.js +1 -606
  411. package/dist/sdk/extension/install-plan.d.ts +69 -0
  412. package/dist/sdk/extension/install-plan.js +2 -0
  413. package/dist/sdk/extension/install-receipts.d.ts +7 -0
  414. package/dist/sdk/extension/install-receipts.js +2 -0
  415. package/dist/sdk/extension/install-runtime.js +3 -313
  416. package/dist/sdk/extension/install-snapshot.js +1 -66
  417. package/dist/sdk/extension/install-sources.js +5 -1057
  418. package/dist/sdk/extension/managed-state.js +2 -252
  419. package/dist/sdk/extension/migrations.js +2 -174
  420. package/dist/sdk/extension/output-ownership.js +1 -25
  421. package/dist/sdk/extension/runtime-summary.js +1 -18
  422. package/dist/sdk/extension/scaffold.js +4 -2308
  423. package/dist/sdk/extension/shared.js +1 -147
  424. package/dist/sdk/extension/source-resolution.js +1 -65
  425. package/dist/sdk/extension/update-check.js +1 -67
  426. package/dist/sdk/extension-command-context.js +1 -44
  427. package/dist/sdk/extension-contracts.js +1 -73
  428. package/dist/sdk/extension.d.ts +7 -2
  429. package/dist/sdk/extension.js +1 -2196
  430. package/dist/sdk/files.js +1 -535
  431. package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
  432. package/dist/sdk/flag-invocation-contracts.js +1 -344
  433. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
  434. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
  435. package/dist/sdk/generated-error-code-catalog.js +1 -16
  436. package/dist/sdk/governance/assurance-action-contracts.js +1 -4
  437. package/dist/sdk/governance/assurance-action.js +1 -411
  438. package/dist/sdk/governance/assurance-limits.js +1 -10
  439. package/dist/sdk/governance/assurance-mutation-error.js +1 -81
  440. package/dist/sdk/governance/assurance-presets.js +1 -135
  441. package/dist/sdk/governance/assurance-runtime.js +1 -238
  442. package/dist/sdk/governance/assurance.js +4 -1182
  443. package/dist/sdk/governance/boundary-fixtures.js +1 -200
  444. package/dist/sdk/governance/coverage-assurance.js +1 -60
  445. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
  446. package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
  447. package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
  448. package/dist/sdk/governance/defect-recurrence.js +1 -623
  449. package/dist/sdk/governance/extension-host-version.js +1 -115
  450. package/dist/sdk/governance/gc.js +1 -368
  451. package/dist/sdk/governance/health.js +1 -2367
  452. package/dist/sdk/governance/hierarchy-validation.js +1 -108
  453. package/dist/sdk/governance/linked-file-report.js +1 -71
  454. package/dist/sdk/governance/merge-receipt-history.js +1 -206
  455. package/dist/sdk/governance/provenance-health.js +1 -282
  456. package/dist/sdk/governance/reindex.js +4 -761
  457. package/dist/sdk/governance/stale-work.js +1 -82
  458. package/dist/sdk/governance/status-role-diagnostics.js +1 -35
  459. package/dist/sdk/governance/storage-integrity.js +1 -280
  460. package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
  461. package/dist/sdk/governance/upgrade.js +2 -327
  462. package/dist/sdk/governance/validate-history-drift.js +1 -81
  463. package/dist/sdk/governance/validate-item-reader.js +1 -17
  464. package/dist/sdk/governance/validate-normalization.js +1 -36
  465. package/dist/sdk/governance/validate.js +1 -2261
  466. package/dist/sdk/governance/workspace-position.js +1 -163
  467. package/dist/sdk/governance.d.ts +1 -0
  468. package/dist/sdk/governance.js +1 -31
  469. package/dist/sdk/graph/adapter.js +1 -181
  470. package/dist/sdk/graph/analytics.js +1 -474
  471. package/dist/sdk/graph/assembly.js +1 -377
  472. package/dist/sdk/graph/cache.js +1 -160
  473. package/dist/sdk/graph/centrality.js +1 -258
  474. package/dist/sdk/graph/conformance.js +1 -130
  475. package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
  476. package/dist/sdk/graph/deadline-scheduling.js +2 -0
  477. package/dist/sdk/graph/durable-cache.d.ts +1 -1
  478. package/dist/sdk/graph/durable-cache.js +1 -361
  479. package/dist/sdk/graph/governance-contracts.js +1 -34
  480. package/dist/sdk/graph/governance.d.ts +13 -1
  481. package/dist/sdk/graph/governance.js +1 -735
  482. package/dist/sdk/graph/hierarchy-integrity.js +1 -310
  483. package/dist/sdk/graph/index.d.ts +3 -2
  484. package/dist/sdk/graph/index.js +1 -26
  485. package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
  486. package/dist/sdk/graph/lifecycle-coverage.js +2 -0
  487. package/dist/sdk/graph/mutation-advisory.js +1 -176
  488. package/dist/sdk/graph/remediation.js +1 -197
  489. package/dist/sdk/graph/run.d.ts +15 -1
  490. package/dist/sdk/graph/run.js +1 -768
  491. package/dist/sdk/graph/scheduling.js +1 -124
  492. package/dist/sdk/graph/traversal.js +1 -284
  493. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
  494. package/dist/sdk/graph.js +1 -15
  495. package/dist/sdk/guide-topics.js +1 -707
  496. package/dist/sdk/guide.js +1 -279
  497. package/dist/sdk/history/maintenance.d.ts +71 -0
  498. package/dist/sdk/history/maintenance.js +2 -0
  499. package/dist/sdk/history/salvage.js +2 -247
  500. package/dist/sdk/history/subject.d.ts +19 -0
  501. package/dist/sdk/history/subject.js +2 -0
  502. package/dist/sdk/history-analytics.js +1 -282
  503. package/dist/sdk/history-compact.js +1 -527
  504. package/dist/sdk/history-mcp.js +1 -68
  505. package/dist/sdk/history-provenance.js +1 -182
  506. package/dist/sdk/history-read.js +1 -96
  507. package/dist/sdk/history-redact.d.ts +1 -14
  508. package/dist/sdk/history-redact.js +1 -643
  509. package/dist/sdk/history-repair.d.ts +5 -0
  510. package/dist/sdk/history-repair.js +1 -657
  511. package/dist/sdk/improvement-ledger-validation.js +1 -62
  512. package/dist/sdk/improvement-ledger.js +2 -257
  513. package/dist/sdk/index.d.ts +4 -0
  514. package/dist/sdk/index.js +1 -183
  515. package/dist/sdk/init-agent-guidance.js +2 -496
  516. package/dist/sdk/init.js +2 -820
  517. package/dist/sdk/invocation-author.js +1 -39
  518. package/dist/sdk/item-children.js +1 -90
  519. package/dist/sdk/item-metadata-index.js +1 -15
  520. package/dist/sdk/item-schedule.js +1 -27
  521. package/dist/sdk/item-transaction.js +1 -396
  522. package/dist/sdk/learnings.js +1 -29
  523. package/dist/sdk/lifecycle/append.js +2 -53
  524. package/dist/sdk/lifecycle/claim.d.ts +2 -0
  525. package/dist/sdk/lifecycle/claim.js +1 -242
  526. package/dist/sdk/lifecycle/close-many.js +1 -438
  527. package/dist/sdk/lifecycle/close.js +1 -468
  528. package/dist/sdk/lifecycle/copy.js +1 -212
  529. package/dist/sdk/lifecycle/create.js +1 -1949
  530. package/dist/sdk/lifecycle/delete.js +1 -45
  531. package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
  532. package/dist/sdk/lifecycle/focus.js +1 -91
  533. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
  534. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
  535. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
  536. package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
  537. package/dist/sdk/lifecycle/mcp-actions.js +1 -51
  538. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
  539. package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
  540. package/dist/sdk/lifecycle/plan.js +1 -1606
  541. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
  542. package/dist/sdk/lifecycle/reopen.js +1 -68
  543. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
  544. package/dist/sdk/lifecycle/restore.d.ts +1 -0
  545. package/dist/sdk/lifecycle/restore.js +1 -330
  546. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
  547. package/dist/sdk/lifecycle/update-many.js +1 -861
  548. package/dist/sdk/lifecycle/update.js +1 -2136
  549. package/dist/sdk/lifecycle-completion.js +1 -92
  550. package/dist/sdk/lifecycle-policy.js +1 -120
  551. package/dist/sdk/linked-artifacts.js +1 -530
  552. package/dist/sdk/mcp/apps.js +4 -133
  553. package/dist/sdk/mcp/authorization.js +1 -404
  554. package/dist/sdk/mcp/discovery.js +1 -494
  555. package/dist/sdk/mcp/interactions.js +1 -336
  556. package/dist/sdk/mcp/protocol.d.ts +7 -0
  557. package/dist/sdk/mcp/protocol.js +1 -184
  558. package/dist/sdk/mcp/skills.js +1 -389
  559. package/dist/sdk/mcp/subscriptions.js +1 -211
  560. package/dist/sdk/mcp/tasks.js +2 -430
  561. package/dist/sdk/mcp/transport.js +1 -260
  562. package/dist/sdk/merge/abandoned-receipts.js +1 -46
  563. package/dist/sdk/merge/driver.js +1 -212
  564. package/dist/sdk/merge/index.js +1 -16
  565. package/dist/sdk/merge/install.js +3 -561
  566. package/dist/sdk/merge/receipt-file-boundary.js +1 -46
  567. package/dist/sdk/merge/receipt-operation.js +1 -96
  568. package/dist/sdk/merge/receipt-schema.js +1 -397
  569. package/dist/sdk/merge/receipts.js +4 -525
  570. package/dist/sdk/merge/reconcile.js +1 -352
  571. package/dist/sdk/merge/three-way.js +3 -775
  572. package/dist/sdk/merge.js +1 -10
  573. package/dist/sdk/mutation-events.js +1 -292
  574. package/dist/sdk/mutation-guard.js +1 -216
  575. package/dist/sdk/notes.js +1 -139
  576. package/dist/sdk/output-contracts.js +1 -172
  577. package/dist/sdk/output-projection.js +1 -430
  578. package/dist/sdk/output-token-accounting.js +1 -140
  579. package/dist/sdk/output.js +1 -64
  580. package/dist/sdk/ownership-source.js +1 -21
  581. package/dist/sdk/package-import-adapters.js +1 -442
  582. package/dist/sdk/package-migrations.js +1 -20
  583. package/dist/sdk/package-runtime-options.js +1 -80
  584. package/dist/sdk/pagination.js +1 -162
  585. package/dist/sdk/profile.js +1 -454
  586. package/dist/sdk/provenance.js +1 -258
  587. package/dist/sdk/public-surface.json +1 -1
  588. package/dist/sdk/query/activity.js +1 -401
  589. package/dist/sdk/query/aggregate.d.ts +16 -0
  590. package/dist/sdk/query/aggregate.js +1 -390
  591. package/dist/sdk/query/calendar.js +1 -964
  592. package/dist/sdk/query/complete-list.js +1 -215
  593. package/dist/sdk/query/context.js +1 -1702
  594. package/dist/sdk/query/duplicate-candidates.js +1 -70
  595. package/dist/sdk/query/get.js +1 -450
  596. package/dist/sdk/query/history.js +1 -186
  597. package/dist/sdk/query/item-filter-options.js +1 -9
  598. package/dist/sdk/query/light-metadata.js +1 -18
  599. package/dist/sdk/query/list-filter-shared.js +1 -81
  600. package/dist/sdk/query/list.js +1 -1304
  601. package/dist/sdk/query/multi-value-filters.js +1 -78
  602. package/dist/sdk/query/next.js +1 -513
  603. package/dist/sdk/query/parsers.js +1 -44
  604. package/dist/sdk/query/projection-contracts.js +1 -184
  605. package/dist/sdk/query/search-contracts.js +1 -230
  606. package/dist/sdk/query/search-pagination.js +1 -35
  607. package/dist/sdk/query/search-rendering.js +1 -105
  608. package/dist/sdk/query/search.js +2 -1987
  609. package/dist/sdk/query.js +1 -35
  610. package/dist/sdk/read-output/continuation.js +1 -194
  611. package/dist/sdk/read-output-budget.js +1 -135
  612. package/dist/sdk/read-output-contracts.js +1 -1225
  613. package/dist/sdk/read-output-rows.js +1 -186
  614. package/dist/sdk/read-output-session.js +1 -208
  615. package/dist/sdk/relationship-analytics.js +1 -410
  616. package/dist/sdk/relationship-context.js +1 -284
  617. package/dist/sdk/relationship-history.js +4 -519
  618. package/dist/sdk/relationship-kinds/contract.js +1 -22
  619. package/dist/sdk/relationship-migration.js +1 -77
  620. package/dist/sdk/relationships.js +1 -579
  621. package/dist/sdk/reproducibility/process.js +1 -87
  622. package/dist/sdk/runtime-action-aliases.js +1 -59
  623. package/dist/sdk/runtime-extended-actions.js +1 -177
  624. package/dist/sdk/runtime-input.js +1 -614
  625. package/dist/sdk/runtime-primitives.js +1 -84
  626. package/dist/sdk/runtime-public-contracts.js +1 -4
  627. package/dist/sdk/runtime-stats-options.js +1 -38
  628. package/dist/sdk/runtime.js +1 -1928
  629. package/dist/sdk/scheduling-shortcuts.js +1 -63
  630. package/dist/sdk/schema-migration.js +3 -856
  631. package/dist/sdk/schema.js +1 -1376
  632. package/dist/sdk/search-refresh-worker.js +1 -18
  633. package/dist/sdk/similarity-scoring.js +1 -53
  634. package/dist/sdk/similarity.js +1 -326
  635. package/dist/sdk/start-task-status.js +1 -14
  636. package/dist/sdk/stats.js +1 -270
  637. package/dist/sdk/structured-mutations.js +1 -580
  638. package/dist/sdk/telemetry-flush.js +1 -13
  639. package/dist/sdk/telemetry.js +1 -405
  640. package/dist/sdk/templates.js +2 -292
  641. package/dist/sdk/test/batch.js +2 -509
  642. package/dist/sdk/test/entry.js +1 -70
  643. package/dist/sdk/test/execution.js +6 -2211
  644. package/dist/sdk/test/linked-command-detection.js +1 -546
  645. package/dist/sdk/test/measurements.js +1 -91
  646. package/dist/sdk/test/parsers.js +1 -545
  647. package/dist/sdk/test/runs.js +1 -193
  648. package/dist/sdk/test/trust.js +2 -206
  649. package/dist/sdk/testing.js +4 -1391
  650. package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
  651. package/dist/sdk/traceability/source-traceability.js +1 -292
  652. package/dist/sdk/tracker-root-discovery.js +1 -9
  653. package/dist/sdk/workspace-contracts-cache.js +1 -28
  654. package/dist/sdk/workspace-contracts.js +1 -33
  655. package/dist/sdk/workspace-memory.js +2 -318
  656. package/dist/sdk/workspace-recipe.js +1 -71
  657. package/dist/sdk/workspace-snapshot.js +4 -613
  658. package/dist/sdk/workspace-transaction-gc.js +1 -149
  659. package/dist/sdk/workspace-transaction.js +2 -363
  660. package/dist/sdk/workspace.js +3 -127
  661. package/dist/types/index.js +1 -9
  662. package/dist/types.js +1 -245
  663. package/docs/AGENT_GUIDE.md +1 -1
  664. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
  665. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
  666. package/docs/EXTENSIONS.md +1 -0
  667. package/docs/HISTORY_MAINTENANCE.md +125 -0
  668. package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
  669. package/docs/PACKAGE_EVIDENCE.md +92 -0
  670. package/docs/PLANNING_MEASUREMENTS.md +183 -0
  671. package/docs/README.md +3 -0
  672. package/docs/SCRIPTING.md +21 -0
  673. package/docs/TESTING.md +23 -0
  674. package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -5
  675. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
  676. package/marketplace.json +2 -2
  677. package/package.json +1 -1
  678. package/packages/pm-beads/package.json +1 -1
  679. package/packages/pm-calendar/package.json +1 -1
  680. package/packages/pm-command-kit/package.json +1 -1
  681. package/packages/pm-digital-twin/package.json +1 -1
  682. package/packages/pm-governance-audit/package.json +1 -1
  683. package/packages/pm-guide-shell/package.json +1 -1
  684. package/packages/pm-kanban/package.json +1 -1
  685. package/packages/pm-lifecycle-hooks/package.json +1 -1
  686. package/packages/pm-linked-test-adapters/package.json +1 -1
  687. package/packages/pm-search-advanced/package.json +1 -1
  688. package/packages/pm-templates/package.json +1 -1
  689. package/packages/pm-todos/package.json +1 -1
  690. package/packages/pm-vcs/package.json +1 -1
  691. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  692. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  693. package/scripts/finalize-build.mjs +45 -3
  694. package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
  695. package/dist/cli-bundle/chunks/chunk-BAX2BYUW.js +0 -2111
  696. package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
  697. package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
  698. package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
  699. package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
  700. package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
  701. package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
  702. package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
  703. package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
  704. package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
  705. package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
  706. package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
  707. package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
  708. package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
  709. package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
  710. package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
  711. package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
  712. package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
  713. package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
  714. package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
  715. package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
  716. package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
  717. package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
  718. package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +0 -2
@@ -1,2091 +1,2 @@
1
- /**
2
- * @module cli/commands/contracts
3
- *
4
- * Implements the pm contracts command surface and its agent-facing runtime behavior.
5
- */
6
-
7
- !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]="188569e7-c809-5f28-a714-d531f57be1d9")}catch(e){}}();
8
- import { EXIT_CODE, SETTINGS_DEFAULTS, PmCliError, activateExtensions, getActiveExtensionRegistrations, loadExtensions, pathExists, commandOptionFlagLabel, resolveCommandOptionPolicyState, resolveItemTypeRegistry, resolveRuntimeFieldRegistry, resolveRuntimeStatusRegistry, getSettingsPath, resolvePmRoot, readSettings, } from "../runtime-primitives.js";
9
- import { buildMcpToolContracts, } from "../../mcp/tool-definitions.js";
10
- import { ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS, ACTIVITY_FLAG_CONTRACTS, AGGREGATE_FLAG_CONTRACTS, ASSURANCE_FLAG_CONTRACTS, APPEND_FLAG_CONTRACTS, CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS, CALENDAR_FLAG_CONTRACTS, CLAIM_FLAG_CONTRACTS, CLOSE_TASK_FLAG_CONTRACTS, COMMENTS_FLAG_CONTRACTS, CLOSE_FLAG_CONTRACTS, CLOSE_MANY_FLAG_CONTRACTS, COMPLETION_FLAG_CONTRACTS, CONFIG_FLAG_CONTRACTS, CONTRACTS_FLAG_CONTRACTS, COPY_FLAG_CONTRACTS, CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS, CONTEXT_FLAG_CONTRACTS, CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS, CREATE_COMMANDER_STRING_OPTION_CONTRACTS, CREATE_FLAG_CONTRACTS, DELETE_FLAG_CONTRACTS, DEPS_FLAG_CONTRACTS, GRAPH_FLAG_CONTRACTS, DOCS_FLAG_CONTRACTS, EXTENSION_ACTIVATE_FLAG_CONTRACTS, EXTENSION_ADOPT_ALL_FLAG_CONTRACTS, EXTENSION_ADOPT_FLAG_CONTRACTS, EXTENSION_CATALOG_FLAG_CONTRACTS, EXTENSION_DEACTIVATE_FLAG_CONTRACTS, EXTENSION_DESCRIBE_FLAG_CONTRACTS, EXTENSION_DOCTOR_FLAG_CONTRACTS, EXTENSION_EXPLORE_FLAG_CONTRACTS, EXTENSION_FLAG_CONTRACTS, EXTENSION_INIT_FLAG_CONTRACTS, EXTENSION_INSTALL_FLAG_CONTRACTS, EXTENSION_MANAGE_FLAG_CONTRACTS, EXTENSION_MIGRATE_FLAG_CONTRACTS, EXTENSION_RELOAD_FLAG_CONTRACTS, EXTENSION_UNINSTALL_FLAG_CONTRACTS, FILES_FLAG_CONTRACTS, FOCUS_FLAG_CONTRACTS, GC_FLAG_CONTRACTS, GET_FLAG_CONTRACTS, GUIDE_FLAG_CONTRACTS, GLOBAL_FLAG_CONTRACTS, HEALTH_FLAG_CONTRACTS, HISTORY_FLAG_CONTRACTS, HISTORY_COMPACT_FLAG_CONTRACTS, HISTORY_REDACT_FLAG_CONTRACTS, HISTORY_REPAIR_FLAG_CONTRACTS, HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS, INSTALL_FLAG_CONTRACTS, INIT_FLAG_CONTRACTS, ITEM_COMPLETE_FLAG_CONTRACTS, ITEM_MUTATE_FLAG_CONTRACTS, ITEM_REOPEN_FLAG_CONTRACTS, LEARNINGS_FLAG_CONTRACTS, LIST_COMMANDER_STRING_OPTION_CONTRACTS, LIST_FILTER_FLAG_CONTRACTS, MERGE_FLAG_CONTRACTS, NOTES_FLAG_CONTRACTS, PACKAGE_FLAG_CONTRACTS, PACKAGE_INIT_FLAG_CONTRACTS, PM_EXTENSION_CAPABILITY_CONTRACTS, PM_EXTENSION_POLICY_MODE_CONTRACTS, PM_EXTENSION_POLICY_SURFACE_CONTRACTS, PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS, PM_EXTENSION_SERVICE_NAME_CONTRACTS, PM_EXTENSION_TRUST_MODE_CONTRACTS, PM_OUTPUT_DEGRADATION_STEPS, PLAN_FLAG_CONTRACTS, PM_CORE_COMMAND_NAMES, PM_DEPRECATED_TOOL_ACTIONS, PM_TOOL_ACTIONS, PM_TOOL_PARAMETERS_SCHEMA, REINDEX_FLAG_CONTRACTS, RELEASE_FLAG_CONTRACTS, RESTORE_FLAG_CONTRACTS, SCHEMA_FLAG_CONTRACTS, PROFILE_FLAG_CONTRACTS, SEARCH_COMMANDER_STRING_OPTION_CONTRACTS, EVAL_FLAG_CONTRACTS, WORKSPACE_FLAG_CONTRACTS, NEXT_FLAG_CONTRACTS, SEARCH_FLAG_CONTRACTS, STATS_FLAG_CONTRACTS, DUPLICATES_FLAG_CONTRACTS, START_TASK_FLAG_CONTRACTS, PAUSE_TASK_FLAG_CONTRACTS, TELEMETRY_FLAG_CONTRACTS, TEST_ALL_FLAG_CONTRACTS, TEST_FLAG_CONTRACTS, TEST_RUNS_FLAG_CONTRACTS, UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS, UPDATE_COMMANDER_STRING_OPTION_CONTRACTS, UPDATE_FLAG_CONTRACTS, UPDATE_MANY_FLAG_CONTRACTS, UPGRADE_FLAG_CONTRACTS, VALIDATE_FLAG_CONTRACTS, compactFlagAliasContracts, PM_COMMAND_ALIAS_CONTRACTS, PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS, resolvePmCommandOutputBudget, } from "../cli-contracts.js";
11
- import { PM_POSITIONAL_ACTION_FLAG_CONTRACTS } from "./flag-contracts.js";
12
- import { GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES, GOVERNANCE_CREATE_MODE_DEFAULT_VALUES, GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES, GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES, } from "../../types.js";
13
- import { BRIEF_LIST_FIELDS, DEFAULT_COMPACT_LIST_FIELDS, LIST_COMMAND_DEFAULT_PROJECTIONS, } from "../query/list.js";
14
- import { getActiveContextIntentContracts, } from "../context-intent-contracts.js";
15
- import { readOutputIncludeModeOptions, resolveReadOutputSurface, PM_READ_OUTPUT_SURFACE_CONTRACTS, } from "../read-output-contracts.js";
16
- import { enrichCliFlagInvocationContracts, } from "../flag-invocation-contracts.js";
17
- import { resolvePmCommandVisibilityTier, } from "../agent-capability-contracts.js";
18
- import { PM_ERROR_CODE_CATALOG } from "../generated-error-code-catalog.js";
19
- import { resolvePmCommandOutputEnvelope, } from "../output-contracts.js";
20
- import { PM_COMMAND_EXIT_OUTCOME_CONTRACTS, resolvePmCommandExitContract, } from "./command-exit-contracts.js";
21
- import { BUILTIN_RELATIONSHIP_KINDS } from "../relationship-kinds/contract.js";
22
- import { ASSURANCE_GATE_TRIGGERS, ASSURANCE_MEASUREMENT_SOURCE_KINDS, } from "../governance/assurance.js";
23
- import { PM_CLI_GRAMMAR_CONTRACT, PM_COMMAND_DESTINATION_CONTRACTS, PM_COMMAND_POSITIONAL_CONTRACTS, PM_POSITIONAL_ACTION_CONTRACTS, positionalShapeKey, resolvePmCommandPositionalContract, } from "./grammar-contracts.js";
24
- const AGENT_BOOTSTRAP_FLAGS = new Map([
25
- [
26
- "claim",
27
- [
28
- "--if-available",
29
- "--next",
30
- "--type",
31
- "--priority",
32
- "--token-budget",
33
- "--explain-ranking",
34
- ],
35
- ],
36
- [
37
- "close",
38
- [
39
- "--reason",
40
- "--validate-close",
41
- "--resolution",
42
- "--expected-result",
43
- "--actual-result",
44
- "--message",
45
- ],
46
- ],
47
- [
48
- "context",
49
- [
50
- "--limit",
51
- "--after",
52
- "--depth",
53
- "--section",
54
- "--token-budget",
55
- "--explain-ranking",
56
- ],
57
- ],
58
- [
59
- "contracts",
60
- [
61
- "--command",
62
- "--flags-only",
63
- "--summary",
64
- "--runtime-only",
65
- "--availability-only",
66
- "--full",
67
- ],
68
- ],
69
- [
70
- "create",
71
- ["--title", "--type", "--status", "--priority", "--dep", "--comment"],
72
- ],
73
- [
74
- "get",
75
- ["--full", "--depth", "--fields", "--tree", "--tree-depth", "--format"],
76
- ],
77
- [
78
- "health",
79
- [
80
- "--check-only",
81
- "--summary",
82
- "--brief",
83
- "--check-telemetry",
84
- "--strict-exit",
85
- "--full",
86
- ],
87
- ],
88
- ["list", ["--status", "--type", "--limit", "--after", "--brief", "--fields"]],
89
- [
90
- "next",
91
- [
92
- "--limit",
93
- "--blocked-limit",
94
- "--ready-only",
95
- "--token-budget",
96
- "--explain-ranking",
97
- "--format",
98
- ],
99
- ],
100
- [
101
- "search",
102
- ["--mode", "--status", "--type", "--limit", "--after", "--fields"],
103
- ],
104
- [
105
- "update",
106
- ["--status", "--message", "--dep", "--comment", "--file", "--test"],
107
- ],
108
- [
109
- "validate",
110
- [
111
- "--check-resolution",
112
- "--check-history-drift",
113
- "--check-storage-integrity",
114
- "--counts",
115
- "--strict-exit",
116
- "--fix-hints",
117
- ],
118
- ],
119
- ]);
120
- const AGENT_BOUNDED_FLAG_PRIORITY = [
121
- "--limit",
122
- "--after",
123
- "--offset",
124
- "--token-budget",
125
- "--brief",
126
- "--summary",
127
- "--compact",
128
- "--fields",
129
- "--full",
130
- "--format",
131
- "--since",
132
- "--until",
133
- ];
134
- const LIST_COMMAND_NAMES = new Set([
135
- "list",
136
- "list-all",
137
- "list-draft",
138
- "list-open",
139
- "list-in-progress",
140
- "list-blocked",
141
- "list-closed",
142
- "list-canceled",
143
- ]);
144
- const PACKAGE_OWNED_ACTIONS = new Set([
145
- "calendar",
146
- "guide",
147
- "reindex",
148
- "completion",
149
- "test-runs-list",
150
- "test-runs-status",
151
- "test-runs-logs",
152
- "test-runs-stop",
153
- "test-runs-resume",
154
- "templates-list",
155
- "templates-save",
156
- "templates-show",
157
- ]);
158
- const PACKAGE_OWNED_COMMANDS = new Set([
159
- "cal",
160
- "calendar",
161
- "completion",
162
- "completion-statuses",
163
- "completion-tags",
164
- "completion-types",
165
- "guide",
166
- "reindex",
167
- "templates",
168
- "templates list",
169
- "templates save",
170
- "templates show",
171
- "test-runs",
172
- "test-runs list",
173
- "test-runs status",
174
- "test-runs logs",
175
- "test-runs stop",
176
- "test-runs resume",
177
- ]);
178
- const PACKAGE_OWNED_COMMAND_INSTALL_HINTS = new Map([
179
- ["cal", "calendar"],
180
- ["calendar", "calendar"],
181
- ["completion", "guide-shell"],
182
- ["completion-statuses", "guide-shell"],
183
- ["completion-tags", "guide-shell"],
184
- ["completion-types", "guide-shell"],
185
- ["guide", "guide-shell"],
186
- ["reindex", "search-advanced"],
187
- ["templates", "templates"],
188
- ["templates list", "templates"],
189
- ["templates save", "templates"],
190
- ["templates show", "templates"],
191
- ["test-runs", "linked-test-adapters"],
192
- ["test-runs list", "linked-test-adapters"],
193
- ["test-runs status", "linked-test-adapters"],
194
- ["test-runs logs", "linked-test-adapters"],
195
- ["test-runs stop", "linked-test-adapters"],
196
- ["test-runs resume", "linked-test-adapters"],
197
- ]);
198
- const PACKAGE_OWNED_ACTION_COMMAND_PATHS = new Map([
199
- ["calendar", "calendar|cal"],
200
- ["guide", "guide"],
201
- ["reindex", "reindex"],
202
- ["completion", "completion"],
203
- ["test-runs-list", "test-runs|test-runs list"],
204
- ["test-runs-status", "test-runs status"],
205
- ["test-runs-logs", "test-runs logs"],
206
- ["test-runs-stop", "test-runs stop"],
207
- ["test-runs-resume", "test-runs resume"],
208
- ["templates-list", "templates|templates list"],
209
- ["templates-save", "templates save"],
210
- ["templates-show", "templates show"],
211
- ]);
212
- const PACKAGE_OWNED_COMMAND_ACTIONS = new Map([...PACKAGE_OWNED_ACTION_COMMAND_PATHS.entries()].flatMap(([action, commandPaths]) => splitCommandPathAliases(commandPaths).map((commandPath) => [commandPath, action])));
213
- const CANONICAL_COMMAND_ALIASES = [
214
- {
215
- canonical: "context",
216
- aliases: ["ctx"],
217
- },
218
- {
219
- canonical: "package",
220
- aliases: ["extension", "packages"],
221
- },
222
- ];
223
- const COMMAND_ALIAS_TO_CANONICAL = new Map(CANONICAL_COMMAND_ALIASES.flatMap((entry) => entry.aliases.map((alias) => [alias, entry.canonical])));
224
- const COMMAND_NAMESPACE_DISPLAY_LIMIT = 10;
225
- const COMMAND_NAMESPACE_FALLBACK_LIMIT = 20;
226
- const COMMAND_INTENTS = new Map([
227
- ["activity", "Read activity."],
228
- ["aggregate", "Group counts."],
229
- ["append", "Append body."],
230
- ["assurance", "Evaluate assurance."],
231
- ["assurance derive", "Derive checks from evidence."],
232
- ["assurance risk", "Select checks for changes."],
233
- ["assurance lineages", "Measure recurrence coverage."],
234
- ["beads", "Manage Beads interoperability."],
235
- ["cal", "Manage calendar integration."],
236
- ["calendar", "Manage calendar integration."],
237
- ["changelog", "Generate changelog output."],
238
- ["claim", "Claim work."],
239
- ["close", "Close work."],
240
- ["close-many", "Close matching work."],
241
- ["close-task", "Close task work."],
242
- ["command-kit", "Inspect command authoring primitives."],
243
- ["comments", "Manage comments."],
244
- ["comments-audit", "Audit comment governance."],
245
- ["completion", "Generate shell completions."],
246
- ["config", "Manage settings."],
247
- ["context", "Build context."],
248
- ["contracts", "Inspect contracts."],
249
- ["copy", "Copy work."],
250
- ["create", "Create work."],
251
- ["dedupe-audit", "Audit duplicate work."],
252
- ["dedupe-merge", "Merge duplicate work."],
253
- ["delete", "Delete work."],
254
- ["deps", "Manage deps."],
255
- ["duplicates", "Find duplicate clusters."],
256
- ["docs", "Link docs."],
257
- ["eval", "Run evaluations."],
258
- ["event", "Manage events."],
259
- ["events", "Read events."],
260
- ["files", "Link files."],
261
- ["focus", "Manage focus."],
262
- ["gc", "Clean caches."],
263
- ["get", "Read item."],
264
- ["graph", "Query graph."],
265
- ["guide", "Show user guides."],
266
- ["health", "Check health."],
267
- ["help", "Show help."],
268
- ["history", "Inspect history."],
269
- ["init", "Initialize workspace."],
270
- ["install", "Install packages."],
271
- ["item", "Mutate work through typed operations."],
272
- ["learnings", "Manage learnings."],
273
- ["list", "List work."],
274
- ["list-all", "List work across every status."],
275
- ["list-blocked", "List blocked work."],
276
- ["list-canceled", "List canceled work."],
277
- ["list-closed", "List closed work."],
278
- ["list-draft", "List draft work."],
279
- ["list-in-progress", "List in-progress work."],
280
- ["list-open", "List open work."],
281
- ["meet", "Record meeting context."],
282
- ["merge", "Manage tracker merges."],
283
- ["next", "Pick next work."],
284
- ["notes", "Manage notes."],
285
- ["normalize", "Normalize tracker data."],
286
- ["ops", "Run operations."],
287
- ["package", "Manage packages."],
288
- ["packages", "Manage packages."],
289
- ["pause-task", "Pause task work."],
290
- ["plan", "Manage plans."],
291
- ["profile", "Manage profiles."],
292
- ["reindex", "Refresh search index."],
293
- ["release", "Release claim."],
294
- ["remind", "Manage reminders."],
295
- ["restore", "Restore history."],
296
- ["schema", "Customize schema."],
297
- ["search", "Search work."],
298
- ["search-advanced", "Run advanced search."],
299
- ["start-task", "Start task work."],
300
- ["stats", "Show stats."],
301
- ["telemetry", "Manage telemetry."],
302
- ["templates", "Manage work templates."],
303
- ["test", "Run linked tests."],
304
- ["test-all", "Run all linked tests."],
305
- ["test-runs", "Inspect background test runs."],
306
- ["todos", "Manage source-code todos."],
307
- ["twin", "Manage repository twins."],
308
- ["update", "Update work."],
309
- ["update-many", "Update matching work."],
310
- ["upgrade", "Upgrade packages."],
311
- ["validate", "Validate data."],
312
- ["vcs", "Inspect version-control context."],
313
- ["workspace", "Manage portable workspace primitives."],
314
- ["history-author-acknowledge", "Acknowledge reviewed history authors."],
315
- ["history-compact", "Compact history."],
316
- ["history-redact", "Redact sensitive history values."],
317
- ["history-repair", "Repair history integrity."],
318
- ]);
319
- // Lifecycle subcommand flag contracts for `pm extension`. Package lifecycle
320
- // swaps in the declarative init contract and adds the package-only upgrade
321
- // command; every shared extension/package subcommand remains byte-identical.
322
- const EXTENSION_LIFECYCLE_FLAG_CONTRACTS = [
323
- ["init", EXTENSION_INIT_FLAG_CONTRACTS],
324
- ["install", EXTENSION_INSTALL_FLAG_CONTRACTS],
325
- ["uninstall", EXTENSION_UNINSTALL_FLAG_CONTRACTS],
326
- ["explore", EXTENSION_EXPLORE_FLAG_CONTRACTS],
327
- ["manage", EXTENSION_MANAGE_FLAG_CONTRACTS],
328
- ["describe", EXTENSION_DESCRIBE_FLAG_CONTRACTS],
329
- ["reload", EXTENSION_RELOAD_FLAG_CONTRACTS],
330
- ["doctor", EXTENSION_DOCTOR_FLAG_CONTRACTS],
331
- ["catalog", EXTENSION_CATALOG_FLAG_CONTRACTS],
332
- ["adopt", EXTENSION_ADOPT_FLAG_CONTRACTS],
333
- ["adopt-all", EXTENSION_ADOPT_ALL_FLAG_CONTRACTS],
334
- ["activate", EXTENSION_ACTIVATE_FLAG_CONTRACTS],
335
- ["deactivate", EXTENSION_DEACTIVATE_FLAG_CONTRACTS],
336
- ["migrate", EXTENSION_MIGRATE_FLAG_CONTRACTS],
337
- ];
338
- const PACKAGE_LIFECYCLE_FLAG_CONTRACTS = [
339
- ...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand, flags]) => subcommand === "init"
340
- ? [subcommand, PACKAGE_INIT_FLAG_CONTRACTS]
341
- : [subcommand, flags]),
342
- ["upgrade", UPGRADE_FLAG_CONTRACTS],
343
- ];
344
- const CORE_COMMAND_FLAG_CONTRACT_ENTRIES = [
345
- ...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand, flags]) => [`extension ${subcommand}`, flags]),
346
- ...PACKAGE_LIFECYCLE_FLAG_CONTRACTS.flatMap(([subcommand, flags]) => [
347
- [`package ${subcommand}`, flags],
348
- [`packages ${subcommand}`, flags],
349
- ]),
350
- ["init", INIT_FLAG_CONTRACTS],
351
- ["config", CONFIG_FLAG_CONTRACTS],
352
- ["extension", EXTENSION_FLAG_CONTRACTS],
353
- ["package", PACKAGE_FLAG_CONTRACTS],
354
- ["packages", PACKAGE_FLAG_CONTRACTS],
355
- ["install", INSTALL_FLAG_CONTRACTS],
356
- ["create", CREATE_FLAG_CONTRACTS],
357
- ["item mutate", ITEM_MUTATE_FLAG_CONTRACTS],
358
- ["item complete", ITEM_COMPLETE_FLAG_CONTRACTS],
359
- ["item reopen", ITEM_REOPEN_FLAG_CONTRACTS],
360
- ["copy", COPY_FLAG_CONTRACTS],
361
- ["focus", FOCUS_FLAG_CONTRACTS],
362
- ["update", UPDATE_FLAG_CONTRACTS],
363
- ["update-many", UPDATE_MANY_FLAG_CONTRACTS],
364
- ["upgrade", UPGRADE_FLAG_CONTRACTS],
365
- ["calendar", CALENDAR_FLAG_CONTRACTS],
366
- ["cal", CALENDAR_FLAG_CONTRACTS],
367
- ["context", CONTEXT_FLAG_CONTRACTS],
368
- ["ctx", CONTEXT_FLAG_CONTRACTS],
369
- ["get", GET_FLAG_CONTRACTS],
370
- ["search", SEARCH_FLAG_CONTRACTS],
371
- ["eval", EVAL_FLAG_CONTRACTS],
372
- ["workspace", WORKSPACE_FLAG_CONTRACTS],
373
- ["workspace position", []],
374
- ["workspace snapshot", WORKSPACE_FLAG_CONTRACTS],
375
- ["workspace snapshot create", WORKSPACE_FLAG_CONTRACTS],
376
- ["workspace snapshot list", WORKSPACE_FLAG_CONTRACTS],
377
- ["workspace snapshot inspect", WORKSPACE_FLAG_CONTRACTS],
378
- ["workspace snapshot restore", WORKSPACE_FLAG_CONTRACTS],
379
- ["workspace snapshot delete", WORKSPACE_FLAG_CONTRACTS],
380
- ["next", NEXT_FLAG_CONTRACTS],
381
- ["aggregate", AGGREGATE_FLAG_CONTRACTS],
382
- ["deps", DEPS_FLAG_CONTRACTS],
383
- ["graph", GRAPH_FLAG_CONTRACTS],
384
- ["guide", GUIDE_FLAG_CONTRACTS],
385
- ["reindex", REINDEX_FLAG_CONTRACTS],
386
- ["history", HISTORY_FLAG_CONTRACTS],
387
- ["history-compact", HISTORY_COMPACT_FLAG_CONTRACTS],
388
- ["history-redact", HISTORY_REDACT_FLAG_CONTRACTS],
389
- ["history-repair", HISTORY_REPAIR_FLAG_CONTRACTS],
390
- ["history-author-acknowledge", HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS],
391
- ["merge", MERGE_FLAG_CONTRACTS],
392
- ["schema", SCHEMA_FLAG_CONTRACTS],
393
- ["profile", PROFILE_FLAG_CONTRACTS],
394
- ["plan", PLAN_FLAG_CONTRACTS],
395
- ["restore", RESTORE_FLAG_CONTRACTS],
396
- ["delete", DELETE_FLAG_CONTRACTS],
397
- ["close", CLOSE_FLAG_CONTRACTS],
398
- ["close-many", CLOSE_MANY_FLAG_CONTRACTS],
399
- ["append", APPEND_FLAG_CONTRACTS],
400
- ["claim", CLAIM_FLAG_CONTRACTS],
401
- ["release", RELEASE_FLAG_CONTRACTS],
402
- ["start-task", START_TASK_FLAG_CONTRACTS],
403
- ["pause-task", PAUSE_TASK_FLAG_CONTRACTS],
404
- ["close-task", CLOSE_TASK_FLAG_CONTRACTS],
405
- ["comments", COMMENTS_FLAG_CONTRACTS],
406
- ["notes", NOTES_FLAG_CONTRACTS],
407
- ["learnings", LEARNINGS_FLAG_CONTRACTS],
408
- ["files", FILES_FLAG_CONTRACTS],
409
- ["docs", DOCS_FLAG_CONTRACTS],
410
- ["test", TEST_FLAG_CONTRACTS],
411
- ["test-all", TEST_ALL_FLAG_CONTRACTS],
412
- ["telemetry", TELEMETRY_FLAG_CONTRACTS],
413
- ["test-runs", TEST_RUNS_FLAG_CONTRACTS],
414
- ["gc", GC_FLAG_CONTRACTS],
415
- ["stats", STATS_FLAG_CONTRACTS],
416
- ["duplicates", DUPLICATES_FLAG_CONTRACTS],
417
- ["validate", VALIDATE_FLAG_CONTRACTS],
418
- ["health", HEALTH_FLAG_CONTRACTS],
419
- ["assurance", ASSURANCE_FLAG_CONTRACTS],
420
- ...PM_POSITIONAL_ACTION_FLAG_CONTRACTS,
421
- ["contracts", CONTRACTS_FLAG_CONTRACTS],
422
- ["completion", COMPLETION_FLAG_CONTRACTS],
423
- ["activity", ACTIVITY_FLAG_CONTRACTS],
424
- ...[...LIST_COMMAND_NAMES].map((command) => [command, LIST_FILTER_FLAG_CONTRACTS]),
425
- ];
426
- const CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND = new Map(CORE_COMMAND_FLAG_CONTRACT_ENTRIES);
427
- /* c8 ignore start -- extension contract shaping utilities are exercised by dedicated extension/runtime integration suites. */
428
- function packageOwnedActionForCommand(command) {
429
- const exactAction = PACKAGE_OWNED_COMMAND_ACTIONS.get(command);
430
- if (exactAction) {
431
- return exactAction;
432
- }
433
- if (command.startsWith("test-runs ")) {
434
- return `test-runs-${command.slice("test-runs ".length)}`;
435
- }
436
- if (command.startsWith("templates ")) {
437
- return `templates-${command.slice("templates ".length)}`;
438
- }
439
- return command;
440
- }
441
- function resolveActionCommandPath(action) {
442
- if (PM_CORE_COMMAND_NAMES.includes(action)) {
443
- return normalizeCommandPath(action);
444
- }
445
- if (action.startsWith("extension-")) {
446
- return normalizeCommandPath(`extension ${action.slice("extension-".length)}`);
447
- }
448
- if (action.startsWith("package-")) {
449
- return normalizeCommandPath(`package ${action.slice("package-".length)}`);
450
- }
451
- if (action.startsWith("item-")) {
452
- return normalizeCommandPath(`item ${action.slice("item-".length)}`);
453
- }
454
- if (action.startsWith("test-runs-")) {
455
- return normalizeCommandPath(`test-runs ${action.slice("test-runs-".length)}`);
456
- }
457
- if (action.startsWith("templates-")) {
458
- return normalizeCommandPath(`templates ${action.slice("templates-".length)}`);
459
- }
460
- if (PACKAGE_OWNED_ACTIONS.has(action)) {
461
- return (PACKAGE_OWNED_ACTION_COMMAND_PATHS.get(action) ??
462
- normalizeCommandPath(action));
463
- }
464
- return null;
465
- }
466
- function actionDescriptorMatchesSelectedCommand(descriptor, selectedCommand) {
467
- if (descriptor.command_path === null) {
468
- return false;
469
- }
470
- return splitCommandPathAliases(descriptor.command_path).some((commandPath) => {
471
- if (commandPath === selectedCommand) {
472
- return true;
473
- }
474
- return (commandPath.startsWith(`${selectedCommand} `) ||
475
- selectedCommand.startsWith(`${commandPath} `));
476
- });
477
- }
478
- function splitCommandPathAliases(commandPath) {
479
- return commandPath
480
- .split("|")
481
- .map((entry) => normalizeCommandPath(entry))
482
- .filter((entry) => entry.length > 0);
483
- }
484
- function resolveScopedCommandsFromActionDescriptors(descriptors, commandCatalog) {
485
- const commandSet = new Set(commandCatalog);
486
- const scoped = new Set();
487
- for (const descriptor of descriptors) {
488
- if (!descriptor.command_path) {
489
- continue;
490
- }
491
- for (const commandPath of splitCommandPathAliases(descriptor.command_path)) {
492
- const tokens = commandPath.split(" ").filter((entry) => entry.length > 0);
493
- if (tokens.length === 0) {
494
- continue;
495
- }
496
- for (let end = tokens.length; end > 0; end -= 1) {
497
- const candidate = tokens.slice(0, end).join(" ");
498
- if (!commandSet.has(candidate)) {
499
- continue;
500
- }
501
- scoped.add(candidate);
502
- break;
503
- }
504
- }
505
- }
506
- return [...scoped].sort((left, right) => left.localeCompare(right));
507
- }
508
- function normalizeToken(value) {
509
- if (typeof value !== "string") {
510
- return undefined;
511
- }
512
- const trimmed = value.trim().toLowerCase();
513
- return trimmed.length > 0 ? trimmed : undefined;
514
- }
515
- function extractActionBranches(schema) {
516
- const oneOf = schema.oneOf;
517
- if (!Array.isArray(oneOf)) {
518
- return [];
519
- }
520
- return oneOf.filter((entry) => typeof entry === "object" && entry !== null);
521
- }
522
- function filterSchemaByAction(schema, action) {
523
- if (!action) {
524
- return { ...schema };
525
- }
526
- const branches = extractActionBranches(schema);
527
- const filtered = branches.filter((entry) => {
528
- const properties = entry.properties;
529
- if (typeof properties !== "object" || properties === null) {
530
- return false;
531
- }
532
- const actionProperty = properties.action;
533
- if (typeof actionProperty !== "object" || actionProperty === null) {
534
- return false;
535
- }
536
- return actionProperty.const === action;
537
- });
538
- return {
539
- ...schema,
540
- oneOf: filtered,
541
- };
542
- }
543
- function filterSchemaByActions(schema, actions) {
544
- const branches = extractActionBranches(schema);
545
- const filtered = branches.filter((entry) => {
546
- const properties = entry.properties;
547
- if (typeof properties !== "object" || properties === null) {
548
- return false;
549
- }
550
- const actionProperty = properties.action;
551
- if (typeof actionProperty !== "object" || actionProperty === null) {
552
- return false;
553
- }
554
- const actionConst = actionProperty.const;
555
- return typeof actionConst === "string" && actions.has(actionConst);
556
- });
557
- return {
558
- ...schema,
559
- oneOf: filtered,
560
- };
561
- }
562
- function normalizeCommandPath(value) {
563
- return value
564
- .trim()
565
- .toLowerCase()
566
- .split(/\s+/)
567
- .filter((entry) => entry.length > 0)
568
- .join(" ");
569
- }
570
- function normalizeActionNameFromCommand(commandPath) {
571
- return commandPath.replace(/\s+/g, "-");
572
- }
573
- function toOptionalTrimmedString(value) {
574
- if (typeof value !== "string") {
575
- return null;
576
- }
577
- const trimmed = value.trim();
578
- return trimmed.length > 0 ? trimmed : null;
579
- }
580
- function normalizeStringList(values) {
581
- if (!Array.isArray(values)) {
582
- return [];
583
- }
584
- const normalized = [];
585
- const seen = new Set();
586
- for (const value of values) {
587
- const trimmed = toOptionalTrimmedString(value);
588
- if (!trimmed || seen.has(trimmed)) {
589
- continue;
590
- }
591
- seen.add(trimmed);
592
- normalized.push(trimmed);
593
- }
594
- return normalized;
595
- }
596
- function assignExtensionFlagBoolean(contract, key, enabled) {
597
- if (enabled) {
598
- contract[key] = true;
599
- }
600
- }
601
- function normalizeExtensionFlagName(value, kind) {
602
- if (value == null) {
603
- return null;
604
- }
605
- if (typeof value !== "string") {
606
- throw new TypeError("Expected string for extension flag name.");
607
- }
608
- const trimmed = value.trim();
609
- if (trimmed.length === 0) {
610
- return null;
611
- }
612
- if (kind === "long") {
613
- return trimmed.startsWith("--") && trimmed.length > 2 ? trimmed : null;
614
- }
615
- return trimmed.startsWith("-") &&
616
- !trimmed.startsWith("--") &&
617
- trimmed.length > 1
618
- ? trimmed
619
- : null;
620
- }
621
- function toExtensionFlagContract(definition) {
622
- const normalizedLong = normalizeExtensionFlagName(definition.long, "long");
623
- const normalizedShort = normalizeExtensionFlagName(definition.short, "short");
624
- const flag = normalizedLong ?? normalizedShort;
625
- if (!flag) {
626
- return null;
627
- }
628
- const contract = { flag };
629
- if (normalizedShort && normalizedLong) {
630
- contract.short = normalizedShort;
631
- }
632
- assignExtensionFlagBoolean(contract, "required", definition.required === true);
633
- assignExtensionFlagBoolean(contract, "repeatable", definition.repeatable === true);
634
- assignExtensionFlagBoolean(contract, "list", definition.list === true);
635
- const description = toOptionalTrimmedString(definition.description);
636
- if (description) {
637
- contract.description = description;
638
- }
639
- const valueName = toOptionalTrimmedString(definition.value_name);
640
- if (valueName) {
641
- contract.value_name = valueName;
642
- }
643
- const rawValueType = [
644
- toOptionalTrimmedString(definition.value_type),
645
- toOptionalTrimmedString(definition.type),
646
- valueName ? "string" : null,
647
- ].find((candidate) => candidate === "string" ||
648
- candidate === "number" ||
649
- candidate === "boolean");
650
- if (rawValueType) {
651
- contract.value_type = rawValueType;
652
- }
653
- return contract;
654
- }
655
- function collectExtensionFlagContractsByCommand(registrations) {
656
- const grouped = new Map();
657
- for (const registration of registrations) {
658
- const commandPath = normalizeCommandPath(registration.target_command);
659
- if (commandPath.length === 0) {
660
- continue;
661
- }
662
- const bucket = grouped.get(commandPath) ?? {
663
- flags: [],
664
- sources: [],
665
- dedupe: new Set(),
666
- sourceDedupe: new Set(),
667
- };
668
- const sourceKey = `${registration.layer}:${registration.name}`;
669
- if (!bucket.sourceDedupe.has(sourceKey)) {
670
- bucket.sourceDedupe.add(sourceKey);
671
- bucket.sources.push({
672
- layer: registration.layer,
673
- name: registration.name,
674
- });
675
- }
676
- for (const definition of registration.flags) {
677
- const contract = toExtensionFlagContract(definition);
678
- if (!contract) {
679
- continue;
680
- }
681
- const key = `${contract.flag}|${contract.short ?? ""}`;
682
- if (bucket.dedupe.has(key)) {
683
- continue;
684
- }
685
- bucket.dedupe.add(key);
686
- bucket.flags.push(contract);
687
- }
688
- grouped.set(commandPath, bucket);
689
- }
690
- const normalized = new Map();
691
- for (const [commandPath, bucket] of grouped.entries()) {
692
- normalized.set(commandPath, {
693
- flags: bucket.flags,
694
- sources: bucket.sources.sort((left, right) => {
695
- const layerOrder = left.layer.localeCompare(right.layer);
696
- if (layerOrder !== 0) {
697
- return layerOrder;
698
- }
699
- return (left.name ?? "").localeCompare(right.name ?? "");
700
- }),
701
- });
702
- }
703
- return normalized;
704
- }
705
- function collectExtensionCommandContracts(runtimeProbe) {
706
- const flagsByCommand = collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations);
707
- const definitionsByCommand = new Map();
708
- for (const definition of runtimeProbe.commandDefinitions) {
709
- const command = normalizeCommandPath(definition.command);
710
- if (command.length === 0) {
711
- continue;
712
- }
713
- const action = toOptionalTrimmedString(definition.action) ??
714
- normalizeActionNameFromCommand(command);
715
- const args = Array.isArray(definition.arguments)
716
- ? definition.arguments
717
- .map((argument) => {
718
- const name = toOptionalTrimmedString(argument.name);
719
- if (!name) {
720
- return null;
721
- }
722
- return {
723
- name,
724
- required: argument.required === true,
725
- variadic: argument.variadic === true,
726
- description: toOptionalTrimmedString(argument.description),
727
- };
728
- })
729
- .filter((argument) => argument !== null)
730
- : [];
731
- definitionsByCommand.set(command, {
732
- command,
733
- action,
734
- source: {
735
- layer: definition.layer,
736
- name: definition.name,
737
- },
738
- description: toOptionalTrimmedString(definition.description),
739
- intent: toOptionalTrimmedString(definition.intent),
740
- arguments: args,
741
- flags: flagsByCommand.get(command)?.flags ?? [],
742
- examples: normalizeStringList(definition.examples),
743
- failure_hints: normalizeStringList(definition.failure_hints),
744
- });
745
- }
746
- const extensionCommands = new Set();
747
- for (const command of runtimeProbe.handlers) {
748
- extensionCommands.add(normalizeCommandPath(command));
749
- }
750
- for (const command of definitionsByCommand.keys()) {
751
- extensionCommands.add(command);
752
- }
753
- for (const command of flagsByCommand.keys()) {
754
- extensionCommands.add(command);
755
- }
756
- const contracts = [];
757
- for (const command of [...extensionCommands].sort((left, right) => left.localeCompare(right))) {
758
- const definition = definitionsByCommand.get(command);
759
- contracts.push(buildCollectedExtensionCommandContract(command, definition, flagsByCommand.get(command)?.flags ?? []));
760
- }
761
- return contracts;
762
- }
763
- function buildCollectedExtensionCommandContract(command, definition, registeredFlags) {
764
- if (definition) {
765
- return {
766
- ...definition,
767
- flags: definition.flags.length > 0 ? definition.flags : registeredFlags,
768
- };
769
- }
770
- return {
771
- command,
772
- action: normalizeActionNameFromCommand(command),
773
- source: null,
774
- description: null,
775
- intent: null,
776
- arguments: [],
777
- flags: registeredFlags,
778
- examples: [],
779
- failure_hints: [],
780
- };
781
- }
782
- function extensionSchemaPropertyNameFromFlag(flag) {
783
- const normalized = flag.flag.replace(/^-+/, "").trim();
784
- if (normalized.length === 0) {
785
- return null;
786
- }
787
- const camelCased = normalized.replace(/-([a-z0-9])/g, (_match, char) => char.toUpperCase());
788
- const cleaned = camelCased.replace(/[^a-zA-Z0-9]/g, "");
789
- return cleaned.length > 0 ? cleaned : null;
790
- }
791
- function buildExtensionArgumentSchema(argument, action) {
792
- if (argument.variadic) {
793
- return {
794
- type: "array",
795
- items: { type: "string" },
796
- description: argument.description ??
797
- `Variadic argument '${argument.name}' for extension action '${action}'.`,
798
- };
799
- }
800
- return {
801
- type: "string",
802
- description: argument.description ??
803
- `Argument '${argument.name}' for extension action '${action}'.`,
804
- };
805
- }
806
- function buildExtensionFlagSchema(flag, action) {
807
- const valueType = flag.value_type ?? "boolean";
808
- const schemaType = valueType === "boolean"
809
- ? "boolean"
810
- : valueType === "number"
811
- ? ["number", "string"]
812
- : "string";
813
- const acceptsMultipleValues = flag.repeatable === true || flag.list === true;
814
- return {
815
- type: acceptsMultipleValues ? "array" : schemaType,
816
- ...(acceptsMultipleValues ? { items: { type: schemaType } } : {}),
817
- description: flag.description ??
818
- `Extension option '${flag.flag}' for action '${action}'.`,
819
- };
820
- }
821
- function buildExtensionActionSchemaBranch(contract) {
822
- const commands = contract.command
823
- .split("|")
824
- .map((command) => command.trim())
825
- .filter((command) => command.length > 0);
826
- const properties = {
827
- action: {
828
- type: "string",
829
- const: contract.action,
830
- description: contract.intent ??
831
- contract.description ??
832
- `Invoke extension command '${contract.command}'.`,
833
- },
834
- };
835
- const required = ["action"];
836
- for (const argument of contract.arguments) {
837
- properties[argument.name] = buildExtensionArgumentSchema(argument, contract.action);
838
- if (argument.required) {
839
- required.push(argument.name);
840
- }
841
- }
842
- for (const flag of contract.flags) {
843
- const propertyName = extensionSchemaPropertyNameFromFlag(flag);
844
- if (!propertyName || properties[propertyName] !== undefined) {
845
- continue;
846
- }
847
- properties[propertyName] = buildExtensionFlagSchema(flag, contract.action);
848
- if (flag.required === true) {
849
- required.push(propertyName);
850
- }
851
- }
852
- return {
853
- type: "object",
854
- properties,
855
- required,
856
- additionalProperties: true,
857
- "x-extension-source": contract.source,
858
- "x-extension-command": commands[0] ?? contract.command,
859
- "x-extension-commands": commands,
860
- };
861
- }
862
- function mergeExtensionFlagContract(existing, incoming) {
863
- existing.description ??= incoming.description;
864
- existing.value_name ??= incoming.value_name;
865
- existing.value_type ??= incoming.value_type;
866
- if (incoming.required === true) {
867
- existing.required = true;
868
- }
869
- if (incoming.repeatable === true) {
870
- existing.repeatable = true;
871
- }
872
- }
873
- function mergeExtensionContractsByAction(contracts) {
874
- const byAction = new Map();
875
- for (const contract of contracts) {
876
- const existing = byAction.get(contract.action);
877
- if (!existing) {
878
- byAction.set(contract.action, {
879
- ...contract,
880
- flags: [...contract.flags],
881
- examples: [...contract.examples],
882
- failure_hints: [...contract.failure_hints],
883
- });
884
- continue;
885
- }
886
- existing.command = [...new Set([existing.command, contract.command])]
887
- .sort((left, right) => left.localeCompare(right))
888
- .join("|");
889
- existing.arguments =
890
- existing.arguments.length >= contract.arguments.length
891
- ? existing.arguments
892
- : contract.arguments;
893
- const flagKeys = new Set(existing.flags.map((flag) => `${flag.flag}|${flag.short ?? ""}`));
894
- for (const flag of contract.flags) {
895
- const key = `${flag.flag}|${flag.short ?? ""}`;
896
- if (!flagKeys.has(key)) {
897
- flagKeys.add(key);
898
- existing.flags.push(flag);
899
- }
900
- else {
901
- const existingFlag = existing.flags.find((candidate) => `${candidate.flag}|${candidate.short ?? ""}` === key);
902
- if (existingFlag) {
903
- mergeExtensionFlagContract(existingFlag, flag);
904
- }
905
- }
906
- }
907
- existing.examples = [
908
- ...new Set([...existing.examples, ...contract.examples]),
909
- ];
910
- existing.failure_hints = [
911
- ...new Set([...existing.failure_hints, ...contract.failure_hints]),
912
- ];
913
- }
914
- return [...byAction.values()].sort((left, right) => left.action.localeCompare(right.action));
915
- }
916
- /* c8 ignore stop */
917
- async function resolveRuntimeExtensionActionProbe(global, readSettingsFn = readSettings) {
918
- const defaultPolicyState = {
919
- mode: SETTINGS_DEFAULTS.extensions.policy.mode,
920
- trust_mode: SETTINGS_DEFAULTS.extensions.policy.trust_mode,
921
- default_sandbox_profile: SETTINGS_DEFAULTS.extensions.policy.default_sandbox_profile,
922
- };
923
- if (global.noExtensions) {
924
- return {
925
- handlers: new Set(),
926
- disabledReason: "extensions_disabled",
927
- commandDefinitions: [],
928
- flagRegistrations: [],
929
- registrations: null,
930
- policyState: defaultPolicyState,
931
- };
932
- }
933
- const pmRoot = resolvePmRoot(process.cwd(), global.path);
934
- if (!(await pathExists(getSettingsPath(pmRoot)))) {
935
- return {
936
- handlers: new Set(),
937
- disabledReason: null,
938
- commandDefinitions: [],
939
- flagRegistrations: [],
940
- registrations: null,
941
- policyState: defaultPolicyState,
942
- };
943
- }
944
- try {
945
- const settings = await readSettingsFn(pmRoot);
946
- const loadResult = await loadExtensions({
947
- pmRoot,
948
- settings,
949
- cwd: process.cwd(),
950
- noExtensions: false,
951
- });
952
- const activationResult = await activateExtensions({
953
- ...loadResult,
954
- loaded: loadResult.loaded,
955
- });
956
- const handlers = new Set(activationResult.commands.handlers.map((entry) => normalizeCommandPath(entry.command)));
957
- return {
958
- handlers,
959
- disabledReason: null,
960
- commandDefinitions: activationResult.registrations.commands,
961
- flagRegistrations: activationResult.registrations.flags,
962
- registrations: activationResult.registrations,
963
- policyState: {
964
- mode: loadResult.policy.mode,
965
- trust_mode: loadResult.policy.trust_mode,
966
- default_sandbox_profile: loadResult.policy.default_sandbox_profile,
967
- },
968
- };
969
- }
970
- catch {
971
- return {
972
- handlers: new Set(),
973
- disabledReason: "extension_runtime_probe_failed",
974
- commandDefinitions: [],
975
- flagRegistrations: [],
976
- registrations: null,
977
- policyState: defaultPolicyState,
978
- };
979
- }
980
- }
981
- function collectActionContractDescriptors(extensionContracts, options = {}) {
982
- /* c8 ignore start -- package-owned action descriptor permutations are covered in package-install integration suites. */
983
- const descriptors = new Map();
984
- for (const action of PM_TOOL_ACTIONS) {
985
- const packageOwned = PACKAGE_OWNED_ACTIONS.has(action);
986
- if (packageOwned && !options.includePackageOwnedActions) {
987
- continue;
988
- }
989
- const commandPath = resolveActionCommandPath(action);
990
- descriptors.set(action, {
991
- action,
992
- provider: packageOwned ? "extension" : "core",
993
- requires_extension: packageOwned,
994
- command_path: commandPath,
995
- });
996
- }
997
- if (options.includePackageOwnedActions) {
998
- for (const action of PACKAGE_OWNED_ACTIONS) {
999
- if (descriptors.has(action)) {
1000
- continue;
1001
- }
1002
- descriptors.set(action, {
1003
- action,
1004
- provider: "extension",
1005
- requires_extension: true,
1006
- command_path: resolveActionCommandPath(action),
1007
- });
1008
- }
1009
- }
1010
- for (const contract of extensionContracts) {
1011
- if (descriptors.has(contract.action)) {
1012
- continue;
1013
- }
1014
- descriptors.set(contract.action, {
1015
- action: contract.action,
1016
- provider: "extension",
1017
- requires_extension: true,
1018
- command_path: normalizeCommandPath(contract.command),
1019
- });
1020
- }
1021
- return [...descriptors.values()].sort((left, right) => (left.action ?? "").localeCompare(right.action ?? ""));
1022
- /* c8 ignore stop */
1023
- }
1024
- function resolveActionAvailability(descriptor, runtimeProbe) {
1025
- /* c8 ignore start -- runtime extension availability branches are exercised in extension policy integration tests. */
1026
- if (descriptor.provider === "core" && !descriptor.requires_extension) {
1027
- return {
1028
- action: descriptor.action,
1029
- invocable: true,
1030
- available: true,
1031
- requires_extension: false,
1032
- provider: "core",
1033
- disabled_reason: null,
1034
- command_path: descriptor.command_path,
1035
- cli_exposed: descriptor.command_path !== null,
1036
- };
1037
- }
1038
- const commandPaths = descriptor.command_path
1039
- ? splitCommandPathAliases(descriptor.command_path)
1040
- : [];
1041
- const extensionCommandAvailable = commandPaths.some((commandPath) => runtimeProbe.handlers.has(commandPath));
1042
- const optionalPackageHint = commandPaths
1043
- .map((commandPath) => PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(commandPath))
1044
- .find((hint) => typeof hint === "string");
1045
- const invocable = runtimeProbe.disabledReason === null && extensionCommandAvailable;
1046
- return {
1047
- action: descriptor.action,
1048
- invocable,
1049
- available: invocable,
1050
- requires_extension: true,
1051
- provider: "extension",
1052
- disabled_reason: invocable
1053
- ? null
1054
- : (runtimeProbe.disabledReason ??
1055
- (optionalPackageHint
1056
- ? `optional_package_not_installed:${optionalPackageHint}`
1057
- : "extension_command_not_registered")),
1058
- command_path: descriptor.command_path,
1059
- cli_exposed: extensionCommandAvailable,
1060
- policy_state: {
1061
- mode: runtimeProbe.policyState.mode,
1062
- trust_mode: runtimeProbe.policyState.trust_mode,
1063
- default_sandbox_profile: runtimeProbe.policyState.default_sandbox_profile,
1064
- },
1065
- };
1066
- /* c8 ignore stop */
1067
- }
1068
- function resolveCoreCommandFlags(command) {
1069
- return (CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(command) ?? GLOBAL_FLAG_CONTRACTS);
1070
- }
1071
- function isCoreCommandPath(command) {
1072
- if (PACKAGE_OWNED_COMMANDS.has(command)) {
1073
- return false;
1074
- }
1075
- return CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.has(command);
1076
- }
1077
- function normalizeCommandForRuntimeFieldFlags(command) {
1078
- if (LIST_COMMAND_NAMES.has(command)) {
1079
- return "list";
1080
- }
1081
- if (command === "cal") {
1082
- return "calendar";
1083
- }
1084
- if (command === "ctx") {
1085
- return "context";
1086
- }
1087
- if (command === "update-many") {
1088
- return "update_many";
1089
- }
1090
- return command;
1091
- }
1092
- function toRuntimeLongFlagToken(token) {
1093
- const trimmed = token.trim();
1094
- if (!trimmed) {
1095
- return null;
1096
- }
1097
- if (trimmed.startsWith("--")) {
1098
- return trimmed;
1099
- }
1100
- if (trimmed.startsWith("-")) {
1101
- return null;
1102
- }
1103
- return `--${trimmed}`;
1104
- }
1105
- function toRuntimeShortFlagToken(token) {
1106
- const trimmed = token.trim();
1107
- if (!trimmed) {
1108
- return null;
1109
- }
1110
- if (trimmed.startsWith("--")) {
1111
- return null;
1112
- }
1113
- if (trimmed.startsWith("-")) {
1114
- return trimmed;
1115
- }
1116
- return null;
1117
- }
1118
- function buildRuntimeFieldFlagContracts(fieldRegistry) {
1119
- /* c8 ignore start -- runtime-field alias collision branches are validated in schema/runtime flag integration tests. */
1120
- const buckets = new Map();
1121
- for (const definition of fieldRegistry.definitions) {
1122
- const primaryFlag = toRuntimeLongFlagToken(definition.cli_flag);
1123
- if (!primaryFlag) {
1124
- continue;
1125
- }
1126
- const shortAlias = definition.cli_aliases
1127
- .map((alias) => toRuntimeShortFlagToken(alias))
1128
- .find((alias) => alias !== null);
1129
- const longAliases = definition.cli_aliases
1130
- .map((alias) => toRuntimeLongFlagToken(alias))
1131
- .filter((alias) => alias !== null && alias !== primaryFlag);
1132
- for (const command of definition.commands) {
1133
- const bucket = buckets.get(command) ?? {
1134
- flags: [],
1135
- seen: new Set(),
1136
- };
1137
- const primaryContract = shortAlias
1138
- ? { flag: primaryFlag, short: shortAlias }
1139
- : { flag: primaryFlag };
1140
- const primaryKey = `${primaryContract.flag}|${primaryContract.short ?? ""}`;
1141
- if (!bucket.seen.has(primaryKey)) {
1142
- bucket.seen.add(primaryKey);
1143
- bucket.flags.push(primaryContract);
1144
- }
1145
- for (const alias of longAliases) {
1146
- const key = `${alias}|`;
1147
- if (bucket.seen.has(key)) {
1148
- continue;
1149
- }
1150
- bucket.seen.add(key);
1151
- bucket.flags.push({ flag: alias });
1152
- }
1153
- buckets.set(command, bucket);
1154
- }
1155
- }
1156
- const result = new Map();
1157
- for (const [command, bucket] of buckets.entries()) {
1158
- result.set(command, compactFlagAliasContracts(bucket.flags));
1159
- }
1160
- return result;
1161
- /* c8 ignore stop */
1162
- }
1163
- function mergeFlagContracts(primary, secondary) {
1164
- /* c8 ignore start -- flag merge dedupe permutations are covered via command-surface integration fixtures. */
1165
- const merged = [];
1166
- const seen = new Set();
1167
- for (const contract of [...primary, ...secondary]) {
1168
- const key = `${contract.flag}|${contract.short ?? ""}`;
1169
- if (seen.has(key)) {
1170
- continue;
1171
- }
1172
- seen.add(key);
1173
- merged.push(contract);
1174
- }
1175
- return compactFlagAliasContracts(merged);
1176
- /* c8 ignore stop */
1177
- }
1178
- function buildCommandFlagSurface(commands, extensionFlagMap, runtimeFieldFlagMap, includeSemanticMetadata) {
1179
- return commands
1180
- .map((command) => {
1181
- const isCoreCommand = isCoreCommandPath(command);
1182
- const coreFlags = isCoreCommand ? resolveCoreCommandFlags(command) : [];
1183
- const runtimeFlags = runtimeFieldFlagMap.get(normalizeCommandForRuntimeFieldFlags(command)) ?? [];
1184
- const extensionFlags = extensionFlagMap.get(command);
1185
- const coreWithRuntime = mergeFlagContracts(coreFlags, runtimeFlags);
1186
- const flags = mergeFlagContracts(coreWithRuntime, extensionFlags?.flags ?? []);
1187
- const provider = coreFlags.length > 0 && (extensionFlags?.flags.length ?? 0) > 0
1188
- ? "mixed"
1189
- : isCoreCommand
1190
- ? "core"
1191
- : "extension";
1192
- return {
1193
- command,
1194
- flags,
1195
- ...(includeSemanticMetadata
1196
- ? {
1197
- canonical_command: canonicalSummaryCommand(command),
1198
- visibility: resolvePmCommandVisibilityTier(canonicalSummaryCommand(command)),
1199
- positionals: resolvePmCommandPositionalContract(command)?.slots ?? [],
1200
- flag_invocations: enrichCliFlagInvocationContracts(command, flags),
1201
- }
1202
- : {}),
1203
- provider,
1204
- extension_sources: extensionFlags?.sources,
1205
- };
1206
- })
1207
- .sort((left, right) => left.command.localeCompare(right.command));
1208
- }
1209
- /** Build the executable alias projection from a command catalog and alias table. */
1210
- export function buildCommandAliasSurface(commands, aliasContracts = PM_COMMAND_ALIAS_CONTRACTS) {
1211
- const commandSet = new Set(commands);
1212
- const grouped = new Map();
1213
- for (const entry of CANONICAL_COMMAND_ALIASES) {
1214
- const aliases = entry.aliases.filter((alias) => commandSet.has(alias));
1215
- grouped.set(entry.canonical, {
1216
- canonical: entry.canonical,
1217
- aliases,
1218
- contracts: [],
1219
- });
1220
- }
1221
- for (const contract of aliasContracts) {
1222
- if (!commandSet.has(contract.canonical)) {
1223
- continue;
1224
- }
1225
- if (contract.registration === "commander" &&
1226
- !commandSet.has(contract.alias)) {
1227
- continue;
1228
- }
1229
- const entry = grouped.get(contract.canonical) ?? {
1230
- canonical: contract.canonical,
1231
- aliases: [],
1232
- contracts: [],
1233
- };
1234
- if (!entry.aliases.includes(contract.alias)) {
1235
- entry.aliases.push(contract.alias);
1236
- }
1237
- entry.contracts.push(contract);
1238
- grouped.set(contract.canonical, entry);
1239
- }
1240
- return [...grouped.values()]
1241
- .map(({ contracts, ...entry }) => contracts.length === 0 ? entry : { ...entry, contracts })
1242
- .sort((left, right) => left.canonical.localeCompare(right.canonical));
1243
- }
1244
- function buildCommanderAliasSurface() {
1245
- return {
1246
- create_string_options: CREATE_COMMANDER_STRING_OPTION_CONTRACTS,
1247
- create_repeatable_options: CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,
1248
- update_string_options: UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,
1249
- update_repeatable_options: UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,
1250
- list_string_options: LIST_COMMANDER_STRING_OPTION_CONTRACTS,
1251
- search_string_options: SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,
1252
- calendar_string_options: CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,
1253
- context_string_options: CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,
1254
- activity_string_options: ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,
1255
- };
1256
- }
1257
- function resolveCreateRequiredOptionContract(typeDefinition, createMode) {
1258
- /* c8 ignore start -- create-option policy shaping is validated by dedicated create command contract fixtures. */
1259
- const baseRequiredOptions = new Set(["title", "type"]);
1260
- if (createMode === "strict") {
1261
- for (const field of typeDefinition.required_create_fields) {
1262
- baseRequiredOptions.add(field);
1263
- }
1264
- for (const field of typeDefinition.required_create_repeatables) {
1265
- baseRequiredOptions.add(field);
1266
- }
1267
- }
1268
- const policyState = resolveCommandOptionPolicyState(typeDefinition, "create", baseRequiredOptions);
1269
- const requiredOptionKeys = [...new Set(policyState.required)].sort((left, right) => left.localeCompare(right));
1270
- const requiredFlags = [
1271
- ...new Set(requiredOptionKeys.map((option) => commandOptionFlagLabel("create", option))),
1272
- ].sort((left, right) => left.localeCompare(right));
1273
- const requiredTypeOptions = [
1274
- ...new Set(typeDefinition.options
1275
- .filter((option) => option.required === true)
1276
- .map((option) => option.key)),
1277
- ].sort((left, right) => left.localeCompare(right));
1278
- return {
1279
- required_option_keys: requiredOptionKeys,
1280
- required_flags: requiredFlags,
1281
- required_type_options: requiredTypeOptions,
1282
- policy_errors: [...new Set(policyState.errors)].sort((left, right) => left.localeCompare(right)),
1283
- };
1284
- /* c8 ignore stop */
1285
- }
1286
- function buildCreateRequiredOptionContracts(typeRegistry) {
1287
- const byTypeStrict = {};
1288
- const byTypeProgressive = {};
1289
- for (const typeName of [...typeRegistry.types].sort((left, right) => left.localeCompare(right))) {
1290
- const typeDefinition = typeRegistry.by_type[typeName];
1291
- byTypeStrict[typeName] = resolveCreateRequiredOptionContract(typeDefinition, "strict");
1292
- byTypeProgressive[typeName] = resolveCreateRequiredOptionContract(typeDefinition, "progressive");
1293
- }
1294
- return {
1295
- default_create_mode: "strict",
1296
- by_create_mode: {
1297
- strict: {
1298
- by_type: byTypeStrict,
1299
- },
1300
- progressive: {
1301
- by_type: byTypeProgressive,
1302
- },
1303
- },
1304
- };
1305
- }
1306
- function attachCreateRequiredOptionContracts(schema, metadata) {
1307
- const branches = extractActionBranches(schema);
1308
- if (branches.length === 0) {
1309
- return schema;
1310
- }
1311
- let touched = false;
1312
- const enrichedBranches = branches.map((branch) => {
1313
- const properties = branch.properties;
1314
- if (typeof properties !== "object" || properties === null) {
1315
- return branch;
1316
- }
1317
- const actionProperty = properties.action;
1318
- if (typeof actionProperty !== "object" || actionProperty === null) {
1319
- return branch;
1320
- }
1321
- if (actionProperty.const !== "create") {
1322
- return branch;
1323
- }
1324
- touched = true;
1325
- return {
1326
- ...branch,
1327
- "x-create-required-options": metadata,
1328
- };
1329
- });
1330
- if (!touched) {
1331
- return schema;
1332
- }
1333
- return {
1334
- ...schema,
1335
- oneOf: enrichedBranches,
1336
- };
1337
- }
1338
- function resolveContractsSelection(options) {
1339
- const explicitlyScoped = normalizeToken(options.action) !== undefined ||
1340
- normalizeToken(options.command) !== undefined;
1341
- const projectionSelected = options.schemaOnly === true ||
1342
- options.flagsOnly === true ||
1343
- options.availabilityOnly === true;
1344
- const summary = options.summary === true ||
1345
- (options.full !== true &&
1346
- options.runtimeOnly !== true &&
1347
- !explicitlyScoped &&
1348
- !projectionSelected);
1349
- const schemaOnly = options.schemaOnly === true;
1350
- const flagsOnly = options.flagsOnly === true;
1351
- const availabilityOnly = options.availabilityOnly === true;
1352
- const runtimeOnly = options.runtimeOnly === true;
1353
- const fullOutput = options.full === true;
1354
- const selectedAction = normalizeToken(options.action);
1355
- const selectedCommand = normalizeToken(options.command);
1356
- const unfilteredDefaultBriefMode = !summary &&
1357
- !fullOutput &&
1358
- !schemaOnly &&
1359
- !flagsOnly &&
1360
- !availabilityOnly &&
1361
- !selectedAction &&
1362
- !selectedCommand;
1363
- return {
1364
- selectedAction,
1365
- selectedCommand,
1366
- summary,
1367
- schemaOnly,
1368
- flagsOnly,
1369
- availabilityOnly,
1370
- runtimeOnly,
1371
- fullOutput,
1372
- omitUnfilteredSchema: unfilteredDefaultBriefMode,
1373
- omitUnfilteredCommandFlags: unfilteredDefaultBriefMode,
1374
- omitUnfilteredCommanderAliases: unfilteredDefaultBriefMode ||
1375
- (selectedCommand !== undefined && !fullOutput),
1376
- };
1377
- }
1378
- function assertSingleContractsProjection(selection) {
1379
- const projectionFlagsEnabled = [
1380
- selection.summary,
1381
- selection.schemaOnly,
1382
- selection.flagsOnly,
1383
- selection.availabilityOnly,
1384
- ].filter((value) => value).length;
1385
- if (projectionFlagsEnabled > 1) {
1386
- throw new PmCliError("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.", EXIT_CODE.USAGE);
1387
- }
1388
- }
1389
- async function readContractsSettings(pmRoot, readSettingsFn = readSettings) {
1390
- try {
1391
- return await readSettingsFn(pmRoot);
1392
- }
1393
- catch {
1394
- return structuredClone(SETTINGS_DEFAULTS);
1395
- }
1396
- }
1397
- async function resolveContractsRuntimeContext(global, pmRoot) {
1398
- const settings = await readContractsSettings(pmRoot);
1399
- const runtimeProbe = await resolveRuntimeExtensionActionProbe(global);
1400
- const typeRegistry = resolveItemTypeRegistry(settings, runtimeProbe.registrations ?? getActiveExtensionRegistrations());
1401
- const runtimeFieldRegistry = resolveRuntimeFieldRegistry(settings.schema);
1402
- const extensionContracts = collectExtensionCommandContracts(runtimeProbe);
1403
- return {
1404
- settings,
1405
- runtimeProbe,
1406
- typeRegistry,
1407
- statusRegistry: resolveRuntimeStatusRegistry(settings.schema),
1408
- runtimeFieldRegistry,
1409
- runtimeFieldFlagMap: buildRuntimeFieldFlagContracts(runtimeFieldRegistry),
1410
- createRequiredOptionContracts: buildCreateRequiredOptionContracts(typeRegistry),
1411
- extensionContracts,
1412
- mergedExtensionContracts: mergeExtensionContractsByAction(extensionContracts),
1413
- extensionFlagMap: collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations),
1414
- };
1415
- }
1416
- function shouldIncludePackageOwnedActions(selection) {
1417
- return (selection.availabilityOnly &&
1418
- ((selection.selectedAction !== undefined &&
1419
- PACKAGE_OWNED_ACTIONS.has(selection.selectedAction)) ||
1420
- (selection.selectedCommand !== undefined &&
1421
- PACKAGE_OWNED_COMMANDS.has(selection.selectedCommand))));
1422
- }
1423
- function collectContractsActionDescriptors(selection, mergedExtensionContracts) {
1424
- const actionDescriptors = collectActionContractDescriptors(mergedExtensionContracts, {
1425
- includePackageOwnedActions: shouldIncludePackageOwnedActions(selection),
1426
- });
1427
- if (selection.selectedAction === undefined &&
1428
- selection.selectedCommand === undefined) {
1429
- const deprecatedActions = new Set(PM_DEPRECATED_TOOL_ACTIONS);
1430
- return actionDescriptors.filter((descriptor) => !deprecatedActions.has(descriptor.action));
1431
- }
1432
- if (shouldIncludePackageOwnedActions(selection) &&
1433
- selection.selectedCommand !== undefined &&
1434
- PACKAGE_OWNED_COMMANDS.has(selection.selectedCommand) &&
1435
- !actionDescriptors.some((entry) => entry.command_path === selection.selectedCommand)) {
1436
- actionDescriptors.push({
1437
- action: packageOwnedActionForCommand(selection.selectedCommand),
1438
- provider: "extension",
1439
- requires_extension: true,
1440
- command_path: selection.selectedCommand,
1441
- });
1442
- }
1443
- return actionDescriptors;
1444
- }
1445
- function assertKnownContractsAction(selection, actionDescriptors) {
1446
- const actionNames = new Set(actionDescriptors.map((entry) => entry.action));
1447
- if (selection.selectedAction && !actionNames.has(selection.selectedAction)) {
1448
- throw new PmCliError(`Unknown action: "${selection.selectedAction}".`, EXIT_CODE.USAGE);
1449
- }
1450
- }
1451
- function buildContractsCommandCatalog(actionDescriptors, mergedExtensionContracts) {
1452
- return [
1453
- ...new Set([
1454
- ...PM_CORE_COMMAND_NAMES.filter((entry) => !PACKAGE_OWNED_COMMANDS.has(entry)),
1455
- ...[...CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.keys()].filter((entry) => !PACKAGE_OWNED_COMMANDS.has(entry)),
1456
- /* c8 ignore next -- action descriptors always include concrete command paths in command-scoped test fixtures. */
1457
- ...actionDescriptors.flatMap((entry) => entry.command_path ? splitCommandPathAliases(entry.command_path) : []),
1458
- ...mergedExtensionContracts.flatMap((entry) => entry.command.split("|")),
1459
- ]),
1460
- ]
1461
- .map((entry) => normalizeCommandPath(entry))
1462
- .filter((entry) => entry.length > 0)
1463
- .sort((left, right) => left.localeCompare(right));
1464
- }
1465
- function buildCommandNamespaceError(command, namespaceChildren) {
1466
- const displayedNamespaceChildren = namespaceChildren.slice(0, COMMAND_NAMESPACE_DISPLAY_LIMIT);
1467
- const hiddenNamespaceChildCount = namespaceChildren.length - displayedNamespaceChildren.length;
1468
- const displayedChildCommandList = hiddenNamespaceChildCount > 0
1469
- ? `${displayedNamespaceChildren.join(", ")}, and ${hiddenNamespaceChildCount} more`
1470
- : displayedNamespaceChildren.join(", ");
1471
- const fallbackCandidates = namespaceChildren.slice(0, COMMAND_NAMESPACE_FALLBACK_LIMIT);
1472
- const childCommandExamples = namespaceChildren
1473
- .slice(0, 5)
1474
- .map((childCommand) => `pm contracts --command "${childCommand}" --flags-only --json`);
1475
- const suggestedChildCommand = namespaceChildren[0];
1476
- return new PmCliError(`Command "${command}" is a command namespace. Choose a concrete child command: ${displayedChildCommandList}.`, EXIT_CODE.USAGE, {
1477
- code: "command_namespace",
1478
- required: "Use a concrete child command path listed under this namespace.",
1479
- why: "Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",
1480
- examples: childCommandExamples,
1481
- nextSteps: [
1482
- `Retry with a child command, for example: ${childCommandExamples[0]}`,
1483
- ],
1484
- recovery: {
1485
- suggested_retry: `pm contracts --command "${suggestedChildCommand}" --flags-only --json`,
1486
- fallback_candidates: fallbackCandidates.map((childCommand) => ({
1487
- source: "command_namespace",
1488
- command: `pm contracts --command "${childCommand}" --flags-only --json`,
1489
- reason: `Child command under ${command}`,
1490
- })),
1491
- },
1492
- });
1493
- }
1494
- function buildPackageOwnedCommandError(command, packageHint) {
1495
- return new PmCliError(`Unknown command: "${command}". Command "${command}" is provided by the optional "${packageHint}" package. Run "pm install ${packageHint} --project" and retry.`, EXIT_CODE.USAGE, {
1496
- code: "unknown_command",
1497
- required: `Install the optional "${packageHint}" package, or choose a command from pm contracts --flags-only --json.`,
1498
- why: "Command contracts include core commands plus commands registered by active packages and extensions.",
1499
- examples: [
1500
- `pm install ${packageHint} --project`,
1501
- `pm contracts --command ${command} --flags-only --json`,
1502
- ],
1503
- nextSteps: [
1504
- `Install the optional package first: pm install ${packageHint} --project`,
1505
- ],
1506
- recovery: {
1507
- suggested_retry: `pm install ${packageHint} --project`,
1508
- },
1509
- });
1510
- }
1511
- function buildUnknownCommandError(command) {
1512
- return new PmCliError(`Unknown command: "${command}".`, EXIT_CODE.USAGE, {
1513
- code: "unknown_command",
1514
- required: "Use a command path listed by pm contracts --flags-only --json.",
1515
- why: "Command contracts are generated from the active core, package, and extension command registry.",
1516
- examples: ["pm contracts --flags-only --json", "pm --help"],
1517
- nextSteps: [
1518
- "Verify spelling and active packages/extensions, then rerun with a known command path.",
1519
- ],
1520
- recovery: {
1521
- suggested_retry: "pm contracts --flags-only --json",
1522
- },
1523
- });
1524
- }
1525
- function assertKnownContractsCommand(selection, commandCatalog) {
1526
- if (!selection.selectedCommand) {
1527
- return;
1528
- }
1529
- const commandNames = new Set(commandCatalog);
1530
- if (commandNames.has(selection.selectedCommand)) {
1531
- return;
1532
- }
1533
- const namespaceChildren = commandCatalog.filter((command) => command.startsWith(`${selection.selectedCommand} `));
1534
- if (namespaceChildren.length > 0) {
1535
- throw buildCommandNamespaceError(selection.selectedCommand, namespaceChildren);
1536
- }
1537
- const packageHint = PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(selection.selectedCommand);
1538
- if (packageHint) {
1539
- throw buildPackageOwnedCommandError(selection.selectedCommand, packageHint);
1540
- }
1541
- throw buildUnknownCommandError(selection.selectedCommand);
1542
- }
1543
- function resolveContractsActionContext(selection, runtime) {
1544
- const actionDescriptors = collectContractsActionDescriptors(selection, runtime.mergedExtensionContracts);
1545
- assertKnownContractsAction(selection, actionDescriptors);
1546
- const commandCatalog = buildContractsCommandCatalog(actionDescriptors, runtime.mergedExtensionContracts);
1547
- assertKnownContractsCommand(selection, commandCatalog);
1548
- const selectedPackageOwnedAction = selection.selectedCommand
1549
- ? PACKAGE_OWNED_COMMAND_ACTIONS.get(selection.selectedCommand)
1550
- : undefined;
1551
- const commandScopedDescriptors = selection.selectedCommand
1552
- ? actionDescriptors.filter((descriptor) => selectedPackageOwnedAction
1553
- ? descriptor.action === selectedPackageOwnedAction
1554
- : actionDescriptorMatchesSelectedCommand(descriptor, selection.selectedCommand))
1555
- : actionDescriptors;
1556
- if (selection.selectedCommand &&
1557
- selection.selectedAction &&
1558
- !commandScopedDescriptors.some((descriptor) => descriptor.action === selection.selectedAction)) {
1559
- throw new PmCliError(`Action "${selection.selectedAction}" is not mapped to command "${selection.selectedCommand}" in contracts output.`, EXIT_CODE.USAGE);
1560
- }
1561
- const scopedActionDescriptors = selection.selectedAction
1562
- ? commandScopedDescriptors.filter((descriptor) => descriptor.action === selection.selectedAction)
1563
- : commandScopedDescriptors;
1564
- const allActionAvailability = [
1565
- ...new Map(scopedActionDescriptors
1566
- .map((descriptor) => resolveActionAvailability(descriptor, runtime.runtimeProbe))
1567
- .map((entry) => [
1568
- /* c8 ignore next -- keyed dedupe by action|path is covered by runtime policy integration tests. */
1569
- selectedPackageOwnedAction
1570
- ? entry.action
1571
- : `${entry.action}|${entry.command_path ?? ""}`,
1572
- entry,
1573
- ])).values(),
1574
- ];
1575
- const actionAvailability = selection.runtimeOnly &&
1576
- !selection.selectedAction &&
1577
- !selection.availabilityOnly
1578
- ? allActionAvailability.filter((entry) => entry.invocable)
1579
- : allActionAvailability;
1580
- return {
1581
- actionDescriptors,
1582
- commandCatalog,
1583
- commandScopedDescriptors,
1584
- scopedActionDescriptors,
1585
- selectedPackageOwnedAction,
1586
- actionAvailability,
1587
- actions: [...new Set(actionAvailability.map((entry) => entry.action))],
1588
- };
1589
- }
1590
- function buildSchemaActionSet(schema) {
1591
- return new Set(extractActionBranches(schema)
1592
- .map((entry) => {
1593
- const properties = entry.properties;
1594
- /* c8 ignore start -- PM_TOOL_PARAMETERS_SCHEMA action branches always carry a properties object; the property-less fallback is validated in schema-level contract tests. */
1595
- if (typeof properties !== "object" || properties === null) {
1596
- return null;
1597
- }
1598
- /* c8 ignore stop */
1599
- const actionProperty = properties.action;
1600
- /* c8 ignore start -- PM_TOOL_PARAMETERS_SCHEMA action branches always carry an action object; the missing-action fallback is validated in schema-level contract tests. */
1601
- if (typeof actionProperty !== "object" || actionProperty === null) {
1602
- return null;
1603
- }
1604
- /* c8 ignore stop */
1605
- const actionConst = actionProperty.const;
1606
- /* c8 ignore start -- the action.const is always a string in PM_TOOL_PARAMETERS_SCHEMA; the non-string fallback is validated in schema-level contract tests. */
1607
- return typeof actionConst === "string" ? actionConst : null;
1608
- /* c8 ignore stop */
1609
- })
1610
- .filter((entry) => entry !== null));
1611
- }
1612
- function buildMergedContractsSchema(mergedExtensionContracts) {
1613
- const schema = PM_TOOL_PARAMETERS_SCHEMA;
1614
- const schemaBranches = extractActionBranches(schema);
1615
- const schemaActionSet = buildSchemaActionSet(schema);
1616
- const extensionBranches = mergedExtensionContracts
1617
- .filter((contract) => !schemaActionSet.has(contract.action))
1618
- .map((contract) => buildExtensionActionSchemaBranch(contract));
1619
- return extensionBranches.length > 0
1620
- ? {
1621
- ...schema,
1622
- oneOf: [...schemaBranches, ...extensionBranches],
1623
- }
1624
- : schema;
1625
- }
1626
- function filterContractsSchema(selection, actionContext, mergedSchema) {
1627
- const descriptorActionSet = new Set(actionContext.actionDescriptors.map((descriptor) => descriptor.action));
1628
- const filteredSchema = selection.selectedAction
1629
- ? filterSchemaByAction(mergedSchema, selection.selectedAction)
1630
- : selection.selectedCommand
1631
- ? filterSchemaByActions(mergedSchema, new Set(actionContext.scopedActionDescriptors.map((descriptor) => descriptor.action)))
1632
- : filterSchemaByActions(mergedSchema, descriptorActionSet);
1633
- return selection.runtimeOnly && !selection.selectedAction
1634
- ? filterSchemaByActions(filteredSchema, new Set(actionContext.actions))
1635
- : filteredSchema;
1636
- }
1637
- function resolveContractsSchemaContext(selection, runtime, actionContext) {
1638
- const mergedSchema = buildMergedContractsSchema(runtime.mergedExtensionContracts);
1639
- const includeSchemaSurface = !selection.flagsOnly && !selection.availabilityOnly;
1640
- const filteredSchema = includeSchemaSurface
1641
- ? attachCreateRequiredOptionContracts(filterContractsSchema(selection, actionContext, mergedSchema), runtime.createRequiredOptionContracts)
1642
- : filterContractsSchema(selection, actionContext, mergedSchema);
1643
- return { mergedSchema, filteredSchema };
1644
- }
1645
- function resolveContractsCommands(selection, actionContext) {
1646
- if (selection.selectedCommand !== undefined) {
1647
- return [selection.selectedCommand];
1648
- }
1649
- if (selection.selectedAction) {
1650
- return resolveScopedCommandsFromActionDescriptors(actionContext.scopedActionDescriptors, actionContext.commandCatalog);
1651
- }
1652
- return actionContext.commandCatalog;
1653
- }
1654
- function resolveOutputCommands(selection, commands) {
1655
- if (selection.selectedCommand !== undefined ||
1656
- selection.selectedAction !== undefined) {
1657
- return commands;
1658
- }
1659
- const hiddenAliases = new Set(PM_COMMAND_ALIAS_CONTRACTS.filter((contract) => contract.hidden && contract.lifecycle === "deprecated").map((contract) => contract.alias));
1660
- return commands.filter((command) => !hiddenAliases.has(command));
1661
- }
1662
- function canonicalSummaryCommand(command) {
1663
- const rootCommand = command.split(" ")[0];
1664
- if (rootCommand.startsWith("list-"))
1665
- return "list";
1666
- if (rootCommand.startsWith("history-"))
1667
- return "history";
1668
- return COMMAND_ALIAS_TO_CANONICAL.get(rootCommand) ?? rootCommand;
1669
- }
1670
- const COMMAND_OPERATION_INTENTS = new Map([
1671
- ["activate", "Activate"],
1672
- ["adopt", "Adopt"],
1673
- ["adopt-all", "Adopt all"],
1674
- ["catalog", "Catalog"],
1675
- ["complete", "Complete"],
1676
- ["create", "Create"],
1677
- ["deactivate", "Deactivate"],
1678
- ["delete", "Delete"],
1679
- ["describe", "Describe"],
1680
- ["doctor", "Diagnose"],
1681
- ["explore", "Explore"],
1682
- ["init", "Initialize"],
1683
- ["inspect", "Inspect"],
1684
- ["install", "Install"],
1685
- ["list", "List"],
1686
- ["manage", "Manage"],
1687
- ["migrate", "Migrate"],
1688
- ["mutate", "Mutate"],
1689
- ["reload", "Reload"],
1690
- ["restore", "Restore"],
1691
- ["run", "Run"],
1692
- ["snapshot", "Manage snapshots for"],
1693
- ["uninstall", "Uninstall"],
1694
- ["upgrade", "Upgrade"],
1695
- ]);
1696
- const COMMAND_INTENT_SUBJECT_OVERRIDES = new Map([
1697
- ["extension adopt-all", "extensions"],
1698
- ["package adopt-all", "packages"],
1699
- ["workspace snapshot list", "workspace snapshots"],
1700
- ]);
1701
- function summarizeCommandIntent(command, extensionContracts) {
1702
- const declared = COMMAND_INTENTS.get(command) ??
1703
- (command.includes(" ")
1704
- ? undefined
1705
- : COMMAND_INTENTS.get(canonicalSummaryCommand(command)));
1706
- if (declared !== undefined) {
1707
- return { intent: declared, intent_source: "command" };
1708
- }
1709
- const extensionContract = extensionContracts.find((contract) => splitCommandPathAliases(contract.command).includes(command));
1710
- if (extensionContract?.intent !== null &&
1711
- extensionContract?.intent !== undefined) {
1712
- return { intent: extensionContract.intent, intent_source: "command" };
1713
- }
1714
- if (extensionContract?.description !== null &&
1715
- extensionContract?.description !== undefined) {
1716
- return {
1717
- intent: extensionContract.description,
1718
- intent_source: "description",
1719
- };
1720
- }
1721
- const tokens = command.split(" ");
1722
- const operation = tokens.at(-1);
1723
- const subject = tokens.slice(0, -1).join(" ");
1724
- const verb = COMMAND_OPERATION_INTENTS.get(operation);
1725
- const intentSubject = COMMAND_INTENT_SUBJECT_OVERRIDES.get(command) ?? subject;
1726
- return {
1727
- intent: verb === undefined || subject.length === 0
1728
- ? `Run ${command}.`
1729
- : `${verb} ${intentSubject}.`,
1730
- intent_source: "generated",
1731
- };
1732
- }
1733
- function buildCommandSummarySurface(commands, extensionContracts = [], options = {}) {
1734
- const includeFormatBudgets = options.includeFormatBudgets ?? true;
1735
- const includeIntentProvenance = options.includeIntentProvenance ?? true;
1736
- return [...new Set(commands.map(normalizeCommandPath))]
1737
- .filter((command) => command.length > 0)
1738
- .sort((left, right) => left.localeCompare(right))
1739
- .map((command) => {
1740
- const budget = resolvePmCommandOutputBudget(command, {
1741
- generateFallback: true,
1742
- });
1743
- const rootCommand = command.split(" ")[0];
1744
- const canonicalRoot = COMMAND_ALIAS_TO_CANONICAL.get(rootCommand) ??
1745
- (rootCommand.startsWith("list-")
1746
- ? "list"
1747
- : rootCommand.startsWith("history-")
1748
- ? "history"
1749
- : rootCommand);
1750
- const availableFlags = new Set([
1751
- ...resolveCoreCommandFlags(command).map((contract) => contract.flag),
1752
- ...extensionContracts
1753
- .filter((contract) => splitCommandPathAliases(contract.command).includes(command))
1754
- .flatMap((contract) => contract.flags.map((flag) => flag.flag)),
1755
- ]);
1756
- const flags = (AGENT_BOOTSTRAP_FLAGS.get(command) ??
1757
- AGENT_BOOTSTRAP_FLAGS.get(canonicalRoot) ??
1758
- AGENT_BOUNDED_FLAG_PRIORITY).filter((flag) => availableFlags.has(flag));
1759
- const intent = summarizeCommandIntent(command, extensionContracts);
1760
- return {
1761
- command,
1762
- intent: intent.intent,
1763
- ...(includeIntentProvenance || intent.intent_source !== "command"
1764
- ? { intent_source: intent.intent_source }
1765
- : {}),
1766
- ...(flags.length > 0 ? { flags } : {}),
1767
- default_max_estimated_tokens: budget.default_max_estimated_tokens,
1768
- ...(includeFormatBudgets
1769
- ? {
1770
- default_max_estimated_tokens_by_format: {
1771
- ...budget.default_max_estimated_tokens_by_format,
1772
- },
1773
- }
1774
- : {}),
1775
- };
1776
- });
1777
- }
1778
- function buildCommandOutputContracts(commands) {
1779
- return commands.map((command) => ({
1780
- budget: resolvePmCommandOutputBudget(command, {
1781
- generateFallback: true,
1782
- }),
1783
- envelope: resolvePmCommandOutputEnvelope(command),
1784
- }));
1785
- }
1786
- function buildCommandExitContractGroups(commands) {
1787
- const groups = new Map();
1788
- for (const command of commands) {
1789
- const contract = resolvePmCommandExitContract(command);
1790
- const exitCodes = contract === undefined
1791
- ? [
1792
- EXIT_CODE.SUCCESS,
1793
- EXIT_CODE.GENERIC_FAILURE,
1794
- EXIT_CODE.USAGE,
1795
- EXIT_CODE.NOT_FOUND,
1796
- EXIT_CODE.CONFLICT,
1797
- EXIT_CODE.DEPENDENCY_FAILED,
1798
- ]
1799
- : contract.exit_codes;
1800
- const key = exitCodes.join(",");
1801
- const group = groups.get(key) ?? { commands: [], exit_codes: exitCodes };
1802
- group.commands.push(command);
1803
- groups.set(key, group);
1804
- }
1805
- return [...groups.values()];
1806
- }
1807
- function resolveExtensionCommandContracts(selection, runtime, outputCommands) {
1808
- if (selection.selectedCommand) {
1809
- return runtime.extensionContracts.filter((entry) => splitCommandPathAliases(entry.command).includes(selection.selectedCommand));
1810
- }
1811
- if (selection.selectedAction) {
1812
- const outputCommandSet = new Set(outputCommands);
1813
- return runtime.extensionContracts.filter((entry) => splitCommandPathAliases(entry.command).some((command) => outputCommandSet.has(command)));
1814
- }
1815
- return runtime.extensionContracts;
1816
- }
1817
- function createContractsResult(selection, schemaContext, actionContext, outputCommands) {
1818
- return {
1819
- schema_version:
1820
- /* c8 ignore next -- schema version/id fallbacks are exercised by schema snapshot tests. */
1821
- typeof schemaContext.mergedSchema["x-schema-version"] === "string"
1822
- ? schemaContext.mergedSchema["x-schema-version"]
1823
- : null,
1824
- schema_id:
1825
- /* c8 ignore next -- schema version/id fallbacks are exercised by schema snapshot tests. */
1826
- typeof schemaContext.mergedSchema.$id === "string"
1827
- ? schemaContext.mergedSchema.$id
1828
- : null,
1829
- selected: {
1830
- action: selection.selectedAction ?? null,
1831
- command: selection.selectedCommand ?? null,
1832
- summary: selection.summary,
1833
- schema_only: selection.schemaOnly,
1834
- flags_only: selection.flagsOnly,
1835
- availability_only: selection.availabilityOnly,
1836
- runtime_only: selection.runtimeOnly,
1837
- command_scoped: selection.selectedCommand !== undefined,
1838
- },
1839
- commands: selection.summary ? [] : outputCommands,
1840
- ...(!selection.summary && !selection.flagsOnly
1841
- ? {
1842
- actions: actionContext.actions,
1843
- action_availability: actionContext.actionAvailability,
1844
- }
1845
- : {}),
1846
- };
1847
- }
1848
- function attachRuntimeContractsResult(result, runtime, selection) {
1849
- const selectedCommand = selection.selectedCommand;
1850
- result.runtime_schema = {
1851
- statuses: runtime.statusRegistry.definitions.map((definition) => definition.id),
1852
- open_status: runtime.statusRegistry.open_status,
1853
- close_status: runtime.statusRegistry.close_status,
1854
- canceled_status: runtime.statusRegistry.canceled_status,
1855
- types: [...runtime.typeRegistry.types],
1856
- fields_by_command: Object.fromEntries([...runtime.runtimeFieldRegistry.command_to_fields.entries()]
1857
- .filter(([command]) => selectedCommand === undefined || command === selectedCommand)
1858
- .map(([command, definitions]) => [
1859
- command,
1860
- [
1861
- ...new Set(definitions.map((definition) => `--${definition.cli_flag}`)),
1862
- ].sort((left, right) => left.localeCompare(right)),
1863
- ])),
1864
- };
1865
- if (selectedCommand !== undefined && !selection.fullOutput) {
1866
- return;
1867
- }
1868
- result.extension_contracts = {
1869
- capabilities: [...PM_EXTENSION_CAPABILITY_CONTRACTS],
1870
- services: [...PM_EXTENSION_SERVICE_NAME_CONTRACTS],
1871
- policy_modes: [...PM_EXTENSION_POLICY_MODE_CONTRACTS],
1872
- policy_mode_scope: "extensions.policy.mode",
1873
- policy_surfaces: [...PM_EXTENSION_POLICY_SURFACE_CONTRACTS],
1874
- trust_modes: [...PM_EXTENSION_TRUST_MODE_CONTRACTS],
1875
- trust_mode_scope: "extensions.policy.trust_mode",
1876
- sandbox_profiles: [...PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS],
1877
- manifest_versions: [1, 2],
1878
- compatibility: {
1879
- current: "v2",
1880
- previous: ["v1"],
1881
- breaking_strategy: "versioned_breaking",
1882
- },
1883
- };
1884
- result.governance_contracts = {
1885
- ownership_enforcement_modes: [...GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES],
1886
- create_modes: [...GOVERNANCE_CREATE_MODE_DEFAULT_VALUES],
1887
- close_validation_modes: [...GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES],
1888
- workflow_enforcement_modes: [...GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES],
1889
- };
1890
- result.relationship_kind_contracts = [
1891
- ...BUILTIN_RELATIONSHIP_KINDS,
1892
- ...(runtime.runtimeProbe.registrations?.relationship_kinds ?? []).flatMap((registration) => registration.definitions),
1893
- ]
1894
- .sort((left, right) => left.kind.localeCompare(right.kind))
1895
- .map((definition) => ({
1896
- canonical: definition.kind,
1897
- aliases: [...(definition.aliases ?? [])],
1898
- ...(definition.inverse === undefined
1899
- ? {}
1900
- : { inverse: definition.inverse }),
1901
- ordering: definition.ordering,
1902
- hierarchy: definition.hierarchy,
1903
- }));
1904
- }
1905
- function attachSchemaContractsResult(result, selection, schemaContext, extensionCommandContracts) {
1906
- if (selection.flagsOnly || selection.availabilityOnly) {
1907
- return;
1908
- }
1909
- if (!selection.omitUnfilteredSchema) {
1910
- result.schema = schemaContext.filteredSchema;
1911
- result.extension_commands = extensionCommandContracts;
1912
- return;
1913
- }
1914
- result.schema_omitted_reason = "unfiltered_default_brief";
1915
- result.extension_commands = extensionCommandContracts;
1916
- }
1917
- function attachFlagContractsResult(result, selection, runtime, outputCommands, commandAliases) {
1918
- if (selection.schemaOnly || selection.availabilityOnly) {
1919
- return;
1920
- }
1921
- if (!selection.omitUnfilteredCommandFlags) {
1922
- result.command_flags = buildCommandFlagSurface(outputCommands, runtime.extensionFlagMap, runtime.runtimeFieldFlagMap, selection.selectedCommand !== undefined);
1923
- const commandSet = new Set(outputCommands);
1924
- result.list_projections = Object.entries(LIST_COMMAND_DEFAULT_PROJECTIONS)
1925
- .filter(([command]) => commandSet.has(command))
1926
- .map(([command, defaultProjection]) => ({
1927
- command,
1928
- default: defaultProjection,
1929
- brief_fields: [...BRIEF_LIST_FIELDS],
1930
- compact_fields: [...DEFAULT_COMPACT_LIST_FIELDS],
1931
- }));
1932
- }
1933
- else {
1934
- result.command_flags_omitted_reason = "unfiltered_default_brief";
1935
- }
1936
- result.command_aliases = commandAliases;
1937
- }
1938
- function attachCommanderAliasContractsResult(result, selection) {
1939
- if (selection.schemaOnly ||
1940
- selection.flagsOnly ||
1941
- selection.availabilityOnly) {
1942
- return;
1943
- }
1944
- if (!selection.omitUnfilteredCommanderAliases) {
1945
- result.commander_aliases = buildCommanderAliasSurface();
1946
- return;
1947
- }
1948
- result.commander_aliases_omitted_reason = selection.selectedCommand
1949
- ? "command_scoped"
1950
- : "unfiltered_default_brief";
1951
- }
1952
- /** Attach the compact agent-facing command semantics shared by summary and full projections. */
1953
- function attachAgentCommandContractsResult(result, outputCommands, extensionCommandContracts, options) {
1954
- result.command_summaries = buildCommandSummarySurface(outputCommands, extensionCommandContracts, {
1955
- includeFormatBudgets: options.includeFormatBudgets,
1956
- includeIntentProvenance: options.includeIntentProvenance,
1957
- });
1958
- result.output_policy = {
1959
- token_estimate: "ceil(utf8_bytes / 4)",
1960
- degradation_ladder: [...PM_OUTPUT_DEGRADATION_STEPS],
1961
- allows_unbounded_opt_out: true,
1962
- };
1963
- result.output_projection_contracts = {
1964
- global_ladder_field: "output_policy.degradation_ladder",
1965
- global_ladder_scope: "union_not_per_command",
1966
- discovery: "pm contracts --command <command> --summary",
1967
- ...(options.includeProjectionModeMatrix
1968
- ? {
1969
- commands: [...new Set(outputCommands.map(normalizeCommandPath))]
1970
- .filter((command) => resolveReadOutputSurface(command) !== undefined)
1971
- .sort((left, right) => left.localeCompare(right))
1972
- .map((command) => ({
1973
- command,
1974
- modes: [...readOutputIncludeModeOptions(command).keys()],
1975
- })),
1976
- }
1977
- : {}),
1978
- };
1979
- result.grammar_contracts = {
1980
- nouns: PM_CLI_GRAMMAR_CONTRACT.nouns,
1981
- shared_verbs: PM_CLI_GRAMMAR_CONTRACT.shared_verbs,
1982
- scope_before_verb: PM_CLI_GRAMMAR_CONTRACT.scope_before_verb,
1983
- visible_top_level_ceiling: PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling,
1984
- ceiling_raise_requires_pm_item: PM_CLI_GRAMMAR_CONTRACT.ceiling_raise_requires_pm_item,
1985
- positional_shape_budget: PM_CLI_GRAMMAR_CONTRACT.positional_shape_budget,
1986
- positional_shape_count: new Set(PM_COMMAND_POSITIONAL_CONTRACTS.map(({ slots }) => positionalShapeKey(slots))).size,
1987
- positional_action_count: PM_POSITIONAL_ACTION_CONTRACTS.length,
1988
- positional_action_parents: [
1989
- ...new Set(PM_POSITIONAL_ACTION_CONTRACTS.map(({ parent }) => parent)),
1990
- ].sort((left, right) => left.localeCompare(right)),
1991
- ...(options.includePositionalSignatures
1992
- ? { positional_signatures: PM_COMMAND_POSITIONAL_CONTRACTS }
1993
- : {}),
1994
- };
1995
- }
1996
- /** Implements run contracts for the public runtime surface of this module. */
1997
- export async function runContracts(options, global) {
1998
- const selection = resolveContractsSelection(options);
1999
- assertSingleContractsProjection(selection);
2000
- const pmRoot = resolvePmRoot(process.cwd(), global.path);
2001
- const runtime = await resolveContractsRuntimeContext(global, pmRoot);
2002
- const actionContext = resolveContractsActionContext(selection, runtime);
2003
- const schemaContext = resolveContractsSchemaContext(selection, runtime, actionContext);
2004
- const commands = resolveContractsCommands(selection, actionContext);
2005
- const outputCommands = resolveOutputCommands(selection, commands);
2006
- const result = createContractsResult(selection, schemaContext, actionContext, outputCommands);
2007
- const extensionCommandContracts = resolveExtensionCommandContracts(selection, runtime, outputCommands);
2008
- const includeCommandDetails = selection.fullOutput || selection.selectedCommand !== undefined;
2009
- if (selection.summary || selection.fullOutput) {
2010
- attachAgentCommandContractsResult(result, outputCommands, extensionCommandContracts, {
2011
- includeFormatBudgets: includeCommandDetails,
2012
- includeIntentProvenance: includeCommandDetails,
2013
- includePositionalSignatures: includeCommandDetails,
2014
- includeProjectionModeMatrix: includeCommandDetails,
2015
- });
2016
- }
2017
- if (selection.summary) {
2018
- return result;
2019
- }
2020
- const commandAliases = buildCommandAliasSurface(actionContext.commandCatalog);
2021
- if (!(selection.flagsOnly && !selection.fullOutput)) {
2022
- attachRuntimeContractsResult(result, runtime, selection);
2023
- }
2024
- attachSchemaContractsResult(result, selection, schemaContext, extensionCommandContracts);
2025
- attachFlagContractsResult(result, selection, runtime, outputCommands, commandAliases);
2026
- attachCommanderAliasContractsResult(result, selection);
2027
- if (selection.selectedCommand === "assurance" || selection.fullOutput) {
2028
- result.assurance_contracts = {
2029
- measurement_source_kinds: [...ASSURANCE_MEASUREMENT_SOURCE_KINDS],
2030
- gate_triggers: [...ASSURANCE_GATE_TRIGGERS],
2031
- };
2032
- }
2033
- if (selection.fullOutput && result.grammar_contracts) {
2034
- result.grammar_contracts.destinations = PM_COMMAND_DESTINATION_CONTRACTS;
2035
- }
2036
- // pm-4os2: snapshot the static MCP tool surface in the full projection so
2037
- // `pnpm contracts:check` (CI static gate) fails on unintended inputSchema
2038
- // drift in src/mcp/tool-definitions.ts.
2039
- if (selection.fullOutput &&
2040
- !selection.schemaOnly &&
2041
- !selection.flagsOnly &&
2042
- !selection.availabilityOnly) {
2043
- result.mcp_tools = buildMcpToolContracts();
2044
- result.context_intents = getActiveContextIntentContracts();
2045
- result.read_output_dimensions = PM_READ_OUTPUT_SURFACE_CONTRACTS;
2046
- result.error_codes = PM_ERROR_CODE_CATALOG;
2047
- result.command_output_contracts =
2048
- buildCommandOutputContracts(outputCommands);
2049
- result.diagnostic_output_contracts = PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS;
2050
- result.command_exit_contracts = {
2051
- vocabulary: PM_COMMAND_EXIT_OUTCOME_CONTRACTS,
2052
- command_sets: buildCommandExitContractGroups(outputCommands),
2053
- };
2054
- }
2055
- return result;
2056
- }
2057
- /** Public contract for test only contracts command, shared by SDK and presentation-layer consumers. */
2058
- export const _testOnlyContractsCommand = {
2059
- actionDescriptorMatchesSelectedCommand,
2060
- attachCreateRequiredOptionContracts,
2061
- buildExtensionActionSchemaBranch,
2062
- buildCommandSummarySurface,
2063
- buildCommandOutputContracts,
2064
- buildCommandExitContractGroups,
2065
- buildRuntimeFieldFlagContracts,
2066
- collectActionContractDescriptors,
2067
- collectExtensionCommandContracts,
2068
- collectExtensionFlagContractsByCommand,
2069
- extractActionBranches,
2070
- extensionSchemaPropertyNameFromFlag,
2071
- filterSchemaByAction,
2072
- filterSchemaByActions,
2073
- isCoreCommandPath,
2074
- mergeExtensionContractsByAction,
2075
- normalizeExtensionFlagName,
2076
- normalizeActionNameFromCommand,
2077
- normalizeCommandForRuntimeFieldFlags,
2078
- normalizeCommandPath,
2079
- packageOwnedActionForCommand,
2080
- readContractsSettings,
2081
- resolveActionCommandPath,
2082
- resolveActionAvailability,
2083
- resolveCoreCommandFlags,
2084
- resolveRuntimeExtensionActionProbe,
2085
- resolveScopedCommandsFromActionDescriptors,
2086
- splitCommandPathAliases,
2087
- toRuntimeLongFlagToken,
2088
- toRuntimeShortFlagToken,
2089
- };
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]="5fbd5bc2-6f35-5f7e-b357-7c16e6991787")}catch(e2){}})();import{EXIT_CODE,SETTINGS_DEFAULTS,PmCliError,activateExtensions,getActiveExtensionRegistrations,loadExtensions,pathExists,commandOptionFlagLabel,resolveCommandOptionPolicyState,resolveItemTypeRegistry,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,getSettingsPath,resolvePmRoot,readSettings}from"../runtime-primitives.js";import{buildMcpToolContracts}from"../../mcp/tool-definitions.js";import{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,ACTIVITY_FLAG_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_OUTPUT_DEGRADATION_STEPS,PLAN_FLAG_CONTRACTS,PM_CORE_COMMAND_NAMES,PM_DEPRECATED_TOOL_ACTIONS,PM_TOOL_ACTIONS,PM_TOOL_PARAMETERS_SCHEMA,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,PROFILE_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,EVAL_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,NEXT_FLAG_CONTRACTS,SEARCH_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,compactFlagAliasContracts,PM_COMMAND_ALIAS_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,resolvePmCommandOutputBudget}from"../cli-contracts.js";import{PM_HISTORY_COMMAND_ALIASES,resolvePmHistoryOperation}from"./command-aliases.js";import{PM_POSITIONAL_ACTION_FLAG_CONTRACTS}from"./flag-contracts.js";import{GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES,GOVERNANCE_CREATE_MODE_DEFAULT_VALUES,GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES,GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES}from"../../types.js";import{BRIEF_LIST_FIELDS,DEFAULT_COMPACT_LIST_FIELDS,LIST_COMMAND_DEFAULT_PROJECTIONS}from"../query/list.js";import{getActiveContextIntentContracts}from"../context-intent-contracts.js";import{readOutputIncludeModeOptions,resolveReadOutputSurface,PM_READ_OUTPUT_SURFACE_CONTRACTS}from"../read-output-contracts.js";import{enrichCliFlagInvocationContracts}from"../flag-invocation-contracts.js";import{resolvePmCommandVisibilityTier}from"../agent-capability-contracts.js";import{PM_ERROR_CODE_CATALOG}from"../generated-error-code-catalog.js";import{resolvePmCommandOutputEnvelope}from"../output-contracts.js";import{PM_COMMAND_EXIT_OUTCOME_CONTRACTS,resolvePmCommandExitContract}from"./command-exit-contracts.js";import{BUILTIN_RELATIONSHIP_KINDS}from"../relationship-kinds/contract.js";import{ASSURANCE_GATE_TRIGGERS,ASSURANCE_MEASUREMENT_SOURCE_KINDS}from"../governance/assurance.js";import{PM_CLI_GRAMMAR_CONTRACT,PM_COMMAND_DESTINATION_CONTRACTS,PM_COMMAND_POSITIONAL_CONTRACTS,PM_POSITIONAL_ACTION_CONTRACTS,positionalShapeKey,resolvePmCommandPositionalContract}from"./grammar-contracts.js";const AGENT_BOOTSTRAP_FLAGS=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]);const AGENT_BOUNDED_FLAG_PRIORITY=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"];const LIST_COMMAND_NAMES=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]);const PACKAGE_OWNED_ACTIONS=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]);const PACKAGE_OWNED_COMMANDS=new Set(["cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]);const PACKAGE_OWNED_COMMAND_INSTALL_HINTS=new Map([["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]);const PACKAGE_OWNED_ACTION_COMMAND_PATHS=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]);const PACKAGE_OWNED_COMMAND_ACTIONS=new Map([...PACKAGE_OWNED_ACTION_COMMAND_PATHS.entries()].flatMap(([action,commandPaths])=>splitCommandPathAliases(commandPaths).map(commandPath=>[commandPath,action])));const CANONICAL_COMMAND_ALIASES=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}];const COMMAND_ALIAS_TO_CANONICAL=new Map(CANONICAL_COMMAND_ALIASES.flatMap(entry=>entry.aliases.map(alias=>[alias,entry.canonical])));const COMMAND_NAMESPACE_DISPLAY_LIMIT=10;const COMMAND_NAMESPACE_FALLBACK_LIMIT=20;const COMMAND_INTENTS=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]);const EXTENSION_LIFECYCLE_FLAG_CONTRACTS=[["init",EXTENSION_INIT_FLAG_CONTRACTS],["install",EXTENSION_INSTALL_FLAG_CONTRACTS],["uninstall",EXTENSION_UNINSTALL_FLAG_CONTRACTS],["explore",EXTENSION_EXPLORE_FLAG_CONTRACTS],["manage",EXTENSION_MANAGE_FLAG_CONTRACTS],["describe",EXTENSION_DESCRIBE_FLAG_CONTRACTS],["reload",EXTENSION_RELOAD_FLAG_CONTRACTS],["doctor",EXTENSION_DOCTOR_FLAG_CONTRACTS],["catalog",EXTENSION_CATALOG_FLAG_CONTRACTS],["adopt",EXTENSION_ADOPT_FLAG_CONTRACTS],["adopt-all",EXTENSION_ADOPT_ALL_FLAG_CONTRACTS],["activate",EXTENSION_ACTIVATE_FLAG_CONTRACTS],["deactivate",EXTENSION_DEACTIVATE_FLAG_CONTRACTS],["migrate",EXTENSION_MIGRATE_FLAG_CONTRACTS]];const PACKAGE_LIFECYCLE_FLAG_CONTRACTS=[...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand,flags])=>subcommand==="init"?[subcommand,PACKAGE_INIT_FLAG_CONTRACTS]:[subcommand,flags]),["upgrade",UPGRADE_FLAG_CONTRACTS]];const CORE_COMMAND_FLAG_CONTRACT_ENTRIES=[...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand,flags])=>[`extension ${subcommand}`,flags]),...PACKAGE_LIFECYCLE_FLAG_CONTRACTS.flatMap(([subcommand,flags])=>[[`package ${subcommand}`,flags],[`packages ${subcommand}`,flags]]),["init",INIT_FLAG_CONTRACTS],["config",CONFIG_FLAG_CONTRACTS],["extension",EXTENSION_FLAG_CONTRACTS],["package",PACKAGE_FLAG_CONTRACTS],["packages",PACKAGE_FLAG_CONTRACTS],["install",INSTALL_FLAG_CONTRACTS],["create",CREATE_FLAG_CONTRACTS],["item mutate",ITEM_MUTATE_FLAG_CONTRACTS],["item complete",ITEM_COMPLETE_FLAG_CONTRACTS],["item reopen",ITEM_REOPEN_FLAG_CONTRACTS],["copy",COPY_FLAG_CONTRACTS],["focus",FOCUS_FLAG_CONTRACTS],["update",UPDATE_FLAG_CONTRACTS],["update-many",UPDATE_MANY_FLAG_CONTRACTS],["upgrade",UPGRADE_FLAG_CONTRACTS],["calendar",CALENDAR_FLAG_CONTRACTS],["cal",CALENDAR_FLAG_CONTRACTS],["context",CONTEXT_FLAG_CONTRACTS],["ctx",CONTEXT_FLAG_CONTRACTS],["get",GET_FLAG_CONTRACTS],["search",SEARCH_FLAG_CONTRACTS],["eval",EVAL_FLAG_CONTRACTS],["workspace",WORKSPACE_FLAG_CONTRACTS],["workspace position",[]],["workspace snapshot",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot create",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot list",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot inspect",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot restore",WORKSPACE_FLAG_CONTRACTS],["workspace snapshot delete",WORKSPACE_FLAG_CONTRACTS],["next",NEXT_FLAG_CONTRACTS],["aggregate",AGGREGATE_FLAG_CONTRACTS],["deps",DEPS_FLAG_CONTRACTS],["graph",GRAPH_FLAG_CONTRACTS],["guide",GUIDE_FLAG_CONTRACTS],["reindex",REINDEX_FLAG_CONTRACTS],["history",HISTORY_FLAG_CONTRACTS],["history-compact",HISTORY_COMPACT_FLAG_CONTRACTS],["history-redact",HISTORY_REDACT_FLAG_CONTRACTS],["history-repair",HISTORY_REPAIR_FLAG_CONTRACTS],["history-author-acknowledge",HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS],["merge",MERGE_FLAG_CONTRACTS],["schema",SCHEMA_FLAG_CONTRACTS],["profile",PROFILE_FLAG_CONTRACTS],["plan",PLAN_FLAG_CONTRACTS],["restore",RESTORE_FLAG_CONTRACTS],["delete",DELETE_FLAG_CONTRACTS],["close",CLOSE_FLAG_CONTRACTS],["close-many",CLOSE_MANY_FLAG_CONTRACTS],["append",APPEND_FLAG_CONTRACTS],["claim",CLAIM_FLAG_CONTRACTS],["release",RELEASE_FLAG_CONTRACTS],["start-task",START_TASK_FLAG_CONTRACTS],["pause-task",PAUSE_TASK_FLAG_CONTRACTS],["close-task",CLOSE_TASK_FLAG_CONTRACTS],["comments",COMMENTS_FLAG_CONTRACTS],["notes",NOTES_FLAG_CONTRACTS],["learnings",LEARNINGS_FLAG_CONTRACTS],["files",FILES_FLAG_CONTRACTS],["docs",DOCS_FLAG_CONTRACTS],["test",TEST_FLAG_CONTRACTS],["test-all",TEST_ALL_FLAG_CONTRACTS],["telemetry",TELEMETRY_FLAG_CONTRACTS],["test-runs",TEST_RUNS_FLAG_CONTRACTS],["gc",GC_FLAG_CONTRACTS],["stats",STATS_FLAG_CONTRACTS],["duplicates",DUPLICATES_FLAG_CONTRACTS],["validate",VALIDATE_FLAG_CONTRACTS],["health",HEALTH_FLAG_CONTRACTS],["assurance",ASSURANCE_FLAG_CONTRACTS],...PM_POSITIONAL_ACTION_FLAG_CONTRACTS,["contracts",CONTRACTS_FLAG_CONTRACTS],["completion",COMPLETION_FLAG_CONTRACTS],["activity",ACTIVITY_FLAG_CONTRACTS],...[...LIST_COMMAND_NAMES].map(command=>[command,LIST_FILTER_FLAG_CONTRACTS])];const CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND=new Map(CORE_COMMAND_FLAG_CONTRACT_ENTRIES);for(const{alias,canonical}of PM_HISTORY_COMMAND_ALIASES){CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.set(canonical,CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(alias))}function packageOwnedActionForCommand(command){const exactAction=PACKAGE_OWNED_COMMAND_ACTIONS.get(command);if(exactAction){return exactAction}if(command.startsWith("test-runs ")){return`test-runs-${command.slice("test-runs ".length)}`}if(command.startsWith("templates ")){return`templates-${command.slice("templates ".length)}`}return command}function resolveActionCommandPath(action){const historyAlias=PM_HISTORY_COMMAND_ALIASES.find(contract=>contract.alias===action);if(historyAlias)return`${historyAlias.canonical}|${historyAlias.alias}`;if(PM_CORE_COMMAND_NAMES.includes(action)){return normalizeCommandPath(action)}if(action.startsWith("extension-")){return normalizeCommandPath(`extension ${action.slice("extension-".length)}`)}if(action.startsWith("package-")){return normalizeCommandPath(`package ${action.slice("package-".length)}`)}if(action.startsWith("item-")){return normalizeCommandPath(`item ${action.slice("item-".length)}`)}if(action.startsWith("test-runs-")){return normalizeCommandPath(`test-runs ${action.slice("test-runs-".length)}`)}if(action.startsWith("templates-")){return normalizeCommandPath(`templates ${action.slice("templates-".length)}`)}if(PACKAGE_OWNED_ACTIONS.has(action)){return PACKAGE_OWNED_ACTION_COMMAND_PATHS.get(action)??normalizeCommandPath(action)}return null}function actionDescriptorMatchesSelectedCommand(descriptor,selectedCommand){const historyOperation=resolvePmHistoryOperation(selectedCommand);if(historyOperation!==selectedCommand)return descriptor.action===historyOperation;if(descriptor.command_path===null){return false}return splitCommandPathAliases(descriptor.command_path).some(commandPath=>{if(commandPath===selectedCommand){return true}return commandPath.startsWith(`${selectedCommand} `)||selectedCommand.startsWith(`${commandPath} `)})}function splitCommandPathAliases(commandPath){return commandPath.split("|").map(entry=>normalizeCommandPath(entry)).filter(entry=>entry.length>0)}function resolveScopedCommandsFromActionDescriptors(descriptors,commandCatalog){const commandSet=new Set(commandCatalog);const scoped=new Set;for(const descriptor of descriptors){if(!descriptor.command_path){continue}for(const commandPath of splitCommandPathAliases(descriptor.command_path)){const tokens=commandPath.split(" ").filter(entry=>entry.length>0);if(tokens.length===0){continue}for(let end=tokens.length;end>0;end-=1){const candidate=tokens.slice(0,end).join(" ");if(!commandSet.has(candidate)){continue}scoped.add(candidate);break}}}return[...scoped].sort((left,right)=>left.localeCompare(right))}function normalizeToken(value){if(typeof value!=="string"){return void 0}const trimmed=value.trim().toLowerCase();return trimmed.length>0?trimmed:void 0}function extractActionBranches(schema){const oneOf=schema.oneOf;if(!Array.isArray(oneOf)){return[]}return oneOf.filter(entry=>typeof entry==="object"&&entry!==null)}function filterSchemaByAction(schema,action){if(!action){return{...schema}}const branches=extractActionBranches(schema);const filtered=branches.filter(entry=>{const properties=entry.properties;if(typeof properties!=="object"||properties===null){return false}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return false}return actionProperty.const===action});return{...schema,oneOf:filtered}}function filterSchemaByActions(schema,actions){const branches=extractActionBranches(schema);const filtered=branches.filter(entry=>{const properties=entry.properties;if(typeof properties!=="object"||properties===null){return false}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return false}const actionConst=actionProperty.const;return typeof actionConst==="string"&&actions.has(actionConst)});return{...schema,oneOf:filtered}}function normalizeCommandPath(value){return value.trim().toLowerCase().split(/\s+/).filter(entry=>entry.length>0).join(" ")}function normalizeActionNameFromCommand(commandPath){return commandPath.replace(/\s+/g,"-")}function toOptionalTrimmedString(value){if(typeof value!=="string"){return null}const trimmed=value.trim();return trimmed.length>0?trimmed:null}function normalizeStringList(values){if(!Array.isArray(values)){return[]}const normalized=[];const seen=new Set;for(const value of values){const trimmed=toOptionalTrimmedString(value);if(!trimmed||seen.has(trimmed)){continue}seen.add(trimmed);normalized.push(trimmed)}return normalized}function assignExtensionFlagBoolean(contract,key,enabled){if(enabled){contract[key]=true}}function normalizeExtensionFlagName(value,kind){if(value==null){return null}if(typeof value!=="string"){throw new TypeError("Expected string for extension flag name.")}const trimmed=value.trim();if(trimmed.length===0){return null}if(kind==="long"){return trimmed.startsWith("--")&&trimmed.length>2?trimmed:null}return trimmed.startsWith("-")&&!trimmed.startsWith("--")&&trimmed.length>1?trimmed:null}function toExtensionFlagContract(definition){const normalizedLong=normalizeExtensionFlagName(definition.long,"long");const normalizedShort=normalizeExtensionFlagName(definition.short,"short");const flag=normalizedLong??normalizedShort;if(!flag){return null}const contract={flag};if(normalizedShort&&normalizedLong){contract.short=normalizedShort}assignExtensionFlagBoolean(contract,"required",definition.required===true);assignExtensionFlagBoolean(contract,"repeatable",definition.repeatable===true);assignExtensionFlagBoolean(contract,"list",definition.list===true);const description=toOptionalTrimmedString(definition.description);if(description){contract.description=description}const valueName=toOptionalTrimmedString(definition.value_name);if(valueName){contract.value_name=valueName}const rawValueType=[toOptionalTrimmedString(definition.value_type),toOptionalTrimmedString(definition.type),valueName?"string":null].find(candidate=>candidate==="string"||candidate==="number"||candidate==="boolean");if(rawValueType){contract.value_type=rawValueType}return contract}function collectExtensionFlagContractsByCommand(registrations){const grouped=new Map;for(const registration of registrations){const commandPath=normalizeCommandPath(registration.target_command);if(commandPath.length===0){continue}const bucket=grouped.get(commandPath)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set};const sourceKey=`${registration.layer}:${registration.name}`;if(!bucket.sourceDedupe.has(sourceKey)){bucket.sourceDedupe.add(sourceKey);bucket.sources.push({layer:registration.layer,name:registration.name})}for(const definition of registration.flags){const contract=toExtensionFlagContract(definition);if(!contract){continue}const key=`${contract.flag}|${contract.short??""}`;if(bucket.dedupe.has(key)){continue}bucket.dedupe.add(key);bucket.flags.push(contract)}grouped.set(commandPath,bucket)}const normalized=new Map;for(const[commandPath,bucket]of grouped.entries()){normalized.set(commandPath,{flags:bucket.flags,sources:bucket.sources.sort((left,right)=>{const layerOrder=left.layer.localeCompare(right.layer);if(layerOrder!==0){return layerOrder}return(left.name??"").localeCompare(right.name??"")})})}return normalized}function collectExtensionCommandContracts(runtimeProbe){const flagsByCommand=collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations);const definitionsByCommand=new Map;for(const definition of runtimeProbe.commandDefinitions){const command=normalizeCommandPath(definition.command);if(command.length===0){continue}const action=toOptionalTrimmedString(definition.action)??normalizeActionNameFromCommand(command);const args=Array.isArray(definition.arguments)?definition.arguments.map(argument=>{const name=toOptionalTrimmedString(argument.name);if(!name){return null}return{name,required:argument.required===true,variadic:argument.variadic===true,description:toOptionalTrimmedString(argument.description)}}).filter(argument=>argument!==null):[];definitionsByCommand.set(command,{command,action,source:{layer:definition.layer,name:definition.name},description:toOptionalTrimmedString(definition.description),intent:toOptionalTrimmedString(definition.intent),arguments:args,flags:flagsByCommand.get(command)?.flags??[],examples:normalizeStringList(definition.examples),failure_hints:normalizeStringList(definition.failure_hints)})}const extensionCommands=new Set;for(const command of runtimeProbe.handlers){extensionCommands.add(normalizeCommandPath(command))}for(const command of definitionsByCommand.keys()){extensionCommands.add(command)}for(const command of flagsByCommand.keys()){extensionCommands.add(command)}const contracts=[];for(const command of[...extensionCommands].sort((left,right)=>left.localeCompare(right))){const definition=definitionsByCommand.get(command);contracts.push(buildCollectedExtensionCommandContract(command,definition,flagsByCommand.get(command)?.flags??[]))}return contracts}function buildCollectedExtensionCommandContract(command,definition,registeredFlags){if(definition){return{...definition,flags:definition.flags.length>0?definition.flags:registeredFlags}}return{command,action:normalizeActionNameFromCommand(command),source:null,description:null,intent:null,arguments:[],flags:registeredFlags,examples:[],failure_hints:[]}}function extensionSchemaPropertyNameFromFlag(flag){const normalized=flag.flag.replace(/^-+/,"").trim();if(normalized.length===0){return null}const camelCased=normalized.replace(/-([a-z0-9])/g,(_match,char)=>char.toUpperCase());const cleaned=camelCased.replace(/[^a-zA-Z0-9]/g,"");return cleaned.length>0?cleaned:null}function buildExtensionArgumentSchema(argument,action){if(argument.variadic){return{type:"array",items:{type:"string"},description:argument.description??`Variadic argument '${argument.name}' for extension action '${action}'.`}}return{type:"string",description:argument.description??`Argument '${argument.name}' for extension action '${action}'.`}}function buildExtensionFlagSchema(flag,action){const valueType=flag.value_type??"boolean";const schemaType=valueType==="boolean"?"boolean":valueType==="number"?["number","string"]:"string";const acceptsMultipleValues=flag.repeatable===true||flag.list===true;return{type:acceptsMultipleValues?"array":schemaType,...acceptsMultipleValues?{items:{type:schemaType}}:{},description:flag.description??`Extension option '${flag.flag}' for action '${action}'.`}}function buildExtensionActionSchemaBranch(contract){const commands=contract.command.split("|").map(command=>command.trim()).filter(command=>command.length>0);const properties={action:{type:"string",const:contract.action,description:contract.intent??contract.description??`Invoke extension command '${contract.command}'.`}};const required=["action"];for(const argument of contract.arguments){properties[argument.name]=buildExtensionArgumentSchema(argument,contract.action);if(argument.required){required.push(argument.name)}}for(const flag of contract.flags){const propertyName=extensionSchemaPropertyNameFromFlag(flag);if(!propertyName||properties[propertyName]!==void 0){continue}properties[propertyName]=buildExtensionFlagSchema(flag,contract.action);if(flag.required===true){required.push(propertyName)}}return{type:"object",properties,required,additionalProperties:true,"x-extension-source":contract.source,"x-extension-command":commands[0]??contract.command,"x-extension-commands":commands}}function mergeExtensionFlagContract(existing,incoming){existing.description??=incoming.description;existing.value_name??=incoming.value_name;existing.value_type??=incoming.value_type;if(incoming.required===true){existing.required=true}if(incoming.repeatable===true){existing.repeatable=true}}function mergeExtensionContractsByAction(contracts){const byAction=new Map;for(const contract of contracts){const existing=byAction.get(contract.action);if(!existing){byAction.set(contract.action,{...contract,flags:[...contract.flags],examples:[...contract.examples],failure_hints:[...contract.failure_hints]});continue}existing.command=[...new Set([existing.command,contract.command])].sort((left,right)=>left.localeCompare(right)).join("|");existing.arguments=existing.arguments.length>=contract.arguments.length?existing.arguments:contract.arguments;const flagKeys=new Set(existing.flags.map(flag=>`${flag.flag}|${flag.short??""}`));for(const flag of contract.flags){const key=`${flag.flag}|${flag.short??""}`;if(!flagKeys.has(key)){flagKeys.add(key);existing.flags.push(flag)}else{const existingFlag=existing.flags.find(candidate=>`${candidate.flag}|${candidate.short??""}`===key);if(existingFlag){mergeExtensionFlagContract(existingFlag,flag)}}}existing.examples=[...new Set([...existing.examples,...contract.examples])];existing.failure_hints=[...new Set([...existing.failure_hints,...contract.failure_hints])]}return[...byAction.values()].sort((left,right)=>left.action.localeCompare(right.action))}async function resolveRuntimeExtensionActionProbe(global2,readSettingsFn=readSettings){const defaultPolicyState={mode:SETTINGS_DEFAULTS.extensions.policy.mode,trust_mode:SETTINGS_DEFAULTS.extensions.policy.trust_mode,default_sandbox_profile:SETTINGS_DEFAULTS.extensions.policy.default_sandbox_profile};if(global2.noExtensions){return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:defaultPolicyState}}const pmRoot=resolvePmRoot(process.cwd(),global2.path);if(!await pathExists(getSettingsPath(pmRoot))){return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:defaultPolicyState}}try{const settings=await readSettingsFn(pmRoot);const loadResult=await loadExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:false});const activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});const handlers=new Set(activationResult.commands.handlers.map(entry=>normalizeCommandPath(entry.command)));return{handlers,disabledReason:null,commandDefinitions:activationResult.registrations.commands,flagRegistrations:activationResult.registrations.flags,registrations:activationResult.registrations,policyState:{mode:loadResult.policy.mode,trust_mode:loadResult.policy.trust_mode,default_sandbox_profile:loadResult.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:defaultPolicyState}}}function collectActionContractDescriptors(extensionContracts,options={}){const descriptors=new Map;for(const action of PM_TOOL_ACTIONS){const packageOwned=PACKAGE_OWNED_ACTIONS.has(action);if(packageOwned&&!options.includePackageOwnedActions){continue}const commandPath=resolveActionCommandPath(action);descriptors.set(action,{action,provider:packageOwned?"extension":"core",requires_extension:packageOwned,command_path:commandPath})}if(options.includePackageOwnedActions){for(const action of PACKAGE_OWNED_ACTIONS){if(descriptors.has(action)){continue}descriptors.set(action,{action,provider:"extension",requires_extension:true,command_path:resolveActionCommandPath(action)})}}for(const contract of extensionContracts){if(descriptors.has(contract.action)){continue}descriptors.set(contract.action,{action:contract.action,provider:"extension",requires_extension:true,command_path:normalizeCommandPath(contract.command)})}return[...descriptors.values()].sort((left,right)=>(left.action??"").localeCompare(right.action??""))}function resolveActionAvailability(descriptor,runtimeProbe){if(descriptor.provider==="core"&&!descriptor.requires_extension){return{action:descriptor.action,invocable:true,available:true,requires_extension:false,provider:"core",disabled_reason:null,command_path:descriptor.command_path,cli_exposed:descriptor.command_path!==null}}const commandPaths=descriptor.command_path?splitCommandPathAliases(descriptor.command_path):[];const extensionCommandAvailable=commandPaths.some(commandPath=>runtimeProbe.handlers.has(commandPath));const optionalPackageHint=commandPaths.map(commandPath=>PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(commandPath)).find(hint=>typeof hint==="string");const invocable=runtimeProbe.disabledReason===null&&extensionCommandAvailable;return{action:descriptor.action,invocable,available:invocable,requires_extension:true,provider:"extension",disabled_reason:invocable?null:runtimeProbe.disabledReason??(optionalPackageHint?`optional_package_not_installed:${optionalPackageHint}`:"extension_command_not_registered"),command_path:descriptor.command_path,cli_exposed:extensionCommandAvailable,policy_state:{mode:runtimeProbe.policyState.mode,trust_mode:runtimeProbe.policyState.trust_mode,default_sandbox_profile:runtimeProbe.policyState.default_sandbox_profile}}}function resolveCoreCommandFlags(command){return CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(command)??GLOBAL_FLAG_CONTRACTS}function isCoreCommandPath(command){if(PACKAGE_OWNED_COMMANDS.has(command)){return false}return CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.has(command)}function normalizeCommandForRuntimeFieldFlags(command){if(LIST_COMMAND_NAMES.has(command)){return"list"}if(command==="cal"){return"calendar"}if(command==="ctx"){return"context"}if(command==="update-many"){return"update_many"}return command}function toRuntimeLongFlagToken(token){const trimmed=token.trim();if(!trimmed){return null}if(trimmed.startsWith("--")){return trimmed}if(trimmed.startsWith("-")){return null}return`--${trimmed}`}function toRuntimeShortFlagToken(token){const trimmed=token.trim();if(!trimmed){return null}if(trimmed.startsWith("--")){return null}if(trimmed.startsWith("-")){return trimmed}return null}function buildRuntimeFieldFlagContracts(fieldRegistry){const buckets=new Map;for(const definition of fieldRegistry.definitions){const primaryFlag=toRuntimeLongFlagToken(definition.cli_flag);if(!primaryFlag){continue}const shortAlias=definition.cli_aliases.map(alias=>toRuntimeShortFlagToken(alias)).find(alias=>alias!==null);const longAliases=definition.cli_aliases.map(alias=>toRuntimeLongFlagToken(alias)).filter(alias=>alias!==null&&alias!==primaryFlag);for(const command of definition.commands){const bucket=buckets.get(command)??{flags:[],seen:new Set};const primaryContract=shortAlias?{flag:primaryFlag,short:shortAlias}:{flag:primaryFlag};const primaryKey=`${primaryContract.flag}|${primaryContract.short??""}`;if(!bucket.seen.has(primaryKey)){bucket.seen.add(primaryKey);bucket.flags.push(primaryContract)}for(const alias of longAliases){const key=`${alias}|`;if(bucket.seen.has(key)){continue}bucket.seen.add(key);bucket.flags.push({flag:alias})}buckets.set(command,bucket)}}const result=new Map;for(const[command,bucket]of buckets.entries()){result.set(command,compactFlagAliasContracts(bucket.flags))}return result}function mergeFlagContracts(primary,secondary){const merged=[];const seen=new Set;for(const contract of[...primary,...secondary]){const key=`${contract.flag}|${contract.short??""}`;if(seen.has(key)){continue}seen.add(key);merged.push(contract)}return compactFlagAliasContracts(merged)}function buildCommandFlagSurface(commands,extensionFlagMap,runtimeFieldFlagMap,includeSemanticMetadata){return commands.map(command=>{const isCoreCommand=isCoreCommandPath(command);const coreFlags=isCoreCommand?resolveCoreCommandFlags(command):[];const runtimeFlags=runtimeFieldFlagMap.get(normalizeCommandForRuntimeFieldFlags(command))??[];const extensionFlags=extensionFlagMap.get(command);const coreWithRuntime=mergeFlagContracts(coreFlags,runtimeFlags);const flags=mergeFlagContracts(coreWithRuntime,extensionFlags?.flags??[]);const provider=coreFlags.length>0&&(extensionFlags?.flags.length??0)>0?"mixed":isCoreCommand?"core":"extension";return{command,flags,...includeSemanticMetadata?{canonical_command:canonicalSummaryCommand(command),visibility:resolvePmCommandVisibilityTier(canonicalSummaryCommand(command)),positionals:resolvePmCommandPositionalContract(command)?.slots??[],flag_invocations:enrichCliFlagInvocationContracts(command,flags)}:{},provider,extension_sources:extensionFlags?.sources}}).sort((left,right)=>left.command.localeCompare(right.command))}function buildCommandAliasSurface(commands,aliasContracts=PM_COMMAND_ALIAS_CONTRACTS){const commandSet=new Set(commands);const grouped=new Map;for(const entry of CANONICAL_COMMAND_ALIASES){const aliases=entry.aliases.filter(alias=>commandSet.has(alias));grouped.set(entry.canonical,{canonical:entry.canonical,aliases,contracts:[]})}for(const contract of aliasContracts){if(!commandSet.has(contract.canonical)){continue}if(contract.registration==="commander"&&!commandSet.has(contract.alias)){continue}const entry=grouped.get(contract.canonical)??{canonical:contract.canonical,aliases:[],contracts:[]};if(!entry.aliases.includes(contract.alias)){entry.aliases.push(contract.alias)}entry.contracts.push(contract);grouped.set(contract.canonical,entry)}return[...grouped.values()].map(({contracts,...entry})=>contracts.length===0?entry:{...entry,contracts}).sort((left,right)=>left.canonical.localeCompare(right.canonical))}function buildCommanderAliasSurface(){return{create_string_options:CREATE_COMMANDER_STRING_OPTION_CONTRACTS,create_repeatable_options:CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,update_string_options:UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,update_repeatable_options:UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,list_string_options:LIST_COMMANDER_STRING_OPTION_CONTRACTS,search_string_options:SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,calendar_string_options:CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,context_string_options:CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,activity_string_options:ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS}}function resolveCreateRequiredOptionContract(typeDefinition,createMode){const baseRequiredOptions=new Set(["title","type"]);if(createMode==="strict"){for(const field of typeDefinition.required_create_fields){baseRequiredOptions.add(field)}for(const field of typeDefinition.required_create_repeatables){baseRequiredOptions.add(field)}}const policyState=resolveCommandOptionPolicyState(typeDefinition,"create",baseRequiredOptions);const requiredOptionKeys=[...new Set(policyState.required)].sort((left,right)=>left.localeCompare(right));const requiredFlags=[...new Set(requiredOptionKeys.map(option=>commandOptionFlagLabel("create",option)))].sort((left,right)=>left.localeCompare(right));const requiredTypeOptions=[...new Set(typeDefinition.options.filter(option=>option.required===true).map(option=>option.key))].sort((left,right)=>left.localeCompare(right));return{required_option_keys:requiredOptionKeys,required_flags:requiredFlags,required_type_options:requiredTypeOptions,policy_errors:[...new Set(policyState.errors)].sort((left,right)=>left.localeCompare(right))}}function buildCreateRequiredOptionContracts(typeRegistry){const byTypeStrict={};const byTypeProgressive={};for(const typeName of[...typeRegistry.types].sort((left,right)=>left.localeCompare(right))){const typeDefinition=typeRegistry.by_type[typeName];byTypeStrict[typeName]=resolveCreateRequiredOptionContract(typeDefinition,"strict");byTypeProgressive[typeName]=resolveCreateRequiredOptionContract(typeDefinition,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:byTypeStrict},progressive:{by_type:byTypeProgressive}}}}function attachCreateRequiredOptionContracts(schema,metadata){const branches=extractActionBranches(schema);if(branches.length===0){return schema}let touched=false;const enrichedBranches=branches.map(branch=>{const properties=branch.properties;if(typeof properties!=="object"||properties===null){return branch}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return branch}if(actionProperty.const!=="create"){return branch}touched=true;return{...branch,"x-create-required-options":metadata}});if(!touched){return schema}return{...schema,oneOf:enrichedBranches}}function resolveContractsSelection(options){const explicitlyScoped=normalizeToken(options.action)!==void 0||normalizeToken(options.command)!==void 0;const projectionSelected=options.schemaOnly===true||options.flagsOnly===true||options.availabilityOnly===true;const summary=options.summary===true||options.full!==true&&options.runtimeOnly!==true&&!explicitlyScoped&&!projectionSelected;const schemaOnly=options.schemaOnly===true;const flagsOnly=options.flagsOnly===true;const availabilityOnly=options.availabilityOnly===true;const runtimeOnly=options.runtimeOnly===true;const fullOutput=options.full===true;const selectedAction=normalizeToken(options.action);const selectedCommand=normalizeToken(options.command);const unfilteredDefaultBriefMode=!summary&&!fullOutput&&!schemaOnly&&!flagsOnly&&!availabilityOnly&&!selectedAction&&!selectedCommand;return{selectedAction,selectedCommand,summary,schemaOnly,flagsOnly,availabilityOnly,runtimeOnly,fullOutput,omitUnfilteredSchema:unfilteredDefaultBriefMode,omitUnfilteredCommandFlags:unfilteredDefaultBriefMode,omitUnfilteredCommanderAliases:unfilteredDefaultBriefMode||selectedCommand!==void 0&&!fullOutput}}function assertSingleContractsProjection(selection){const projectionFlagsEnabled=[selection.summary,selection.schemaOnly,selection.flagsOnly,selection.availabilityOnly].filter(value=>value).length;if(projectionFlagsEnabled>1){throw new PmCliError("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",EXIT_CODE.USAGE)}}async function readContractsSettings(pmRoot,readSettingsFn=readSettings){try{return await readSettingsFn(pmRoot)}catch{return structuredClone(SETTINGS_DEFAULTS)}}async function resolveContractsRuntimeContext(global2,pmRoot){const settings=await readContractsSettings(pmRoot);const runtimeProbe=await resolveRuntimeExtensionActionProbe(global2);const typeRegistry=resolveItemTypeRegistry(settings,runtimeProbe.registrations??getActiveExtensionRegistrations());const runtimeFieldRegistry=resolveRuntimeFieldRegistry(settings.schema);const extensionContracts=collectExtensionCommandContracts(runtimeProbe);return{settings,runtimeProbe,typeRegistry,statusRegistry:resolveRuntimeStatusRegistry(settings.schema),runtimeFieldRegistry,runtimeFieldFlagMap:buildRuntimeFieldFlagContracts(runtimeFieldRegistry),createRequiredOptionContracts:buildCreateRequiredOptionContracts(typeRegistry),extensionContracts,mergedExtensionContracts:mergeExtensionContractsByAction(extensionContracts),extensionFlagMap:collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations)}}function shouldIncludePackageOwnedActions(selection){return selection.availabilityOnly&&(selection.selectedAction!==void 0&&PACKAGE_OWNED_ACTIONS.has(selection.selectedAction)||selection.selectedCommand!==void 0&&PACKAGE_OWNED_COMMANDS.has(selection.selectedCommand))}function collectContractsActionDescriptors(selection,mergedExtensionContracts){const actionDescriptors=collectActionContractDescriptors(mergedExtensionContracts,{includePackageOwnedActions:shouldIncludePackageOwnedActions(selection)});if(selection.selectedAction===void 0&&selection.selectedCommand===void 0){const deprecatedActions=new Set(PM_DEPRECATED_TOOL_ACTIONS);return actionDescriptors.filter(descriptor=>!deprecatedActions.has(descriptor.action))}if(shouldIncludePackageOwnedActions(selection)&&selection.selectedCommand!==void 0&&PACKAGE_OWNED_COMMANDS.has(selection.selectedCommand)&&!actionDescriptors.some(entry=>entry.command_path===selection.selectedCommand)){actionDescriptors.push({action:packageOwnedActionForCommand(selection.selectedCommand),provider:"extension",requires_extension:true,command_path:selection.selectedCommand})}return actionDescriptors}function assertKnownContractsAction(selection,actionDescriptors){const actionNames=new Set(actionDescriptors.map(entry=>entry.action));if(selection.selectedAction&&!actionNames.has(selection.selectedAction)){throw new PmCliError(`Unknown action: "${selection.selectedAction}".`,EXIT_CODE.USAGE)}}function buildContractsCommandCatalog(actionDescriptors,mergedExtensionContracts){return[...new Set([...PM_CORE_COMMAND_NAMES.filter(entry=>!PACKAGE_OWNED_COMMANDS.has(entry)),...[...CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.keys()].filter(entry=>!PACKAGE_OWNED_COMMANDS.has(entry)),...actionDescriptors.flatMap(entry=>entry.command_path?splitCommandPathAliases(entry.command_path):[]),...mergedExtensionContracts.flatMap(entry=>entry.command.split("|"))])].map(entry=>normalizeCommandPath(entry)).filter(entry=>entry.length>0).sort((left,right)=>left.localeCompare(right))}function buildCommandNamespaceError(command,namespaceChildren){const displayedNamespaceChildren=namespaceChildren.slice(0,COMMAND_NAMESPACE_DISPLAY_LIMIT);const hiddenNamespaceChildCount=namespaceChildren.length-displayedNamespaceChildren.length;const displayedChildCommandList=hiddenNamespaceChildCount>0?`${displayedNamespaceChildren.join(", ")}, and ${hiddenNamespaceChildCount} more`:displayedNamespaceChildren.join(", ");const fallbackCandidates=namespaceChildren.slice(0,COMMAND_NAMESPACE_FALLBACK_LIMIT);const childCommandExamples=namespaceChildren.slice(0,5).map(childCommand=>`pm contracts --command "${childCommand}" --flags-only --json`);const suggestedChildCommand=namespaceChildren[0];return new PmCliError(`Command "${command}" is a command namespace. Choose a concrete child command: ${displayedChildCommandList}.`,EXIT_CODE.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:childCommandExamples,nextSteps:[`Retry with a child command, for example: ${childCommandExamples[0]}`],recovery:{suggested_retry:`pm contracts --command "${suggestedChildCommand}" --flags-only --json`,fallback_candidates:fallbackCandidates.map(childCommand=>({source:"command_namespace",command:`pm contracts --command "${childCommand}" --flags-only --json`,reason:`Child command under ${command}`}))}})}function buildPackageOwnedCommandError(command,packageHint){return new PmCliError(`Unknown command: "${command}". Command "${command}" is provided by the optional "${packageHint}" package. Run "pm install ${packageHint} --project" and retry.`,EXIT_CODE.USAGE,{code:"unknown_command",required:`Install the optional "${packageHint}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${packageHint} --project`,`pm contracts --command ${command} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${packageHint} --project`],recovery:{suggested_retry:`pm install ${packageHint} --project`}})}function buildUnknownCommandError(command){return new PmCliError(`Unknown command: "${command}".`,EXIT_CODE.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function assertKnownContractsCommand(selection,commandCatalog){if(!selection.selectedCommand){return}const commandNames=new Set(commandCatalog);if(commandNames.has(selection.selectedCommand)){return}const namespaceChildren=commandCatalog.filter(command=>command.startsWith(`${selection.selectedCommand} `));if(namespaceChildren.length>0){throw buildCommandNamespaceError(selection.selectedCommand,namespaceChildren)}const packageHint=PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(selection.selectedCommand);if(packageHint){throw buildPackageOwnedCommandError(selection.selectedCommand,packageHint)}throw buildUnknownCommandError(selection.selectedCommand)}function resolveContractsActionContext(selection,runtime){const actionDescriptors=collectContractsActionDescriptors(selection,runtime.mergedExtensionContracts);assertKnownContractsAction(selection,actionDescriptors);const commandCatalog=buildContractsCommandCatalog(actionDescriptors,runtime.mergedExtensionContracts);assertKnownContractsCommand(selection,commandCatalog);const selectedPackageOwnedAction=selection.selectedCommand?PACKAGE_OWNED_COMMAND_ACTIONS.get(selection.selectedCommand):void 0;const commandScopedDescriptors=selection.selectedCommand?actionDescriptors.filter(descriptor=>selectedPackageOwnedAction?descriptor.action===selectedPackageOwnedAction:actionDescriptorMatchesSelectedCommand(descriptor,selection.selectedCommand)):actionDescriptors;if(selection.selectedCommand&&selection.selectedAction&&!commandScopedDescriptors.some(descriptor=>descriptor.action===selection.selectedAction)){throw new PmCliError(`Action "${selection.selectedAction}" is not mapped to command "${selection.selectedCommand}" in contracts output.`,EXIT_CODE.USAGE)}const scopedActionDescriptors=selection.selectedAction?commandScopedDescriptors.filter(descriptor=>descriptor.action===selection.selectedAction):commandScopedDescriptors;const allActionAvailability=[...new Map(scopedActionDescriptors.map(descriptor=>resolveActionAvailability(descriptor,runtime.runtimeProbe)).map(entry=>[selectedPackageOwnedAction?entry.action:`${entry.action}|${entry.command_path??""}`,entry])).values()];const actionAvailability=selection.runtimeOnly&&!selection.selectedAction&&!selection.availabilityOnly?allActionAvailability.filter(entry=>entry.invocable):allActionAvailability;return{actionDescriptors,commandCatalog,commandScopedDescriptors,scopedActionDescriptors,selectedPackageOwnedAction,actionAvailability,actions:[...new Set(actionAvailability.map(entry=>entry.action))]}}function buildSchemaActionSet(schema){return new Set(extractActionBranches(schema).map(entry=>{const properties=entry.properties;if(typeof properties!=="object"||properties===null){return null}const actionProperty=properties.action;if(typeof actionProperty!=="object"||actionProperty===null){return null}const actionConst=actionProperty.const;return typeof actionConst==="string"?actionConst:null}).filter(entry=>entry!==null))}function buildMergedContractsSchema(mergedExtensionContracts){const schema=PM_TOOL_PARAMETERS_SCHEMA;const schemaBranches=extractActionBranches(schema);const schemaActionSet=buildSchemaActionSet(schema);const extensionBranches=mergedExtensionContracts.filter(contract=>!schemaActionSet.has(contract.action)).map(contract=>buildExtensionActionSchemaBranch(contract));return extensionBranches.length>0?{...schema,oneOf:[...schemaBranches,...extensionBranches]}:schema}function filterContractsSchema(selection,actionContext,mergedSchema){const descriptorActionSet=new Set(actionContext.actionDescriptors.map(descriptor=>descriptor.action));const filteredSchema=selection.selectedAction?filterSchemaByAction(mergedSchema,selection.selectedAction):selection.selectedCommand?filterSchemaByActions(mergedSchema,new Set(actionContext.scopedActionDescriptors.map(descriptor=>descriptor.action))):filterSchemaByActions(mergedSchema,descriptorActionSet);return selection.runtimeOnly&&!selection.selectedAction?filterSchemaByActions(filteredSchema,new Set(actionContext.actions)):filteredSchema}function resolveContractsSchemaContext(selection,runtime,actionContext){const mergedSchema=buildMergedContractsSchema(runtime.mergedExtensionContracts);const includeSchemaSurface=!selection.flagsOnly&&!selection.availabilityOnly;const filteredSchema=includeSchemaSurface?attachCreateRequiredOptionContracts(filterContractsSchema(selection,actionContext,mergedSchema),runtime.createRequiredOptionContracts):filterContractsSchema(selection,actionContext,mergedSchema);return{mergedSchema,filteredSchema}}function resolveContractsCommands(selection,actionContext){if(selection.selectedCommand!==void 0){return[selection.selectedCommand]}if(selection.selectedAction){return resolveScopedCommandsFromActionDescriptors(actionContext.scopedActionDescriptors,actionContext.commandCatalog)}return actionContext.commandCatalog}function resolveOutputCommands(selection,commands){if(selection.selectedCommand!==void 0||selection.selectedAction!==void 0){return commands}const hiddenAliases=new Set(PM_COMMAND_ALIAS_CONTRACTS.filter(contract=>contract.hidden&&(contract.lifecycle==="deprecated"||!selection.fullOutput&&!selection.availabilityOnly)).map(contract=>contract.alias));return commands.filter(command=>!hiddenAliases.has(command))}function canonicalSummaryCommand(command){const historyAlias=PM_HISTORY_COMMAND_ALIASES.find(contract=>contract.alias===command||contract.canonical===command);if(historyAlias)return historyAlias.canonical;const rootCommand=command.split(" ")[0];if(rootCommand.startsWith("list-"))return"list";return COMMAND_ALIAS_TO_CANONICAL.get(rootCommand)??rootCommand}const COMMAND_OPERATION_INTENTS=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]);const COMMAND_INTENT_SUBJECT_OVERRIDES=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function summarizeCommandIntent(command,extensionContracts){const declared=COMMAND_INTENTS.get(resolvePmHistoryOperation(command))??(command.includes(" ")?void 0:COMMAND_INTENTS.get(canonicalSummaryCommand(command)));if(declared!==void 0){return{intent:declared,intent_source:"command"}}const extensionContract=extensionContracts.find(contract=>splitCommandPathAliases(contract.command).includes(command));if(extensionContract?.intent!==null&&extensionContract?.intent!==void 0){return{intent:extensionContract.intent,intent_source:"command"}}if(extensionContract?.description!==null&&extensionContract?.description!==void 0){return{intent:extensionContract.description,intent_source:"description"}}const tokens=command.split(" ");const operation=tokens.at(-1);const subject=tokens.slice(0,-1).join(" ");const verb=COMMAND_OPERATION_INTENTS.get(operation);const intentSubject=COMMAND_INTENT_SUBJECT_OVERRIDES.get(command)??subject;return{intent:verb===void 0||subject.length===0?`Run ${command}.`:`${verb} ${intentSubject}.`,intent_source:"generated"}}function buildCommandSummarySurface(commands,extensionContracts=[],options={}){const includeFormatBudgets=options.includeFormatBudgets??true;const includeIntentProvenance=options.includeIntentProvenance??true;return[...new Set(commands.map(normalizeCommandPath))].filter(command=>command.length>0).sort((left,right)=>left.localeCompare(right)).map(command=>{const budget=resolvePmCommandOutputBudget(command,{generateFallback:true});const rootCommand=command.split(" ")[0];const canonicalRoot=COMMAND_ALIAS_TO_CANONICAL.get(rootCommand)??(rootCommand.startsWith("list-")?"list":rootCommand.startsWith("history-")?"history":rootCommand);const availableFlags=new Set([...resolveCoreCommandFlags(command).map(contract=>contract.flag),...extensionContracts.filter(contract=>splitCommandPathAliases(contract.command).includes(command)).flatMap(contract=>contract.flags.map(flag=>flag.flag))]);const flags=(AGENT_BOOTSTRAP_FLAGS.get(resolvePmHistoryOperation(command))??AGENT_BOOTSTRAP_FLAGS.get(canonicalRoot)??AGENT_BOUNDED_FLAG_PRIORITY).filter(flag=>availableFlags.has(flag));const intent=summarizeCommandIntent(command,extensionContracts);return{command,intent:intent.intent,...includeIntentProvenance||intent.intent_source!=="command"?{intent_source:intent.intent_source}:{},...flags.length>0?{flags}:{},default_max_estimated_tokens:budget.default_max_estimated_tokens,...includeFormatBudgets?{default_max_estimated_tokens_by_format:{...budget.default_max_estimated_tokens_by_format}}:{}}})}function buildCommandOutputContracts(commands){return commands.map(command=>({budget:resolvePmCommandOutputBudget(command,{generateFallback:true}),envelope:resolvePmCommandOutputEnvelope(command)}))}function buildCommandExitContractGroups(commands){const groups=new Map;for(const command of commands){const contract=resolvePmCommandExitContract(command);const exitCodes=contract===void 0?[EXIT_CODE.SUCCESS,EXIT_CODE.GENERIC_FAILURE,EXIT_CODE.USAGE,EXIT_CODE.NOT_FOUND,EXIT_CODE.CONFLICT,EXIT_CODE.DEPENDENCY_FAILED]:contract.exit_codes;const key=exitCodes.join(",");const group=groups.get(key)??{commands:[],exit_codes:exitCodes};group.commands.push(command);groups.set(key,group)}return[...groups.values()]}function resolveExtensionCommandContracts(selection,runtime,outputCommands){if(selection.selectedCommand){return runtime.extensionContracts.filter(entry=>splitCommandPathAliases(entry.command).includes(selection.selectedCommand))}if(selection.selectedAction){const outputCommandSet=new Set(outputCommands);return runtime.extensionContracts.filter(entry=>splitCommandPathAliases(entry.command).some(command=>outputCommandSet.has(command)))}return runtime.extensionContracts}function createContractsResult(selection,schemaContext,actionContext,outputCommands){return{schema_version:typeof schemaContext.mergedSchema["x-schema-version"]==="string"?schemaContext.mergedSchema["x-schema-version"]:null,schema_id:typeof schemaContext.mergedSchema.$id==="string"?schemaContext.mergedSchema.$id:null,selected:{action:selection.selectedAction??null,command:selection.selectedCommand??null,summary:selection.summary,schema_only:selection.schemaOnly,flags_only:selection.flagsOnly,availability_only:selection.availabilityOnly,runtime_only:selection.runtimeOnly,command_scoped:selection.selectedCommand!==void 0},commands:selection.summary?[]:outputCommands,...!selection.summary&&!selection.flagsOnly?{actions:actionContext.actions,action_availability:actionContext.actionAvailability}:{}}}function attachRuntimeContractsResult(result,runtime,selection){const selectedCommand=selection.selectedCommand;result.runtime_schema={statuses:runtime.statusRegistry.definitions.map(definition=>definition.id),open_status:runtime.statusRegistry.open_status,close_status:runtime.statusRegistry.close_status,canceled_status:runtime.statusRegistry.canceled_status,types:[...runtime.typeRegistry.types],fields_by_command:Object.fromEntries([...runtime.runtimeFieldRegistry.command_to_fields.entries()].filter(([command])=>selectedCommand===void 0||command===selectedCommand).map(([command,definitions])=>[command,[...new Set(definitions.map(definition=>`--${definition.cli_flag}`))].sort((left,right)=>left.localeCompare(right))]))};if(selectedCommand!==void 0&&!selection.fullOutput){return}result.extension_contracts={capabilities:[...PM_EXTENSION_CAPABILITY_CONTRACTS],services:[...PM_EXTENSION_SERVICE_NAME_CONTRACTS],policy_modes:[...PM_EXTENSION_POLICY_MODE_CONTRACTS],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...PM_EXTENSION_POLICY_SURFACE_CONTRACTS],trust_modes:[...PM_EXTENSION_TRUST_MODE_CONTRACTS],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}};result.governance_contracts={ownership_enforcement_modes:[...GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES],create_modes:[...GOVERNANCE_CREATE_MODE_DEFAULT_VALUES],close_validation_modes:[...GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES],workflow_enforcement_modes:[...GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES]};result.relationship_kind_contracts=[...BUILTIN_RELATIONSHIP_KINDS,...(runtime.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(registration=>registration.definitions)].sort((left,right)=>left.kind.localeCompare(right.kind)).map(definition=>({canonical:definition.kind,aliases:[...definition.aliases??[]],...definition.inverse===void 0?{}:{inverse:definition.inverse},ordering:definition.ordering,hierarchy:definition.hierarchy}))}function attachSchemaContractsResult(result,selection,schemaContext,extensionCommandContracts){if(selection.flagsOnly||selection.availabilityOnly){return}if(!selection.omitUnfilteredSchema){result.schema=schemaContext.filteredSchema;result.extension_commands=extensionCommandContracts;return}result.schema_omitted_reason="unfiltered_default_brief";result.extension_commands=extensionCommandContracts}function attachFlagContractsResult(result,selection,runtime,outputCommands,commandAliases){if(selection.schemaOnly||selection.availabilityOnly){return}if(!selection.omitUnfilteredCommandFlags){result.command_flags=buildCommandFlagSurface(outputCommands,runtime.extensionFlagMap,runtime.runtimeFieldFlagMap,selection.selectedCommand!==void 0);const commandSet=new Set(outputCommands);result.list_projections=Object.entries(LIST_COMMAND_DEFAULT_PROJECTIONS).filter(([command])=>commandSet.has(command)).map(([command,defaultProjection])=>({command,default:defaultProjection,brief_fields:[...BRIEF_LIST_FIELDS],compact_fields:[...DEFAULT_COMPACT_LIST_FIELDS]}))}else{result.command_flags_omitted_reason="unfiltered_default_brief"}result.command_aliases=selection.fullOutput?commandAliases:commandAliases.map(({canonical,aliases})=>({canonical,aliases}));if(!selection.fullOutput){result.command_alias_contracts_omitted_reason="compact_projection; restore with --full"}}function attachCommanderAliasContractsResult(result,selection){if(selection.schemaOnly||selection.flagsOnly||selection.availabilityOnly){return}if(!selection.omitUnfilteredCommanderAliases){result.commander_aliases=buildCommanderAliasSurface();return}result.commander_aliases_omitted_reason=selection.selectedCommand?"command_scoped":"unfiltered_default_brief"}function attachAgentCommandContractsResult(result,outputCommands,extensionCommandContracts,options){result.command_summaries=buildCommandSummarySurface(outputCommands,extensionCommandContracts,{includeFormatBudgets:options.includeFormatBudgets,includeIntentProvenance:options.includeIntentProvenance});result.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...PM_OUTPUT_DEGRADATION_STEPS],allows_unbounded_opt_out:true};result.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...options.includeProjectionModeMatrix?{commands:[...new Set(outputCommands.map(normalizeCommandPath))].filter(command=>resolveReadOutputSurface(command)!==void 0).sort((left,right)=>left.localeCompare(right)).map(command=>({command,modes:[...readOutputIncludeModeOptions(command).keys()]}))}:{}};result.grammar_contracts={nouns:PM_CLI_GRAMMAR_CONTRACT.nouns,shared_verbs:PM_CLI_GRAMMAR_CONTRACT.shared_verbs,scope_before_verb:PM_CLI_GRAMMAR_CONTRACT.scope_before_verb,visible_top_level_ceiling:PM_CLI_GRAMMAR_CONTRACT.visible_top_level_ceiling,ceiling_raise_requires_pm_item:PM_CLI_GRAMMAR_CONTRACT.ceiling_raise_requires_pm_item,positional_shape_budget:PM_CLI_GRAMMAR_CONTRACT.positional_shape_budget,positional_shape_count:new Set(PM_COMMAND_POSITIONAL_CONTRACTS.map(({slots})=>positionalShapeKey(slots))).size,positional_action_count:PM_POSITIONAL_ACTION_CONTRACTS.length,positional_action_parents:[...new Set(PM_POSITIONAL_ACTION_CONTRACTS.map(({parent})=>parent))].sort((left,right)=>left.localeCompare(right)),...options.includePositionalSignatures?{positional_signatures:PM_COMMAND_POSITIONAL_CONTRACTS}:{}}}async function runContracts(options,global2){const selection=resolveContractsSelection(options);assertSingleContractsProjection(selection);const pmRoot=resolvePmRoot(process.cwd(),global2.path);const runtime=await resolveContractsRuntimeContext(global2,pmRoot);const actionContext=resolveContractsActionContext(selection,runtime);const schemaContext=resolveContractsSchemaContext(selection,runtime,actionContext);const commands=resolveContractsCommands(selection,actionContext);const outputCommands=resolveOutputCommands(selection,commands);const result=createContractsResult(selection,schemaContext,actionContext,outputCommands);const extensionCommandContracts=resolveExtensionCommandContracts(selection,runtime,outputCommands);const includeCommandDetails=selection.fullOutput||selection.selectedCommand!==void 0;if(selection.summary||selection.fullOutput){attachAgentCommandContractsResult(result,outputCommands,extensionCommandContracts,{includeFormatBudgets:includeCommandDetails,includeIntentProvenance:includeCommandDetails,includePositionalSignatures:includeCommandDetails,includeProjectionModeMatrix:includeCommandDetails})}if(selection.summary){return result}const commandAliases=buildCommandAliasSurface(actionContext.commandCatalog);if(!(selection.flagsOnly&&!selection.fullOutput)){attachRuntimeContractsResult(result,runtime,selection)}attachSchemaContractsResult(result,selection,schemaContext,extensionCommandContracts);attachFlagContractsResult(result,selection,runtime,outputCommands,commandAliases);attachCommanderAliasContractsResult(result,selection);if(selection.selectedCommand==="assurance"||selection.fullOutput){result.assurance_contracts={measurement_source_kinds:[...ASSURANCE_MEASUREMENT_SOURCE_KINDS],gate_triggers:[...ASSURANCE_GATE_TRIGGERS]}}if(selection.fullOutput&&result.grammar_contracts){result.grammar_contracts.destinations=PM_COMMAND_DESTINATION_CONTRACTS}if(selection.fullOutput&&!selection.schemaOnly&&!selection.flagsOnly&&!selection.availabilityOnly){result.mcp_tools=buildMcpToolContracts();result.context_intents=getActiveContextIntentContracts();result.read_output_dimensions=PM_READ_OUTPUT_SURFACE_CONTRACTS;result.error_codes=PM_ERROR_CODE_CATALOG;result.command_output_contracts=buildCommandOutputContracts(outputCommands);result.diagnostic_output_contracts=PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS;result.command_exit_contracts={vocabulary:PM_COMMAND_EXIT_OUTCOME_CONTRACTS,command_sets:buildCommandExitContractGroups(outputCommands)}}return result}const _testOnlyContractsCommand={actionDescriptorMatchesSelectedCommand,attachCreateRequiredOptionContracts,buildExtensionActionSchemaBranch,buildCommandSummarySurface,buildCommandOutputContracts,buildCommandExitContractGroups,buildRuntimeFieldFlagContracts,collectActionContractDescriptors,collectExtensionCommandContracts,collectExtensionFlagContractsByCommand,extractActionBranches,extensionSchemaPropertyNameFromFlag,filterSchemaByAction,filterSchemaByActions,isCoreCommandPath,mergeExtensionContractsByAction,normalizeExtensionFlagName,normalizeActionNameFromCommand,normalizeCommandForRuntimeFieldFlags,normalizeCommandPath,packageOwnedActionForCommand,readContractsSettings,resolveActionCommandPath,resolveActionAvailability,resolveCoreCommandFlags,resolveRuntimeExtensionActionProbe,resolveScopedCommandsFromActionDescriptors,splitCommandPathAliases,toRuntimeLongFlagToken,toRuntimeShortFlagToken};export{_testOnlyContractsCommand,buildCommandAliasSurface,runContracts};
2090
2
  //# sourceMappingURL=runtime-contracts.js.map
2091
- //# debugId=188569e7-c809-5f28-a714-d531f57be1d9