@unbrained/pm-cli 2026.11.22 → 2026.11.24

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 (912) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/after-command-context-usage.js +1 -1
  3. package/dist/cli/argv-utils.js +1 -1
  4. package/dist/cli/bootstrap-args.js +1 -1
  5. package/dist/cli/bundle-integrity.js +2 -2
  6. package/dist/cli/command-namespaces.js +1 -1
  7. package/dist/cli/commander-usage.js +11 -11
  8. package/dist/cli/commands/annotations/comments.js +1 -1
  9. package/dist/cli/commands/annotations/docs.js +1 -1
  10. package/dist/cli/commands/annotations/files.js +1 -1
  11. package/dist/cli/commands/annotations/learnings.js +1 -1
  12. package/dist/cli/commands/annotations/notes.js +1 -1
  13. package/dist/cli/commands/extension/describe.js +1 -1
  14. package/dist/cli/commands/extension/extension.js +1 -1
  15. package/dist/cli/commands/extension/scaffold.js +1 -1
  16. package/dist/cli/commands/extension/shared.js +1 -1
  17. package/dist/cli/commands/governance/gc.js +1 -1
  18. package/dist/cli/commands/governance/health.js +1 -1
  19. package/dist/cli/commands/governance/telemetry.js +1 -1
  20. package/dist/cli/commands/governance/validate.js +1 -1
  21. package/dist/cli/commands/history/activity.js +1 -1
  22. package/dist/cli/commands/history/history-compact.js +1 -1
  23. package/dist/cli/commands/history/history-redact.js +1 -1
  24. package/dist/cli/commands/history/history-repair.js +1 -1
  25. package/dist/cli/commands/history/history.js +1 -1
  26. package/dist/cli/commands/history/restore.js +1 -1
  27. package/dist/cli/commands/lifecycle/append.js +1 -1
  28. package/dist/cli/commands/lifecycle/claim.js +1 -1
  29. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  30. package/dist/cli/commands/lifecycle/close.js +1 -1
  31. package/dist/cli/commands/lifecycle/copy.js +1 -1
  32. package/dist/cli/commands/lifecycle/create.js +1 -1
  33. package/dist/cli/commands/lifecycle/delete.js +1 -1
  34. package/dist/cli/commands/lifecycle/focus.js +1 -1
  35. package/dist/cli/commands/lifecycle/plan.js +1 -1
  36. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  37. package/dist/cli/commands/lifecycle/update.js +1 -1
  38. package/dist/cli/commands/query/aggregate.js +1 -1
  39. package/dist/cli/commands/query/context.js +1 -1
  40. package/dist/cli/commands/query/deps.js +1 -1
  41. package/dist/cli/commands/query/duplicates.js +1 -1
  42. package/dist/cli/commands/query/eval.js +1 -1
  43. package/dist/cli/commands/query/get.js +1 -1
  44. package/dist/cli/commands/query/graph.js +1 -1
  45. package/dist/cli/commands/query/list.js +1 -1
  46. package/dist/cli/commands/query/next.js +1 -1
  47. package/dist/cli/commands/query/search.js +1 -1
  48. package/dist/cli/commands/query/stats.js +1 -1
  49. package/dist/cli/commands/test/test-all.js +1 -1
  50. package/dist/cli/commands/test/test-runs.js +1 -1
  51. package/dist/cli/commands/test/test.js +1 -1
  52. package/dist/cli/commands/workspace/config.js +1 -1
  53. package/dist/cli/commands/workspace/contracts.js +1 -1
  54. package/dist/cli/commands/workspace/init.js +1 -1
  55. package/dist/cli/commands/workspace/merge.js +1 -1
  56. package/dist/cli/commands/workspace/profile.js +1 -1
  57. package/dist/cli/commands/workspace/schema.js +1 -1
  58. package/dist/cli/commands/workspace/upgrade.js +1 -1
  59. package/dist/cli/context-intent-invocation.js +1 -1
  60. package/dist/cli/description-stdin.js +1 -1
  61. package/dist/cli/error-guidance.js +5 -5
  62. package/dist/cli/expected-revisions.js +1 -1
  63. package/dist/cli/extension-command-help.js +6 -6
  64. package/dist/cli/extension-recovery.js +1 -1
  65. package/dist/cli/help-content.js +5 -5
  66. package/dist/cli/help-json-payload.js +7 -7
  67. package/dist/cli/invocation-profile.js +2 -2
  68. package/dist/cli/main.js +5 -5
  69. package/dist/cli/migration-gates.js +1 -1
  70. package/dist/cli/option-values.js +1 -1
  71. package/dist/cli/preflight-warnings.js +3 -3
  72. package/dist/cli/public.js +1 -1
  73. package/dist/cli/register-annotations.js +1 -1
  74. package/dist/cli/register-assurance.js +1 -1
  75. package/dist/cli/register-files-lookup.js +1 -1
  76. package/dist/cli/register-history-activity.js +1 -1
  77. package/dist/cli/register-history-author.js +1 -1
  78. package/dist/cli/register-history-maintenance.js +2 -2
  79. package/dist/cli/register-list-query.js +10 -10
  80. package/dist/cli/register-mutation-options.js +0 -1
  81. package/dist/cli/register-mutation.js +6 -6
  82. package/dist/cli/register-operations.js +1 -1
  83. package/dist/cli/register-setup.js +1 -1
  84. package/dist/cli/register-structured-mutation.js +1 -1
  85. package/dist/cli/registration-helpers.js +1 -1
  86. package/dist/cli/runtime/activation.js +1 -1
  87. package/dist/cli/runtime/annotation-option-retry.js +1 -1
  88. package/dist/cli/runtime/close-fields-retry.js +1 -1
  89. package/dist/cli/runtime/field-route-retry.js +1 -1
  90. package/dist/cli/runtime/invocation-options.js +1 -1
  91. package/dist/cli/runtime/invocation-rewrites.js +1 -1
  92. package/dist/cli/runtime/projection-retry.js +1 -1
  93. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  94. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  95. package/dist/cli/runtime/selection.js +1 -1
  96. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  97. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  98. package/dist/cli/schema/registration.js +15 -15
  99. package/dist/cli/schema-registration-helpers.js +1 -1
  100. package/dist/cli/search-refresh.js +1 -1
  101. package/dist/cli/stats-analytics-json.js +1 -1
  102. package/dist/cli/telemetry-flush.js +1 -1
  103. package/dist/cli-bundle/bundle-manifest.json +1 -1
  104. package/dist/cli-bundle/chunks/chunk-23K6DQQY.js +9 -0
  105. package/dist/cli-bundle/chunks/chunk-37UDIJ2K.js +3 -0
  106. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  107. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-7IROAPWI.js +3 -0
  109. package/dist/cli-bundle/chunks/chunk-7VRFEURZ.js +33 -0
  110. package/dist/cli-bundle/chunks/chunk-7X253M6Z.js +3 -0
  111. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  112. package/dist/cli-bundle/chunks/chunk-AWB5KBJS.js +2 -0
  113. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  114. package/dist/cli-bundle/chunks/chunk-DQDRA3SW.js +2 -0
  115. package/dist/cli-bundle/chunks/chunk-FXJYZBWV.js +113 -0
  116. package/dist/cli-bundle/chunks/chunk-HNKK2UG6.js +8 -0
  117. package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-I2OJ5B4A.js +2 -0
  119. package/dist/cli-bundle/chunks/chunk-I3BFCKZR.js +2 -0
  120. package/dist/cli-bundle/chunks/chunk-MXUSC5RS.js +31 -0
  121. package/dist/cli-bundle/chunks/chunk-PLIUU37C.js +3 -0
  122. package/dist/cli-bundle/chunks/chunk-PQUBVRV5.js +2 -0
  123. package/dist/cli-bundle/chunks/chunk-PW7U7WCE.js +3 -0
  124. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  125. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  126. package/dist/cli-bundle/chunks/chunk-SSALO4DB.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-STOOTHZZ.js +2 -0
  128. package/dist/cli-bundle/chunks/chunk-TKRY22SO.js +2 -0
  129. package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-TVIJ2VCU.js} +93 -93
  130. package/dist/cli-bundle/chunks/chunk-VJSGUXGU.js +3 -0
  131. package/dist/cli-bundle/chunks/chunk-WWTPNIC2.js +6 -0
  132. package/dist/cli-bundle/chunks/chunk-XFADNMGD.js +2 -0
  133. package/dist/cli-bundle/chunks/chunk-YOPTAIBD.js +125 -0
  134. package/dist/cli-bundle/chunks/chunk-YW2HBHRO.js +70 -0
  135. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  136. package/dist/cli-bundle/chunks/chunk-Z7MFVRDV.js +2 -0
  137. package/dist/cli-bundle/chunks/chunk-ZOX4SWRL.js +8 -0
  138. package/dist/cli-bundle/chunks/chunk-ZYCOM4MS.js +9 -0
  139. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  140. package/dist/cli-bundle/chunks/field-option-collisions-W66HSWMK.js +2 -0
  141. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  142. package/dist/cli-bundle/{focused-chunks/item-revision-2O6MLPEX.js → chunks/item-revision-D3LSBNIR.js} +2 -2
  143. package/dist/cli-bundle/chunks/item-transaction-M6NTBYH3.js +2 -0
  144. package/dist/cli-bundle/chunks/mutation-actor-OKL3CQVX.js +2 -0
  145. package/dist/cli-bundle/chunks/mutation-admission-EKPEOZMF.js +2 -0
  146. package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-3LBV6CS2.js} +11 -11
  147. package/dist/cli-bundle/chunks/register-mutation-72AGTMNE.js +21 -0
  148. package/dist/cli-bundle/chunks/register-operations-XERFG2SH.js +2 -0
  149. package/dist/cli-bundle/chunks/register-setup-W22L34Z4.js +2 -0
  150. package/dist/cli-bundle/chunks/runtime-schema-JP2KBHBY.js +2 -0
  151. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  152. package/dist/cli-bundle/chunks/stage-T2LKWN7C.js +2 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-24VRBNKE.js +26 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-3ELVASVA.js +2 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-3GT4A3ZN.js +44 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-3OCDKITJ.js +3 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-3Z7MCUJM.js +3 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-46MP7IZN.js +5 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-5LDBS6MS.js +91 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-B6BNHKUW.js +78 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-C7WHWI7K.js +3 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-EUQGZPGO.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-FDZPRJXJ.js +27 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-GXP7Q4XM.js +2 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-HL47UQZJ.js +8 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-LMFIAQ2V.js +2 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-LMU7DDOA.js +2 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-OZOCEB2Q.js +8 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-Q2HY44LV.js +13 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-REFMQY47.js +2 -0
  177. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  178. package/dist/cli-bundle/focused-chunks/chunk-RIQUIHYU.js +3 -0
  179. package/dist/cli-bundle/focused-chunks/chunk-RLO2HCZT.js +2 -0
  180. package/dist/cli-bundle/focused-chunks/chunk-SMMOZ3H3.js +100 -0
  181. package/dist/cli-bundle/focused-chunks/chunk-UVTUX54T.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/chunk-XDBHD4CY.js +8 -0
  184. package/dist/cli-bundle/focused-chunks/chunk-YD66IRSL.js +2 -0
  185. package/dist/cli-bundle/focused-chunks/chunk-Z7W2RQIB.js +2 -0
  186. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  187. package/dist/cli-bundle/focused-chunks/field-option-collisions-UODPSV6W.js +2 -0
  188. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  189. package/dist/cli-bundle/focused-chunks/item-revision-QH7RNBX4.js +2 -0
  190. package/dist/cli-bundle/focused-chunks/item-transaction-ZO72OINF.js +2 -0
  191. package/dist/cli-bundle/focused-chunks/mutation-actor-PHVLKG4I.js +2 -0
  192. package/dist/cli-bundle/focused-chunks/mutation-admission-ZSG5OECH.js +2 -0
  193. package/dist/cli-bundle/focused-chunks/runtime-schema-6RQMIDTN.js +2 -0
  194. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  195. package/dist/cli-bundle/focused-chunks/stage-AQMKRVX4.js +2 -0
  196. package/dist/cli-bundle/main.js +27 -27
  197. package/dist/cli-bundle/sdk-authoring.js +1 -1
  198. package/dist/cli-bundle/sdk-contracts.js +5 -5
  199. package/dist/cli-bundle/sdk-core.js +1 -1
  200. package/dist/cli-bundle/sdk-governance.js +1 -1
  201. package/dist/cli-bundle/sdk-graph.js +1 -1
  202. package/dist/cli-bundle/sdk-merge.js +66 -66
  203. package/dist/cli-bundle/sdk-query.js +1 -1
  204. package/dist/cli-bundle/sdk-runtime.js +1 -1
  205. package/dist/cli-bundle/sdk-testing.js +1 -1
  206. package/dist/cli-bundle/sdk.js +13 -13
  207. package/dist/cli.js +1 -1
  208. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  209. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  210. package/dist/core/checkpoint/mutation-context.js +1 -1
  211. package/dist/core/config/nested-settings.js +1 -1
  212. package/dist/core/config/positional-value.js +1 -1
  213. package/dist/core/diagnostics/remediation.js +1 -1
  214. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  215. package/dist/core/extensions/activation-summary.js +1 -1
  216. package/dist/core/extensions/activation-transaction.js +1 -1
  217. package/dist/core/extensions/capability-usage.js +1 -1
  218. package/dist/core/extensions/command-hook-context.js +1 -1
  219. package/dist/core/extensions/command-metadata-contract.js +1 -1
  220. package/dist/core/extensions/command-visibility-tier.js +1 -1
  221. package/dist/core/extensions/contribution-inventory.js +1 -1
  222. package/dist/core/extensions/exporter-output-contract.js +1 -1
  223. package/dist/core/extensions/extension-candidate.js +1 -1
  224. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  225. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  226. package/dist/core/extensions/extension-policy.js +1 -1
  227. package/dist/core/extensions/extension-registries.js +1 -1
  228. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  229. package/dist/core/extensions/extension-types.js +1 -1
  230. package/dist/core/extensions/flag-definition-validation.js +1 -1
  231. package/dist/core/extensions/flag-value-types.js +1 -1
  232. package/dist/core/extensions/index.js +1 -1
  233. package/dist/core/extensions/item-field-types.js +1 -1
  234. package/dist/core/extensions/item-fields.js +1 -1
  235. package/dist/core/extensions/loader.js +1 -1
  236. package/dist/core/extensions/manifest-parser.js +1 -1
  237. package/dist/core/extensions/manifest-schema.js +1 -1
  238. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  239. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  240. package/dist/core/extensions/mutation-actor.js +1 -1
  241. package/dist/core/extensions/preflight-ownership.js +1 -1
  242. package/dist/core/extensions/read-output-contract.js +1 -1
  243. package/dist/core/extensions/registration-contracts.js +1 -1
  244. package/dist/core/extensions/registration-validation.js +1 -1
  245. package/dist/core/extensions/registration-values.js +1 -1
  246. package/dist/core/extensions/reserved-host-flags.js +1 -1
  247. package/dist/core/extensions/runtime-registrations.js +1 -1
  248. package/dist/core/extensions/service-ownership.js +1 -1
  249. package/dist/core/extensions/version-compat.js +1 -1
  250. package/dist/core/extensions/version-diagnostics.js +1 -1
  251. package/dist/core/fs/atomic-create.js +1 -1
  252. package/dist/core/fs/file-glob.js +1 -1
  253. package/dist/core/fs/fs-utils.js +2 -2
  254. package/dist/core/fs/host-environment-errors.js +1 -1
  255. package/dist/core/fs/index.js +1 -1
  256. package/dist/core/fs/path-utils.js +1 -1
  257. package/dist/core/governance/content-fields.js +1 -1
  258. package/dist/core/governance/issue-codes.js +1 -1
  259. package/dist/core/governance/metadata-coverage.js +1 -1
  260. package/dist/core/history/bridge.js +1 -1
  261. package/dist/core/history/digest.js +1 -1
  262. package/dist/core/history/drift-cache.js +3 -3
  263. package/dist/core/history/drift-scan.js +1 -1
  264. package/dist/core/history/event-classification.js +1 -1
  265. package/dist/core/history/event-index.js +11 -11
  266. package/dist/core/history/history-compact-bulk.js +1 -1
  267. package/dist/core/history/history-diff.js +1 -1
  268. package/dist/core/history/history-rewrite.js +1 -1
  269. package/dist/core/history/history-storage-stats.js +1 -1
  270. package/dist/core/history/history-stream-policy.js +1 -1
  271. package/dist/core/history/history.js +2 -2
  272. package/dist/core/history/identity.js +1 -1
  273. package/dist/core/history/index.js +1 -1
  274. package/dist/core/history/operation-contract.js +1 -1
  275. package/dist/core/history/projection.js +1 -1
  276. package/dist/core/history/read.js +1 -1
  277. package/dist/core/history/replay.js +2 -2
  278. package/dist/core/history/stream-summary.js +2 -2
  279. package/dist/core/history/tombstone.js +1 -1
  280. package/dist/core/history/version-address.js +1 -1
  281. package/dist/core/history/workspace-history.js +2 -2
  282. package/dist/core/io/body-file.js +1 -1
  283. package/dist/core/io/bulk-ids-input.js +2 -2
  284. package/dist/core/item/actionability.js +1 -1
  285. package/dist/core/item/deferred-fields.js +1 -1
  286. package/dist/core/item/dependency-reference.js +1 -1
  287. package/dist/core/item/id.js +1 -1
  288. package/dist/core/item/index.js +1 -1
  289. package/dist/core/item/item-format-version.js +1 -1
  290. package/dist/core/item/item-format.js +7 -7
  291. package/dist/core/item/item-record.js +1 -1
  292. package/dist/core/item/item-type-definition.js +1 -1
  293. package/dist/core/item/literal-mutation-input.js +1 -1
  294. package/dist/core/item/parent-reference-policy.js +1 -1
  295. package/dist/core/item/parse.js +8 -8
  296. package/dist/core/item/plan-lifecycle.js +1 -1
  297. package/dist/core/item/priority.js +1 -1
  298. package/dist/core/item/sprint-release-format.js +1 -1
  299. package/dist/core/item/status-filter.js +1 -1
  300. package/dist/core/item/status.js +1 -1
  301. package/dist/core/item/toon-decode.js +1 -1
  302. package/dist/core/item/type-registry.js +1 -1
  303. package/dist/core/item/type-synonyms.js +1 -1
  304. package/dist/core/lock/index.js +1 -1
  305. package/dist/core/lock/lock-confinement.js +1 -1
  306. package/dist/core/lock/lock-gc.js +1 -1
  307. package/dist/core/lock/lock-owner.js +1 -1
  308. package/dist/core/lock/lock.js +4 -4
  309. package/dist/core/output/linked-test-projection.js +5 -5
  310. package/dist/core/output/mutation-projection.js +1 -1
  311. package/dist/core/output/output-control.js +1 -1
  312. package/dist/core/output/output.js +19 -19
  313. package/dist/core/output/query-summary.js +1 -1
  314. package/dist/core/output/tabular.js +3 -3
  315. package/dist/core/packages/manifest.js +1 -1
  316. package/dist/core/packages/root.js +1 -1
  317. package/dist/core/policy/workflow-policy-schema.js +1 -1
  318. package/dist/core/policy/workflow-policy-store.js +1 -1
  319. package/dist/core/policy/workflow-policy.js +1 -1
  320. package/dist/core/profile/profile-describe.js +1 -1
  321. package/dist/core/profile/profile-lint.d.ts +1 -1
  322. package/dist/core/profile/profile-lint.js +1 -1
  323. package/dist/core/profile/profile-plan.js +1 -1
  324. package/dist/core/profile/profile-presets.js +4 -4
  325. package/dist/core/reproducibility/context.js +1 -1
  326. package/dist/core/schema/fields-file.js +2 -2
  327. package/dist/core/schema/item-types-file.js +2 -2
  328. package/dist/core/schema/runtime-field-filters.js +1 -1
  329. package/dist/core/schema/runtime-field-values.js +1 -1
  330. package/dist/core/schema/runtime-schema.d.ts +2 -0
  331. package/dist/core/schema/runtime-schema.js +2 -2
  332. package/dist/core/schema/status-defs-file.js +2 -2
  333. package/dist/core/schema/status-token.js +1 -1
  334. package/dist/core/schema/type-inference.js +1 -1
  335. package/dist/core/schema/type-presets.js +1 -1
  336. package/dist/core/schema/type-workflows.js +1 -1
  337. package/dist/core/search/background-refresh.js +2 -2
  338. package/dist/core/search/bm25.js +1 -1
  339. package/dist/core/search/cache.js +2 -2
  340. package/dist/core/search/corpus.js +1 -1
  341. package/dist/core/search/embedding-batches.js +1 -1
  342. package/dist/core/search/eval-thresholds.js +1 -1
  343. package/dist/core/search/eval.js +1 -1
  344. package/dist/core/search/http-client.js +1 -1
  345. package/dist/core/search/providers.js +1 -1
  346. package/dist/core/search/relevance.js +1 -1
  347. package/dist/core/search/semantic-defaults.js +1 -1
  348. package/dist/core/search/staleness.js +1 -1
  349. package/dist/core/search/vector-stores.js +2 -2
  350. package/dist/core/search/vectorization-metadata.js +1 -1
  351. package/dist/core/sentry/helpers.js +1 -1
  352. package/dist/core/sentry/instrument.js +1 -1
  353. package/dist/core/sentry/sensitive-assignments.js +1 -1
  354. package/dist/core/session/session-state.js +1 -1
  355. package/dist/core/shared/agent-session-context.js +1 -1
  356. package/dist/core/shared/author.js +5 -5
  357. package/dist/core/shared/command-line.js +1 -1
  358. package/dist/core/shared/command-types.js +0 -1
  359. package/dist/core/shared/conflict-markers.js +1 -1
  360. package/dist/core/shared/constants.js +1 -1
  361. package/dist/core/shared/error-details.js +1 -1
  362. package/dist/core/shared/errors.js +1 -1
  363. package/dist/core/shared/html-entity-decode.js +1 -1
  364. package/dist/core/shared/index.js +1 -1
  365. package/dist/core/shared/item-metadata-contract.js +1 -1
  366. package/dist/core/shared/lazy-module.js +1 -1
  367. package/dist/core/shared/levenshtein.js +1 -1
  368. package/dist/core/shared/memo.js +1 -1
  369. package/dist/core/shared/numeric-parsers.js +1 -1
  370. package/dist/core/shared/option-alias-visibility.js +1 -1
  371. package/dist/core/shared/output-unicode.js +1 -1
  372. package/dist/core/shared/primitives.js +1 -1
  373. package/dist/core/shared/process-tree.js +2 -2
  374. package/dist/core/shared/secret-rules.js +5 -5
  375. package/dist/core/shared/serial-queue.js +1 -1
  376. package/dist/core/shared/serialization.js +1 -1
  377. package/dist/core/shared/split-comma-list.js +1 -1
  378. package/dist/core/shared/text-normalization.js +1 -1
  379. package/dist/core/shared/time.js +2 -2
  380. package/dist/core/shared/url-credentials.js +1 -1
  381. package/dist/core/store/index.js +1 -1
  382. package/dist/core/store/item-format-migration.js +1 -1
  383. package/dist/core/store/item-metadata-cache.js +1 -1
  384. package/dist/core/store/item-metadata-query-index.js +11 -11
  385. package/dist/core/store/item-metadata-read-work.js +1 -1
  386. package/dist/core/store/item-mutation-precondition.js +1 -1
  387. package/dist/core/store/item-store.js +1 -1
  388. package/dist/core/store/paths.js +1 -1
  389. package/dist/core/store/settings-concurrency.js +1 -1
  390. package/dist/core/store/settings-read-cache.js +1 -1
  391. package/dist/core/store/settings-sections.js +2 -2
  392. package/dist/core/store/settings-validator.js +1 -1
  393. package/dist/core/store/settings.d.ts +3 -1
  394. package/dist/core/store/settings.js +6 -6
  395. package/dist/core/store/sqlite-runtime.js +1 -1
  396. package/dist/core/store/tracker-preflight.js +1 -1
  397. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  398. package/dist/core/telemetry/consent.js +3 -3
  399. package/dist/core/telemetry/observability.js +1 -1
  400. package/dist/core/telemetry/policy.js +1 -1
  401. package/dist/core/telemetry/read-sampling.js +2 -2
  402. package/dist/core/telemetry/runtime.js +9 -9
  403. package/dist/core/test/background-runs.js +4 -4
  404. package/dist/core/test/item-test-run-tracking.js +1 -1
  405. package/dist/core/test/run-selectors.js +1 -1
  406. package/dist/core/validate/estimate-defaults.js +1 -1
  407. package/dist/core/validate/fix-planning.js +1 -1
  408. package/dist/core/validate/linked-artifact-reference.js +1 -1
  409. package/dist/core/validate/missing-by-type.js +1 -1
  410. package/dist/core/validate/missing-link-owners.js +1 -1
  411. package/dist/core/validate/stale-file-classification.js +1 -1
  412. package/dist/mcp/http-server.js +5 -5
  413. package/dist/mcp/legacy-adapter.js +1 -1
  414. package/dist/mcp/runtime-capabilities.js +1 -1
  415. package/dist/mcp/server.js +4 -4
  416. package/dist/mcp/tool-definitions.js +1 -1
  417. package/dist/sdk/actionability.js +1 -1
  418. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  419. package/dist/sdk/agent/command-recovery.js +1 -1
  420. package/dist/sdk/agent/command-suggestions.js +1 -1
  421. package/dist/sdk/agent/create-option-policy.js +1 -1
  422. package/dist/sdk/agent/identity-config.js +1 -1
  423. package/dist/sdk/agent/item-addressing.js +1 -1
  424. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  425. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  426. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  427. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  428. package/dist/sdk/agent-capability-contracts.js +3 -3
  429. package/dist/sdk/agent-session-context.js +1 -1
  430. package/dist/sdk/annotations.js +1 -1
  431. package/dist/sdk/author-attribution.js +1 -1
  432. package/dist/sdk/cli-bootstrap.js +1 -1
  433. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  434. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  435. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  436. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  437. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  438. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  439. package/dist/sdk/cli-contracts/completeness.js +1 -1
  440. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  441. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  442. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  443. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  444. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  445. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  446. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  447. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  448. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  449. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  450. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  451. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  452. package/dist/sdk/cli-contracts.js +1 -1
  453. package/dist/sdk/cli-program.js +1 -1
  454. package/dist/sdk/command-line.js +1 -1
  455. package/dist/sdk/comments.js +1 -1
  456. package/dist/sdk/compile-cache.js +1 -1
  457. package/dist/sdk/completion/bash.js +2 -2
  458. package/dist/sdk/completion/fish.js +72 -72
  459. package/dist/sdk/completion/shared.js +1 -1
  460. package/dist/sdk/completion/zsh.js +75 -75
  461. package/dist/sdk/completion.js +1 -1
  462. package/dist/sdk/config.js +1 -1
  463. package/dist/sdk/context/recency.js +1 -1
  464. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  465. package/dist/sdk/context/usage-egress.js +1 -1
  466. package/dist/sdk/context/usage-ledger.js +6 -6
  467. package/dist/sdk/context-intent-contracts.js +1 -1
  468. package/dist/sdk/context-intent-runtime.js +1 -1
  469. package/dist/sdk/context-packing.js +1 -1
  470. package/dist/sdk/context-relevance.js +1 -1
  471. package/dist/sdk/context-signal-store.js +2 -2
  472. package/dist/sdk/context-usage.js +1 -1
  473. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  474. package/dist/sdk/dependencies.js +1 -1
  475. package/dist/sdk/dependency-flag-validation.js +1 -1
  476. package/dist/sdk/dependency-provenance.js +1 -1
  477. package/dist/sdk/docs.js +1 -1
  478. package/dist/sdk/duplicates.js +1 -1
  479. package/dist/sdk/environment/host-environment-errors.js +1 -1
  480. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  481. package/dist/sdk/environment/source-context.js +1 -1
  482. package/dist/sdk/environment/tracker-preflight.js +1 -1
  483. package/dist/sdk/error-code-catalog.js +1 -1
  484. package/dist/sdk/error-runtime.js +1 -1
  485. package/dist/sdk/errors.js +1 -1
  486. package/dist/sdk/eval.js +1 -1
  487. package/dist/sdk/extension/author-manifest.js +1 -1
  488. package/dist/sdk/extension/bundled-catalog.js +1 -1
  489. package/dist/sdk/extension/command-options.d.ts +26 -1
  490. package/dist/sdk/extension/command-options.js +1 -1
  491. package/dist/sdk/extension/concurrency.js +1 -1
  492. package/dist/sdk/extension/copy-scope.js +1 -1
  493. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  494. package/dist/sdk/extension/describe.js +3 -3
  495. package/dist/sdk/extension/doctor.js +1 -1
  496. package/dist/sdk/extension/install-plan.js +1 -1
  497. package/dist/sdk/extension/install-receipts.js +1 -1
  498. package/dist/sdk/extension/install-runtime.js +3 -3
  499. package/dist/sdk/extension/install-snapshot.js +1 -1
  500. package/dist/sdk/extension/install-sources.js +5 -5
  501. package/dist/sdk/extension/managed-state.js +2 -2
  502. package/dist/sdk/extension/managed-update-status.js +1 -1
  503. package/dist/sdk/extension/migrations.js +2 -2
  504. package/dist/sdk/extension/native-command-options.js +1 -1
  505. package/dist/sdk/extension/output-ownership.js +1 -1
  506. package/dist/sdk/extension/runtime-summary.js +1 -1
  507. package/dist/sdk/extension/scaffold.js +11 -11
  508. package/dist/sdk/extension/shared.js +1 -1
  509. package/dist/sdk/extension/source-resolution.js +1 -1
  510. package/dist/sdk/extension/static-inventory.js +1 -1
  511. package/dist/sdk/extension/update-check.js +1 -1
  512. package/dist/sdk/extension-command-context.js +2 -2
  513. package/dist/sdk/extension-contracts.js +1 -1
  514. package/dist/sdk/extension.js +1 -1
  515. package/dist/sdk/files.js +1 -1
  516. package/dist/sdk/flag-invocation-contracts.js +1 -1
  517. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  518. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  519. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  520. package/dist/sdk/generated-error-code-catalog.js +1 -1
  521. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  522. package/dist/sdk/governance/assurance-action.js +1 -1
  523. package/dist/sdk/governance/assurance-limits.js +1 -1
  524. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  525. package/dist/sdk/governance/assurance-presets.js +1 -1
  526. package/dist/sdk/governance/assurance-runtime.js +1 -1
  527. package/dist/sdk/governance/assurance.js +4 -4
  528. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  529. package/dist/sdk/governance/closure-timestamps.js +1 -1
  530. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  531. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  532. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  533. package/dist/sdk/governance/defect-recurrence.js +2 -2
  534. package/dist/sdk/governance/extension-host-version.js +1 -1
  535. package/dist/sdk/governance/gc.js +1 -1
  536. package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
  537. package/dist/sdk/governance/health/projection.js +1 -1
  538. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  539. package/dist/sdk/governance/health.js +2 -2
  540. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  541. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  542. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  543. package/dist/sdk/governance/linked-file-report.js +1 -1
  544. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  545. package/dist/sdk/governance/provenance-health.js +4 -4
  546. package/dist/sdk/governance/reindex.js +5 -5
  547. package/dist/sdk/governance/stale-work.js +1 -1
  548. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  549. package/dist/sdk/governance/storage-integrity.js +1 -1
  550. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  551. package/dist/sdk/governance/upgrade.js +2 -2
  552. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  553. package/dist/sdk/governance/validate-history-drift.js +1 -1
  554. package/dist/sdk/governance/validate-item-reader.js +1 -1
  555. package/dist/sdk/governance/validate-normalization.js +1 -1
  556. package/dist/sdk/governance/validate.js +1 -1
  557. package/dist/sdk/governance/workflow-completeness.js +1 -1
  558. package/dist/sdk/governance/workflow-policy.js +3 -3
  559. package/dist/sdk/governance/workspace-position.js +2 -2
  560. package/dist/sdk/graph/analytics.js +1 -1
  561. package/dist/sdk/graph/assembly.js +1 -1
  562. package/dist/sdk/graph/cache.js +1 -1
  563. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  564. package/dist/sdk/graph/centrality.js +1 -1
  565. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  566. package/dist/sdk/graph/durable-cache.js +1 -1
  567. package/dist/sdk/graph/governance-contracts.js +1 -1
  568. package/dist/sdk/graph/governance.js +1 -1
  569. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  570. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  571. package/dist/sdk/graph/mutation-advisory.js +1 -1
  572. package/dist/sdk/graph/query-contracts.js +1 -1
  573. package/dist/sdk/graph/remediation.js +1 -1
  574. package/dist/sdk/graph/run.js +1 -1
  575. package/dist/sdk/graph/scheduling.js +1 -1
  576. package/dist/sdk/graph/traversal.js +1 -1
  577. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  578. package/dist/sdk/guide-topics.js +1 -1
  579. package/dist/sdk/guide.js +7 -7
  580. package/dist/sdk/history/append-only-repair.js +4 -4
  581. package/dist/sdk/history/attestation-command.js +2 -2
  582. package/dist/sdk/history/attestation-contract.js +1 -1
  583. package/dist/sdk/history/attestation-scan.js +1 -1
  584. package/dist/sdk/history/attestation.js +1 -1
  585. package/dist/sdk/history/maintenance.js +1 -1
  586. package/dist/sdk/history/reanchor-refusal.js +1 -1
  587. package/dist/sdk/history/reseed.js +1 -1
  588. package/dist/sdk/history/salvage.js +5 -5
  589. package/dist/sdk/history/subject.js +1 -1
  590. package/dist/sdk/history-analytics.js +1 -1
  591. package/dist/sdk/history-compact.js +1 -1
  592. package/dist/sdk/history-mcp.js +1 -1
  593. package/dist/sdk/history-provenance.js +1 -1
  594. package/dist/sdk/history-read.js +1 -1
  595. package/dist/sdk/history-redact.js +1 -1
  596. package/dist/sdk/history-repair.js +1 -1
  597. package/dist/sdk/improvement-ledger-validation.js +1 -1
  598. package/dist/sdk/improvement-ledger.js +2 -2
  599. package/dist/sdk/index.d.ts +1 -1
  600. package/dist/sdk/init-agent-guidance.js +10 -10
  601. package/dist/sdk/init.js +14 -14
  602. package/dist/sdk/invocation-author.js +1 -1
  603. package/dist/sdk/item-children.js +1 -1
  604. package/dist/sdk/item-metadata-index.js +1 -1
  605. package/dist/sdk/item-schedule.js +1 -1
  606. package/dist/sdk/item-transaction.js +1 -1
  607. package/dist/sdk/learnings.js +1 -1
  608. package/dist/sdk/lifecycle/append.js +3 -3
  609. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  610. package/dist/sdk/lifecycle/claim.js +1 -1
  611. package/dist/sdk/lifecycle/cli-input.js +1 -1
  612. package/dist/sdk/lifecycle/close-many.js +1 -1
  613. package/dist/sdk/lifecycle/close.js +1 -1
  614. package/dist/sdk/lifecycle/copy.js +1 -1
  615. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  616. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  617. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  618. package/dist/sdk/lifecycle/create.js +1 -1
  619. package/dist/sdk/lifecycle/delete.js +1 -1
  620. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  621. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  622. package/dist/sdk/lifecycle/focus.js +1 -1
  623. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  624. package/dist/sdk/lifecycle/item-revision.js +1 -1
  625. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  626. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  627. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  628. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  629. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  630. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  631. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  632. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  633. package/dist/sdk/lifecycle/plan.js +1 -1
  634. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  635. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  636. package/dist/sdk/lifecycle/reopen.js +1 -1
  637. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  638. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  639. package/dist/sdk/lifecycle/restore.js +1 -1
  640. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  641. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  642. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  643. package/dist/sdk/lifecycle/task-composition.js +1 -1
  644. package/dist/sdk/lifecycle/update-many.js +1 -1
  645. package/dist/sdk/lifecycle/update.js +2 -2
  646. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  647. package/dist/sdk/lifecycle-completion.js +1 -1
  648. package/dist/sdk/lifecycle-policy.js +1 -1
  649. package/dist/sdk/linked-artifacts.js +2 -2
  650. package/dist/sdk/mcp/apps.js +5 -5
  651. package/dist/sdk/mcp/authorization.js +1 -1
  652. package/dist/sdk/mcp/discovery.js +1 -1
  653. package/dist/sdk/mcp/executable.js +4 -4
  654. package/dist/sdk/mcp/interactions.js +1 -1
  655. package/dist/sdk/mcp/protocol.js +1 -1
  656. package/dist/sdk/mcp/skills.js +3 -3
  657. package/dist/sdk/mcp/subscriptions.js +1 -1
  658. package/dist/sdk/mcp/tasks.js +2 -2
  659. package/dist/sdk/mcp/transport.js +1 -1
  660. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  661. package/dist/sdk/merge/driver.js +7 -7
  662. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  663. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  664. package/dist/sdk/merge/index.js +1 -1
  665. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  666. package/dist/sdk/merge/install.js +6 -6
  667. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  668. package/dist/sdk/merge/receipt-operation.js +1 -1
  669. package/dist/sdk/merge/receipt-schema.js +1 -1
  670. package/dist/sdk/merge/receipts.js +4 -4
  671. package/dist/sdk/merge/reconcile.js +1 -1
  672. package/dist/sdk/merge/settlement-hook.js +4 -4
  673. package/dist/sdk/merge/stage.js +1 -1
  674. package/dist/sdk/merge/three-way.js +9 -9
  675. package/dist/sdk/merge/worktree-config.js +2 -2
  676. package/dist/sdk/merge.js +1 -1
  677. package/dist/sdk/mutation-events.js +1 -1
  678. package/dist/sdk/mutation-guard.js +1 -1
  679. package/dist/sdk/notes.js +1 -1
  680. package/dist/sdk/output/fit-envelope.js +1 -1
  681. package/dist/sdk/output/list-envelope.js +1 -1
  682. package/dist/sdk/output/table-rows.js +1 -1
  683. package/dist/sdk/output-contracts.js +1 -1
  684. package/dist/sdk/output-projection.js +1 -1
  685. package/dist/sdk/output-token-accounting.js +1 -1
  686. package/dist/sdk/output.js +2 -2
  687. package/dist/sdk/ownership-source.js +1 -1
  688. package/dist/sdk/package-import-adapters.js +1 -1
  689. package/dist/sdk/package-migrations.js +1 -1
  690. package/dist/sdk/package-runtime-options.js +1 -1
  691. package/dist/sdk/pagination.js +1 -1
  692. package/dist/sdk/profile.js +5 -5
  693. package/dist/sdk/provenance.js +1 -1
  694. package/dist/sdk/public-surface.json +1 -1
  695. package/dist/sdk/query/activity.js +1 -1
  696. package/dist/sdk/query/aggregate.js +1 -1
  697. package/dist/sdk/query/calendar.js +4 -4
  698. package/dist/sdk/query/complete-list.js +1 -1
  699. package/dist/sdk/query/context.js +2 -2
  700. package/dist/sdk/query/declared-blockers.js +1 -1
  701. package/dist/sdk/query/duplicate-candidates.js +1 -1
  702. package/dist/sdk/query/get-facet-roots.js +1 -1
  703. package/dist/sdk/query/get.js +1 -1
  704. package/dist/sdk/query/history.js +1 -1
  705. package/dist/sdk/query/item-filter-options.js +0 -1
  706. package/dist/sdk/query/light-metadata.js +1 -1
  707. package/dist/sdk/query/list-filter-shared.js +1 -1
  708. package/dist/sdk/query/list.js +1 -1
  709. package/dist/sdk/query/multi-value-filters.js +1 -1
  710. package/dist/sdk/query/next-ranking-policy.js +1 -1
  711. package/dist/sdk/query/next-ready-budget.js +1 -1
  712. package/dist/sdk/query/next.js +2 -2
  713. package/dist/sdk/query/parsers.js +1 -1
  714. package/dist/sdk/query/projection-contracts.js +1 -1
  715. package/dist/sdk/query/search/corpus.js +2 -2
  716. package/dist/sdk/query/search/filters.js +1 -1
  717. package/dist/sdk/query/search/input.js +1 -1
  718. package/dist/sdk/query/search/lexical.js +1 -1
  719. package/dist/sdk/query/search/response.js +1 -1
  720. package/dist/sdk/query/search/semantic.js +3 -3
  721. package/dist/sdk/query/search/types.js +0 -1
  722. package/dist/sdk/query/search-contracts.js +1 -1
  723. package/dist/sdk/query/search-pagination.js +1 -1
  724. package/dist/sdk/query/search-rendering.js +1 -1
  725. package/dist/sdk/query/search.js +1 -1
  726. package/dist/sdk/query/window-pagination.js +1 -1
  727. package/dist/sdk/query/workspace-contracts.js +1 -1
  728. package/dist/sdk/read-output/continuation.js +1 -1
  729. package/dist/sdk/read-output/extension.js +1 -1
  730. package/dist/sdk/read-output/options.js +1 -1
  731. package/dist/sdk/read-output/positional-rows.js +1 -1
  732. package/dist/sdk/read-output/provenance.js +1 -1
  733. package/dist/sdk/read-output/session-result.js +0 -1
  734. package/dist/sdk/read-output/surfaces.js +1 -1
  735. package/dist/sdk/read-output/tail-retention.js +1 -1
  736. package/dist/sdk/read-output-budget.js +1 -1
  737. package/dist/sdk/read-output-contracts.d.ts +11 -0
  738. package/dist/sdk/read-output-contracts.js +1 -1
  739. package/dist/sdk/read-output-rows.js +1 -1
  740. package/dist/sdk/read-output-session.js +1 -1
  741. package/dist/sdk/relationship-analytics.js +1 -1
  742. package/dist/sdk/relationship-context.js +1 -1
  743. package/dist/sdk/relationship-history.js +6 -6
  744. package/dist/sdk/relationship-kinds/contract.js +1 -1
  745. package/dist/sdk/relationships.js +1 -1
  746. package/dist/sdk/reproducibility/process.js +1 -1
  747. package/dist/sdk/runtime/actions.js +1 -1
  748. package/dist/sdk/runtime/context.js +1 -1
  749. package/dist/sdk/runtime/mutation-admission.js +1 -1
  750. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  751. package/dist/sdk/runtime/schema-preview.js +1 -1
  752. package/dist/sdk/runtime/schema.js +1 -1
  753. package/dist/sdk/runtime-action-aliases.js +1 -1
  754. package/dist/sdk/runtime-extended-actions.js +1 -1
  755. package/dist/sdk/runtime-input.d.ts +2 -0
  756. package/dist/sdk/runtime-input.js +1 -1
  757. package/dist/sdk/runtime-primitives.js +1 -1
  758. package/dist/sdk/runtime-public-contracts.js +0 -1
  759. package/dist/sdk/runtime-stats-options.js +1 -1
  760. package/dist/sdk/runtime.d.ts +5 -3
  761. package/dist/sdk/runtime.js +1 -1
  762. package/dist/sdk/scheduling-shortcuts.js +1 -1
  763. package/dist/sdk/schema/field-flag-spelling.d.ts +22 -0
  764. package/dist/sdk/schema/field-flag-spelling.js +2 -0
  765. package/dist/sdk/schema/field-option-collisions.js +2 -0
  766. package/dist/sdk/schema-migration.js +4 -4
  767. package/dist/sdk/schema.js +7 -7
  768. package/dist/sdk/search-refresh-worker.js +1 -1
  769. package/dist/sdk/similarity-scoring.js +1 -1
  770. package/dist/sdk/similarity.js +1 -1
  771. package/dist/sdk/start-task-status.js +1 -1
  772. package/dist/sdk/stats.js +1 -1
  773. package/dist/sdk/structured-mutations.js +1 -1
  774. package/dist/sdk/telemetry-flush.js +1 -1
  775. package/dist/sdk/telemetry.js +4 -4
  776. package/dist/sdk/templates.js +3 -3
  777. package/dist/sdk/test/batch.js +2 -2
  778. package/dist/sdk/test/command-args.js +1 -1
  779. package/dist/sdk/test/command-resolution.js +2 -2
  780. package/dist/sdk/test/entry.js +2 -2
  781. package/dist/sdk/test/execution-receipts.js +2 -2
  782. package/dist/sdk/test/execution.js +5 -5
  783. package/dist/sdk/test/json-path.js +1 -1
  784. package/dist/sdk/test/linked-command-detection.js +1 -1
  785. package/dist/sdk/test/measurements.js +1 -1
  786. package/dist/sdk/test/parsers.js +1 -1
  787. package/dist/sdk/test/prerequisites.js +1 -1
  788. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  789. package/dist/sdk/test/run-phases.js +1 -1
  790. package/dist/sdk/test/runs.js +1 -1
  791. package/dist/sdk/test/trust.js +2 -2
  792. package/dist/sdk/test/update.js +1 -1
  793. package/dist/sdk/test/workspace-snapshot.js +1 -1
  794. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  795. package/dist/sdk/traceability/source-traceability.js +2 -2
  796. package/dist/sdk/tracker-root-discovery.js +1 -1
  797. package/dist/sdk/transactions/item-finalization.js +1 -1
  798. package/dist/sdk/workspace-contracts-cache.js +1 -1
  799. package/dist/sdk/workspace-contracts.js +1 -1
  800. package/dist/sdk/workspace-memory.js +2 -2
  801. package/dist/sdk/workspace-snapshot.js +5 -5
  802. package/dist/sdk/workspace-transaction-gc.js +1 -1
  803. package/dist/sdk/workspace-transaction.js +2 -2
  804. package/dist/sdk/workspace.js +6 -6
  805. package/dist/types/index.js +1 -1
  806. package/dist/types.js +1 -1
  807. package/docs/COMMANDS.md +1 -1
  808. package/docs/EXTENSIONS.md +2 -2
  809. package/docs/READ_OUTPUT_CONTRACTS.md +2 -0
  810. package/docs/SDK.md +94 -5
  811. package/docs/SDK_AUDITED_MUTATIONS.md +11 -0
  812. package/marketplace.json +1 -1
  813. package/package.json +2 -1
  814. package/packages/pm-beads/package.json +1 -1
  815. package/packages/pm-calendar/package.json +1 -1
  816. package/packages/pm-command-kit/package.json +1 -1
  817. package/packages/pm-digital-twin/package.json +1 -1
  818. package/packages/pm-governance-audit/package.json +1 -1
  819. package/packages/pm-guide-shell/package.json +1 -1
  820. package/packages/pm-kanban/package.json +1 -1
  821. package/packages/pm-lifecycle-hooks/package.json +1 -1
  822. package/packages/pm-linked-test-adapters/package.json +1 -1
  823. package/packages/pm-search-advanced/package.json +1 -1
  824. package/packages/pm-templates/package.json +1 -1
  825. package/packages/pm-todos/package.json +1 -1
  826. package/packages/pm-vcs/package.json +1 -1
  827. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  828. package/plugins/pm-claude/package.json +1 -1
  829. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  830. package/plugins/pm-codex/package.json +1 -1
  831. package/plugins/pm-codex/plugin.json +1 -1
  832. package/runtime-dependencies.json +1 -1
  833. package/scripts/finalize-build.mjs +63 -24
  834. package/scripts/prepare-build-cache.mjs +28 -1
  835. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
  836. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
  837. package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
  838. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
  839. package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
  840. package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
  841. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
  842. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  843. package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
  844. package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
  845. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
  846. package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
  847. package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
  848. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
  849. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  850. package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
  851. package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
  852. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  853. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  854. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
  855. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  856. package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
  857. package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
  858. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
  859. package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
  860. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
  861. package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
  862. package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
  863. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  864. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  865. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  866. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  867. package/dist/cli-bundle/chunks/item-revision-4QBMZXKX.js +0 -2
  868. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
  869. package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
  870. package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
  871. package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
  872. package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
  873. package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
  874. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  875. package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
  876. package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
  877. package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
  878. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  879. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  880. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
  881. package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
  882. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
  883. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
  884. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
  885. package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
  886. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  888. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  892. package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
  893. package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
  894. package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
  895. package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
  896. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
  897. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
  898. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  899. package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
  900. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
  901. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
  902. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
  903. package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
  904. package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
  905. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
  906. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  907. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  908. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
  909. package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
  910. package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
  911. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  912. package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="12066389-daef-5fce-b7a6-0ecffa926d66")}catch{}})();import{levenshteinDistanceWithinLimit}from"../../core/shared/levenshtein.js";import{PM_COMMAND_ALIAS_CONTRACTS,resolvePmCommandAlias,resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";function resolveMisnestedCommandPath(unknownPath,availablePaths){const tokens=unknownPath.trim().split(/\s+/u);if(!(tokens.length<2||availablePaths.includes(tokens.join(" "))))for(let namespaceLength=1;namespaceLength<tokens.length;namespaceLength+=1){if(!availablePaths.includes(tokens.slice(0,namespaceLength).join(" ")))return;const suffix=tokens.slice(namespaceLength).join(" "),alias=resolvePmCommandAlias(suffix),candidates=new Set(availablePaths.filter(candidate=>candidate===suffix||candidate.endsWith(` ${suffix}`)||candidate===alias?.canonical).map(candidate=>resolvePmCommandAlias(candidate)?.canonical??candidate).filter(candidate=>availablePaths.includes(candidate)));if(candidates.size>0)return candidates.size===1?[...candidates][0]:void 0}}const COMMAND_SYNONYMS={add:["create","append"],fetch:["get"],inspect:["get","health"],log:["history","comments","notes"],ls:["list"],pause:["release"],read:["get"],remove:["delete"],rm:["delete"],show:["get"],start:["start-task"]};function scoreCommandPathMatch(commandPath,queryToken){const normalizedPath=commandPath.trim().toLowerCase(),normalizedToken=queryToken.trim().toLowerCase();if(normalizedToken.length===0)return Number.POSITIVE_INFINITY;const segments=normalizedPath.split(" "),semanticIndex=COMMAND_SYNONYMS[normalizedToken]?.indexOf(resolvePmCommandOperation(normalizedPath));if(semanticIndex!==void 0&&semanticIndex>=0)return semanticIndex;if(normalizedPath===normalizedToken)return 10;if(segments.includes(normalizedToken))return 11;if(segments.some(segment=>segment.startsWith(normalizedToken)))return 12;const maxDistance=normalizedToken.length>=5?2:1;let bestDistance=Number.POSITIVE_INFINITY;for(const segment of segments){const distance=levenshteinDistanceWithinLimit(segment,normalizedToken,maxDistance);distance!==null&&(bestDistance=Math.min(bestDistance,distance))}return Number.isFinite(bestDistance)?20+bestDistance:normalizedPath.includes(normalizedToken)?30:Number.POSITIVE_INFINITY}function rankCommandPaths(commandPaths,queryToken){return commandPaths.map(path=>({path,score:scoreCommandPathMatch(path,queryToken)})).filter(entry=>Number.isFinite(entry.score)).sort((left,right)=>left.score!==right.score?left.score-right.score:left.path===right.path?0:left.path<right.path?-1:1).map(entry=>entry.path)}function canonicalizeCommandSuggestions(candidates,availablePaths,queryToken){const available=new Set(availablePaths),aliases=PM_COMMAND_ALIAS_CONTRACTS.filter(alias=>alias.lifecycle==="deprecated").slice().sort((left,right)=>right.alias.length-left.alias.length),preferred=[],resolved=candidates.flatMap(candidate=>{const alias=aliases.find(entry=>candidate===entry.alias||candidate.startsWith(`${entry.alias} `));let canonical=candidate;if(alias){const suffix=candidate.slice(alias.alias.length);if(!available.has(`${alias.canonical}${suffix}`))return[];canonical=`${alias.canonical_argv.join(" ")}${suffix}`}return queryToken!==void 0&&scoreCommandPathMatch(candidate,queryToken)<10&&preferred.push(canonical),[canonical]});return[...new Set(preferred.length>0?preferred:resolved)]}export{canonicalizeCommandSuggestions,rankCommandPaths,resolveMisnestedCommandPath,scoreCommandPathMatch};
1
+ import{levenshteinDistanceWithinLimit as d}from"../../core/shared/levenshtein.js";import{PM_COMMAND_ALIAS_CONTRACTS as h,resolvePmCommandAlias as m,resolvePmCommandOperation as p}from"../cli-contracts/command-aliases.js";function C(a,s){const e=a.trim().split(/\s+/u);if(!(e.length<2||s.includes(e.join(" "))))for(let t=1;t<e.length;t+=1){if(!s.includes(e.slice(0,t).join(" ")))return;const r=e.slice(t).join(" "),o=m(r),c=new Set(s.filter(n=>n===r||n.endsWith(` ${r}`)||n===o?.canonical).map(n=>m(n)?.canonical??n).filter(n=>s.includes(n)));if(c.size>0)return c.size===1?[...c][0]:void 0}}const I={add:["create","append"],fetch:["get"],inspect:["get","health"],log:["history","comments","notes"],ls:["list"],pause:["release"],read:["get"],remove:["delete"],rm:["delete"],show:["get"],start:["start-task"]};function f(a,s){const e=a.trim().toLowerCase(),t=s.trim().toLowerCase();if(t.length===0)return Number.POSITIVE_INFINITY;const r=e.split(" "),o=I[t]?.indexOf(p(e));if(o!==void 0&&o>=0)return o;if(e===t)return 10;if(r.includes(t))return 11;if(r.some(i=>i.startsWith(t)))return 12;const c=t.length>=5?2:1;let n=Number.POSITIVE_INFINITY;for(const i of r){const l=d(i,t,c);l!==null&&(n=Math.min(n,l))}return Number.isFinite(n)?20+n:e.includes(t)?30:Number.POSITIVE_INFINITY}function S(a,s){return a.map(e=>({path:e,score:f(e,s)})).filter(e=>Number.isFinite(e.score)).sort((e,t)=>e.score!==t.score?e.score-t.score:e.path===t.path?0:e.path<t.path?-1:1).map(e=>e.path)}function M(a,s,e){const t=new Set(s),r=h.filter(n=>n.lifecycle==="deprecated").slice().sort((n,i)=>i.alias.length-n.alias.length),o=[],c=a.flatMap(n=>{const i=r.find(u=>n===u.alias||n.startsWith(`${u.alias} `));let l=n;if(i){const u=n.slice(i.alias.length);if(!t.has(`${i.canonical}${u}`))return[];l=`${i.canonical_argv.join(" ")}${u}`}return e!==void 0&&f(n,e)<10&&o.push(l),[l]});return[...new Set(o.length>0?o:c)]}export{M as canonicalizeCommandSuggestions,S as rankCommandPaths,C as resolveMisnestedCommandPath,f as scoreCommandPathMatch};
2
2
  //# sourceMappingURL=command-suggestions.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();const CREATE_REPEATABLE_CLEAR_FLAGS={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function resolveCreateExplicitEmptyFlag(optionKey){return CREATE_REPEATABLE_CLEAR_FLAGS[optionKey]}function supportsCreateExplicitEmpty(optionKey){return resolveCreateExplicitEmptyFlag(optionKey)!==void 0}export{resolveCreateExplicitEmptyFlag,supportsCreateExplicitEmpty};
1
+ const t={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function r(e){return t[e]}function n(e){return r(e)!==void 0}export{r as resolveCreateExplicitEmptyFlag,n as supportsCreateExplicitEmpty};
2
2
  //# sourceMappingURL=create-option-policy.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="544840da-22f5-5734-81ec-e12c5612545c")}catch{}})();const HARNESS_NAMESPACE_PATTERN=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,MAX_AUTHOR_LENGTH=128,MAX_OBSERVED_AUTHORS=1e4;function requireLegacyAuthor(value){const author=value?.trim();if(!author||author==="__proto__"||author.length>128)throw new Error("A legacy author must contain 1-128 characters.");return author}function requireCanonicalHarness(value){const harness=value?.trim().toLowerCase();if(!harness||!HARNESS_NAMESPACE_PATTERN.test(harness))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return harness}function orderedAliases(aliases){return Object.fromEntries(Object.entries(aliases).sort(([left],[right])=>left.localeCompare(right)))}function countResidualAuthors(observed,aliases){const residual=new Set;for(const raw of(observed??[]).slice(0,1e4)){const author=raw.trim().slice(0,128);author.length===0||author.startsWith("harness:")||Object.hasOwn(aliases,author)||residual.add(author)}return residual.size}function applyAddOperation(aliases,input){const legacyAuthor=requireLegacyAuthor(input.legacy_author),canonicalHarness=requireCanonicalHarness(input.canonical_harness);if(legacyAuthor===canonicalHarness||legacyAuthor===`harness:${canonicalHarness}`||legacyAuthor.startsWith("harness:"))throw new Error(`The legacy author "${legacyAuthor}" is already canonical and must not be aliased.`);return aliases[legacyAuthor]===canonicalHarness?!1:(aliases[legacyAuthor]=canonicalHarness,!0)}function applyVocabularyOperation(aliases,input){if(input.operation==="add")return applyAddOperation(aliases,input);if(input.operation==="remove"){const legacyAuthor=requireLegacyAuthor(input.legacy_author);return Object.hasOwn(aliases,legacyAuthor)?(delete aliases[legacyAuthor],!0):!1}if(input.operation==="clear"){const changed=Object.keys(aliases).length>0;for(const key of Object.keys(aliases))delete aliases[key];return changed}const exhaustive=input.operation;throw new Error(`Unsupported vocabulary operation: ${String(exhaustive)}`)}function summarizeAgentIdentityVocabulary(vocabulary){return{version:vocabulary?.version??1,alias_count:Object.keys(vocabulary?.aliases??{}).length}}function planAgentIdentityVocabularyMutation(current,input){const versionBefore=current?.version??1,aliases={...current?.aliases},changed=applyVocabularyOperation(aliases,input),vocabulary={version:changed?versionBefore+1:versionBefore,aliases:orderedAliases(aliases)};return{vocabulary,preview:{operation:input.operation,changed,version_before:versionBefore,version_after:vocabulary.version,alias_count:Object.keys(vocabulary.aliases).length,residual_author_count:countResidualAuthors(input.observed_authors,vocabulary.aliases)}}}export{planAgentIdentityVocabularyMutation,summarizeAgentIdentityVocabulary};
1
+ const c=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,f=128,A=1e4;function s(r){const e=r?.trim();if(!e||e==="__proto__"||e.length>128)throw new Error("A legacy author must contain 1-128 characters.");return e}function i(r){const e=r?.trim().toLowerCase();if(!e||!c.test(e))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return e}function u(r){return Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)))}function l(r,e){const t=new Set;for(const o of(r??[]).slice(0,1e4)){const n=o.trim().slice(0,128);n.length===0||n.startsWith("harness:")||Object.hasOwn(e,n)||t.add(n)}return t.size}function h(r,e){const t=s(e.legacy_author),o=i(e.canonical_harness);if(t===o||t===`harness:${o}`||t.startsWith("harness:"))throw new Error(`The legacy author "${t}" is already canonical and must not be aliased.`);return r[t]===o?!1:(r[t]=o,!0)}function _(r,e){if(e.operation==="add")return h(r,e);if(e.operation==="remove"){const o=s(e.legacy_author);return Object.hasOwn(r,o)?(delete r[o],!0):!1}if(e.operation==="clear"){const o=Object.keys(r).length>0;for(const n of Object.keys(r))delete r[n];return o}const t=e.operation;throw new Error(`Unsupported vocabulary operation: ${String(t)}`)}function d(r){return{version:r?.version??1,alias_count:Object.keys(r?.aliases??{}).length}}function y(r,e){const t=r?.version??1,o={...r?.aliases},n=_(o,e),a={version:n?t+1:t,aliases:u(o)};return{vocabulary:a,preview:{operation:e.operation,changed:n,version_before:t,version_after:a.version,alias_count:Object.keys(a.aliases).length,residual_author_count:l(e.observed_authors,a.aliases)}}}export{y as planAgentIdentityVocabularyMutation,d as summarizeAgentIdentityVocabulary};
2
2
  //# sourceMappingURL=identity-config.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8efedca0-725e-520f-ad06-825a0cccddaa")}catch{}})();import{findBootstrapCommandTokenIndex}from"../cli-contracts/bootstrap-command-scanner.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";const ITEM_ID_ALIAS_COMMANDS=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]),ITEM_ID_ALIAS_SUBCOMMANDS=new Map([["files","discover"],["item","complete"]]),TRAILING_POSITIONAL_COUNTS=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function supportsItemIdAlias(commandName){const normalized=resolvePmCommandOperation(commandName?.trim().toLowerCase()??"");return ITEM_ID_ALIAS_COMMANDS.has(normalized)||ITEM_ID_ALIAS_SUBCOMMANDS.has(normalized)}function resolveNamespacedItemAddressIndex(argv,commandIndex,commandName){const fallback=ITEM_ID_ALIAS_COMMANDS.has(commandName)?commandIndex+1:void 0,leafOffset=findBootstrapCommandTokenIndex(argv.slice(commandIndex+1));if(leafOffset===void 0)return fallback;const leafIndex=commandIndex+1+leafOffset,candidate=`${commandName} ${argv[leafIndex]}`,operation=resolvePmCommandOperation(candidate);return operation===candidate?commandName==="item"&&argv[leafIndex]==="complete"?leafIndex+1:fallback:supportsItemIdAlias(operation)?resolveItemAddressIndex(argv,leafIndex,operation):void 0}function resolveItemAddressIndex(argv,commandIndex,commandName){if(["history","context","ctx","update","close","item"].includes(commandName))return resolveNamespacedItemAddressIndex(argv,commandIndex,commandName);const declaredSubcommand=ITEM_ID_ALIAS_SUBCOMMANDS.get(commandName);if(declaredSubcommand===void 0)return commandIndex+1;const usesDeclaredSubcommand=argv[commandIndex+1]?.toLowerCase()===declaredSubcommand;return commandIndex+(usesDeclaredSubcommand?2:1)}function buildFlagContractMap(commandPath){const contractsByFlag=new Map;for(const contract of resolveSubcommandFlagContractsForCommand(commandPath))for(const flag of[contract.flag,contract.short,...contract.aliases??[]])flag&&contractsByFlag.set(flag,contract);return contractsByFlag}function collectNamedItemIds(argv){const namedIds=[];for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;token==="--id"?(namedIds.push({index,consumed:2,value:argv[index+1]}),index+=1):token.startsWith("--id=")&&namedIds.push({index,consumed:1,value:token.slice(5)})}return namedIds}function consumesSeparateFlagValue(token,nextToken,contractsByFlag){if(token.indexOf("=")>=0||nextToken===void 0||nextToken.startsWith("-"))return!1;const contract=contractsByFlag.get(token);return contract!==void 0&&contract.value_type!=="boolean"}function hasPositionalItemId(argv,addressIndex,commandPath,namedIndex,contractsByFlag){let trailingPositionals=0;for(let index=addressIndex;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--id"){index+=1;continue}if(!token.startsWith("--id=")){if(!token.startsWith("-")){if(index<namedIndex)return!0;trailingPositionals+=1;continue}consumesSeparateFlagValue(token,argv[index+1],contractsByFlag)&&(index+=1)}}return trailingPositionals>(TRAILING_POSITIONAL_COUNTS.get(resolvePmCommandOperation(commandPath))??0)}function normalizeItemAddressInvocation(argv){const commandIndex=findBootstrapCommandTokenIndex(argv),commandName=commandIndex===void 0?void 0:argv[commandIndex]?.toLowerCase();if(commandName!=="context"&&commandName!=="ctx"&&!supportsItemIdAlias(commandName))return{argv:[...argv],changed:!1,conflict:!1};const addressIndex=resolveItemAddressIndex(argv,commandIndex,commandName);if(addressIndex===void 0)return{argv:[...argv],changed:!1,conflict:!1};const commandPath=addressIndex>commandIndex+1?`${resolvePmCommandOperation(argv.slice(commandIndex,addressIndex-1).join(" "))} ${argv[addressIndex-1]}`:commandName,contractsByFlag=buildFlagContractMap(commandPath),namedIds=collectNamedItemIds(argv),named=namedIds[0];if(!named||!named.value?.trim())return{argv:[...argv],changed:!1,conflict:!1};if(namedIds.length>1||hasPositionalItemId(argv,addressIndex,commandPath,named.index,contractsByFlag))return{argv:[...argv],changed:!1,conflict:!0,itemId:named.value};const withoutNamed=[...argv.slice(0,named.index),...argv.slice(named.index+named.consumed)],normalizedCommandIndex=findBootstrapCommandTokenIndex(withoutNamed),normalizedAddressIndex=resolveItemAddressIndex(withoutNamed,normalizedCommandIndex,commandName);return withoutNamed.splice(normalizedAddressIndex,0,named.value),{argv:withoutNamed,changed:!0,conflict:!1,itemId:named.value}}export{normalizeItemAddressInvocation,supportsItemIdAlias};
1
+ import{findBootstrapCommandTokenIndex as l}from"../cli-contracts/bootstrap-command-scanner.js";import{resolvePmCommandOperation as d}from"../cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand as x}from"../cli-contracts/flag-contracts.js";const u=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]),m=new Map([["files","discover"],["item","complete"]]),A=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function p(e){const n=d(e?.trim().toLowerCase()??"");return u.has(n)||m.has(n)}function C(e,n,t){const s=u.has(t)?n+1:void 0,c=l(e.slice(n+1));if(c===void 0)return s;const r=n+1+c,i=`${t} ${e[r]}`,o=d(i);return o===i?t==="item"&&e[r]==="complete"?r+1:s:p(o)?f(e,r,o):void 0}function f(e,n,t){if(["history","context","ctx","update","close","item"].includes(t))return C(e,n,t);const s=m.get(t);if(s===void 0)return n+1;const c=e[n+1]?.toLowerCase()===s;return n+(c?2:1)}function S(e){const n=new Map;for(const t of x(e))for(const s of[t.flag,t.short,...t.aliases??[]])s&&n.set(s,t);return n}function M(e){const n=[];for(let t=0;t<e.length;t+=1){const s=e[t];if(s==="--")break;s==="--id"?(n.push({index:t,consumed:2,value:e[t+1]}),t+=1):s.startsWith("--id=")&&n.push({index:t,consumed:1,value:s.slice(5)})}return n}function y(e,n,t){if(e.indexOf("=")>=0||n===void 0||n.startsWith("-"))return!1;const c=t.get(e);return c!==void 0&&c.value_type!=="boolean"}function _(e,n,t,s,c){let r=0;for(let i=n;i<e.length;i+=1){const o=e[i];if(o==="--")break;if(o==="--id"){i+=1;continue}if(!o.startsWith("--id=")){if(!o.startsWith("-")){if(i<s)return!0;r+=1;continue}y(o,e[i+1],c)&&(i+=1)}}return r>(A.get(d(t))??0)}function w(e){const n=l(e),t=n===void 0?void 0:e[n]?.toLowerCase();if(t!=="context"&&t!=="ctx"&&!p(t))return{argv:[...e],changed:!1,conflict:!1};const s=f(e,n,t);if(s===void 0)return{argv:[...e],changed:!1,conflict:!1};const c=s>n+1?`${d(e.slice(n,s-1).join(" "))} ${e[s-1]}`:t,r=S(c),i=M(e),o=i[0];if(!o||!o.value?.trim())return{argv:[...e],changed:!1,conflict:!1};if(i.length>1||_(e,s,c,o.index,r))return{argv:[...e],changed:!1,conflict:!0,itemId:o.value};const a=[...e.slice(0,o.index),...e.slice(o.index+o.consumed)],I=l(a),h=f(a,I,t);return a.splice(h,0,o.value),{argv:a,changed:!0,conflict:!1,itemId:o.value}}export{w as normalizeItemAddressInvocation,p as supportsItemIdAlias};
2
2
  //# sourceMappingURL=item-addressing.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b58016fa-9817-5421-a4a3-78d1b1d22937")}catch{}})();import{findBootstrapCommandTokenIndex,GLOBAL_VALUE_CONSUMING_FLAGS,BOOTSTRAP_BOOLEAN_FLAGS}from"../cli-contracts/bootstrap-command-scanner.js";import{findPmNamespacedCommand}from"../cli-contracts/command-aliases.js";import{assertLinkedTestCommand,normalizeStructuredLinkedTestEntry,STRUCTURED_LINKED_TEST_KEYS}from"../test/entry.js";import{parseCsvKv}from"../../core/item/parse.js";function hasAdmittedTestCommand(command){if(!command?.trim())return!1;try{return assertLinkedTestCommand(command.trim()),!0}catch{return!1}}function structuredTestReplacement(value){try{const{command,...metadata}=normalizeStructuredLinkedTestEntry(parseCsvKv(value,"--add"),"--add");return hasAdmittedTestCommand(command)?["--add",value]:["command=<actual command>",...Object.entries(metadata).map(([key,entry])=>`${key}=${JSON.stringify(entry)}`)].join(",")}catch{return}}function hasOnlyPresentationSuffix(args){for(let index=0;index<args.length;index+=1){const token=args[index];if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)&&token!=="--all")continue;const flag=token.split("=",1)[0];if(!GLOBAL_VALUE_CONSUMING_FLAGS.has(flag)||["--author","--path","--pm-path"].includes(flag))return!1;if(!token.includes("=")){const value=args[++index];if(value===void 0||value.startsWith("-"))return!1}}return!0}function positionalOperands(command,argv){const start=findBootstrapCommandTokenIndex(argv);if(start===void 0)return;const namespaced=findPmNamespacedCommand(argv.slice(start));if((namespaced?.alias??argv[start])!==command)return;const idIndex=start+(namespaced?.canonical_argv.length??1),id=argv[idIndex],value=argv[idIndex+1];if(!(!id||id==="add"||id.startsWith("-"))&&!(!value||value.startsWith("-"))&&hasOnlyPresentationSuffix(argv.slice(idIndex+2)))return{idIndex,value}}function replacementArgs(command,value){const key=/^[A-Za-z_][A-Za-z0-9_]*=/u.exec(value)?.[0];if(command==="test")return key?["command=","cmd="].includes(key)?structuredTestReplacement(value):STRUCTURED_LINKED_TEST_KEYS.includes(key.slice(0,-1))?`command=<actual command>,${value}`:void 0:hasAdmittedTestCommand(value)?["--add-json",JSON.stringify({command:value})]:"command=<actual command>";if(!(key&&key!=="path="))return["--add",key?value:`path=${JSON.stringify(value)}`]}function resolveLinkedResourcePositionalRecovery(command,argv){if(command===void 0||!["files","docs","test"].includes(command))return;const operands=positionalOperands(command,argv);if(!operands)return;const{idIndex,value}=operands,itemId=argv[idIndex],replacement=replacementArgs(command,value);if(replacement!==void 0)return typeof replacement=="string"?{itemId,value,templateArgs:[...argv.slice(0,idIndex+1),"--add",replacement,...argv.slice(idIndex+2)]}:{itemId,value,retryArgs:[...argv.slice(0,idIndex+1),...replacement,...argv.slice(idIndex+2)]}}export{resolveLinkedResourcePositionalRecovery};
1
+ import{findBootstrapCommandTokenIndex as f,GLOBAL_VALUE_CONSUMING_FLAGS as u,BOOTSTRAP_BOOLEAN_FLAGS as a}from"../cli-contracts/bootstrap-command-scanner.js";import{findPmNamespacedCommand as m}from"../cli-contracts/command-aliases.js";import{assertLinkedTestCommand as l,normalizeStructuredLinkedTestEntry as p,STRUCTURED_LINKED_TEST_KEYS as h}from"../test/entry.js";import{parseCsvKv as A}from"../../core/item/parse.js";function c(t){if(!t?.trim())return!1;try{return l(t.trim()),!0}catch{return!1}}function O(t){try{const{command:n,...e}=p(A(t,"--add"),"--add");return c(n)?["--add",t]:["command=<actual command>",...Object.entries(e).map(([r,d])=>`${r}=${JSON.stringify(d)}`)].join(",")}catch{return}}function S(t){for(let n=0;n<t.length;n+=1){const e=t[n];if(a.has(e)&&e!=="--all")continue;const i=e.split("=",1)[0];if(!u.has(i)||["--author","--path","--pm-path"].includes(i))return!1;if(!e.includes("=")){const r=t[++n];if(r===void 0||r.startsWith("-"))return!1}}return!0}function y(t,n){const e=f(n);if(e===void 0)return;const i=m(n.slice(e));if((i?.alias??n[e])!==t)return;const d=e+(i?.canonical_argv.length??1),s=n[d],o=n[d+1];if(!(!s||s==="add"||s.startsWith("-"))&&!(!o||o.startsWith("-"))&&S(n.slice(d+2)))return{idIndex:d,value:o}}function T(t,n){const e=/^[A-Za-z_][A-Za-z0-9_]*=/u.exec(n)?.[0];if(t==="test")return e?["command=","cmd="].includes(e)?O(n):h.includes(e.slice(0,-1))?`command=<actual command>,${n}`:void 0:c(n)?["--add-json",JSON.stringify({command:n})]:"command=<actual command>";if(!(e&&e!=="path="))return["--add",e?n:`path=${JSON.stringify(n)}`]}function C(t,n){if(t===void 0||!["files","docs","test"].includes(t))return;const e=y(t,n);if(!e)return;const{idIndex:i,value:r}=e,d=n[i],s=T(t,r);if(s!==void 0)return typeof s=="string"?{itemId:d,value:r,templateArgs:[...n.slice(0,i+1),"--add",s,...n.slice(i+2)]}:{itemId:d,value:r,retryArgs:[...n.slice(0,i+1),...s,...n.slice(i+2)]}}export{C as resolveLinkedResourcePositionalRecovery};
2
2
  //# sourceMappingURL=linked-resource-recovery.js.map
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2b2197f3-7203-52c8-9cc7-f714b33a9306")}catch{}})();const PM_REFUSAL_CLOSURE_EXECUTABLE_CODE_BASELINE=16,PM_REFUSAL_CLOSURE_EXECUTABLE_CANONICAL_CODE_BASELINE=Object.freeze(["bulk_ids_input_empty","bulk_ids_input_missing_path","bulk_ids_input_unreadable","invalid_argument_value","missing_lifecycle_target","missing_required_argument","projection_options_mutually_exclusive","tracker_not_initialized","tracker_root_missing","tracker_root_not_directory","tracker_root_unreadable","unknown_context_intent","unknown_field_projection","unknown_option","unknown_subcommand"]),PM_REFUSAL_CLOSURE_EXECUTABLE_CODE_BASELINE_V2=18,PM_REFUSAL_CLOSURE_EXECUTABLE_CANONICAL_CODE_BASELINE_V2=Object.freeze([...PM_REFUSAL_CLOSURE_EXECUTABLE_CANONICAL_CODE_BASELINE,"manifest_unknown_key","no_version_bounds_declared"].sort((left,right)=>left.localeCompare(right)));function verifyPmRefusalClosureRatchet(report,baseline=PM_REFUSAL_CLOSURE_EXECUTABLE_CODE_BASELINE_V2){return{ok:report.executable_error_code_count>=baseline,baseline,actual:report.executable_error_code_count}}function verifyPmRefusalClosureIdentityRatchet(report,requiredCanonicalCodes=PM_REFUSAL_CLOSURE_EXECUTABLE_CANONICAL_CODE_BASELINE_V2){const executableCanonicalCodes=new Set(report.rows.filter(({disposition})=>disposition==="executable").map(({canonical_code:canonicalCode})=>canonicalCode)),missingRequiredCanonicalCodes=requiredCanonicalCodes.filter(code=>!executableCanonicalCodes.has(code));return{ok:missingRequiredCanonicalCodes.length===0,required_canonical_codes:[...requiredCanonicalCodes],missing_required_canonical_codes:missingRequiredCanonicalCodes}}function evidenceFor(evidence,canonicalCode){const existing=evidence.get(canonicalCode);if(existing)return existing;const created={kinds:new Set,probeIds:new Set};return evidence.set(canonicalCode,created),created}function buildPmRefusalClosureCensus(catalog,closedDomains,grammar){const canonicalByCode=new Map(catalog.map(contract=>[contract.code,contract.canonical_code??contract.code])),evidence=new Map;let closedDomainProbeCount=0,grammarProbeCount=0;for(const contract of catalog){const target=evidenceFor(evidence,contract.canonical_code??contract.code);for(const state of contract.owned_states??[])target.kinds.add("owned_state"),target.probeIds.add(state.probe_id)}for(const contract of closedDomains){const canonical=canonicalByCode.get(contract.error_code);if(canonical===void 0)continue;closedDomainProbeCount+=1;const target=evidenceFor(evidence,canonical);target.kinds.add("closed_domain"),target.probeIds.add(contract.probe_id)}for(const contract of grammar){const canonical=canonicalByCode.get(contract.error_code);if(canonical===void 0)continue;grammarProbeCount+=1;const target=evidenceFor(evidence,canonical);target.kinds.add("grammar"),target.probeIds.add(contract.probe_id)}const rows=catalog.map(contract=>{const canonicalCode=contract.canonical_code??contract.code,joined=evidence.get(canonicalCode),probeIds=[...joined.probeIds].sort();return{code:contract.code,canonical_code:canonicalCode,disposition:probeIds.length>0?"executable":"uncovered",evidence_kinds:[...joined.kinds].sort(),probe_ids:probeIds}}).sort((left,right)=>left.code<right.code?-1:1),uncoveredErrorCodes=rows.filter(({disposition})=>disposition==="uncovered").map(({code})=>code),executableCount=rows.length-uncoveredErrorCodes.length;return{ok:uncoveredErrorCodes.length===0,catalog_error_code_count:rows.length,executable_error_code_count:executableCount,uncovered_error_code_count:uncoveredErrorCodes.length,coverage_fraction:rows.length===0?1:executableCount/rows.length,closed_domain_probe_count:closedDomainProbeCount,grammar_probe_count:grammarProbeCount,uncovered_error_codes:uncoveredErrorCodes,rows}}function renderPmRefusalClosureCensusMarkdown(report){const rows=report.rows.map(row=>`| \`${row.code}\` | \`${row.canonical_code}\` | ${row.disposition} | ${row.evidence_kinds.join(", ")||"none"} | ${row.probe_ids.length} |`);return["# Generated refusal closure census","","Tracker: `pm-f05lsg`.","","Every catalog code is listed. An `uncovered` row is an explicit closure obligation, never an omission or implied approval.","",`- Catalog error codes: ${report.catalog_error_code_count}`,`- Executable error codes: ${report.executable_error_code_count}`,`- Executable-code ratchet floor: ${PM_REFUSAL_CLOSURE_EXECUTABLE_CODE_BASELINE_V2}`,`- Required executable canonical codes: ${PM_REFUSAL_CLOSURE_EXECUTABLE_CANONICAL_CODE_BASELINE_V2.map(code=>`\`${code}\``).join(", ")}`,`- Uncovered error codes: ${report.uncovered_error_code_count}`,`- Coverage fraction: ${report.coverage_fraction.toFixed(6)}`,`- Closed-domain probes: ${report.closed_domain_probe_count}`,`- Grammar probes: ${report.grammar_probe_count}`,"","| Error code | Canonical code | Disposition | Evidence kinds | Probe count |","| --- | --- | --- | --- | --- |",...rows,""].join(`
2
- `)}export{PM_REFUSAL_CLOSURE_EXECUTABLE_CANONICAL_CODE_BASELINE,PM_REFUSAL_CLOSURE_EXECUTABLE_CANONICAL_CODE_BASELINE_V2,PM_REFUSAL_CLOSURE_EXECUTABLE_CODE_BASELINE,PM_REFUSAL_CLOSURE_EXECUTABLE_CODE_BASELINE_V2,buildPmRefusalClosureCensus,renderPmRefusalClosureCensusMarkdown,verifyPmRefusalClosureIdentityRatchet,verifyPmRefusalClosureRatchet};
1
+ const E=16,g=Object.freeze(["bulk_ids_input_empty","bulk_ids_input_missing_path","bulk_ids_input_unreadable","invalid_argument_value","missing_lifecycle_target","missing_required_argument","projection_options_mutually_exclusive","tracker_not_initialized","tracker_root_missing","tracker_root_not_directory","tracker_root_unreadable","unknown_context_intent","unknown_field_projection","unknown_option","unknown_subcommand"]),b=18,f=Object.freeze([...g,"manifest_unknown_key","no_version_bounds_declared"].sort((o,n)=>o.localeCompare(n)));function C(o,n=b){return{ok:o.executable_error_code_count>=n,baseline:n,actual:o.executable_error_code_count}}function k(o,n=f){const r=new Set(o.rows.filter(({disposition:t})=>t==="executable").map(({canonical_code:t})=>t)),_=n.filter(t=>!r.has(t));return{ok:_.length===0,required_canonical_codes:[...n],missing_required_canonical_codes:_}}function s(o,n){const r=o.get(n);if(r)return r;const _={kinds:new Set,probeIds:new Set};return o.set(n,_),_}function v(o,n,r){const _=new Map(o.map(e=>[e.code,e.canonical_code??e.code])),t=new Map;let u=0,l=0;for(const e of o){const c=s(t,e.canonical_code??e.code);for(const d of e.owned_states??[])c.kinds.add("owned_state"),c.probeIds.add(d.probe_id)}for(const e of n){const c=_.get(e.error_code);if(c===void 0)continue;u+=1;const d=s(t,c);d.kinds.add("closed_domain"),d.probeIds.add(e.probe_id)}for(const e of r){const c=_.get(e.error_code);if(c===void 0)continue;l+=1;const d=s(t,c);d.kinds.add("grammar"),d.probeIds.add(e.probe_id)}const a=o.map(e=>{const c=e.canonical_code??e.code,d=t.get(c),m=[...d.probeIds].sort();return{code:e.code,canonical_code:c,disposition:m.length>0?"executable":"uncovered",evidence_kinds:[...d.kinds].sort(),probe_ids:m}}).sort((e,c)=>e.code<c.code?-1:1),i=a.filter(({disposition:e})=>e==="uncovered").map(({code:e})=>e),p=a.length-i.length;return{ok:i.length===0,catalog_error_code_count:a.length,executable_error_code_count:p,uncovered_error_code_count:i.length,coverage_fraction:a.length===0?1:p/a.length,closed_domain_probe_count:u,grammar_probe_count:l,uncovered_error_codes:i,rows:a}}function x(o){const n=o.rows.map(r=>`| \`${r.code}\` | \`${r.canonical_code}\` | ${r.disposition} | ${r.evidence_kinds.join(", ")||"none"} | ${r.probe_ids.length} |`);return["# Generated refusal closure census","","Tracker: `pm-f05lsg`.","","Every catalog code is listed. An `uncovered` row is an explicit closure obligation, never an omission or implied approval.","",`- Catalog error codes: ${o.catalog_error_code_count}`,`- Executable error codes: ${o.executable_error_code_count}`,`- Executable-code ratchet floor: ${b}`,`- Required executable canonical codes: ${f.map(r=>`\`${r}\``).join(", ")}`,`- Uncovered error codes: ${o.uncovered_error_code_count}`,`- Coverage fraction: ${o.coverage_fraction.toFixed(6)}`,`- Closed-domain probes: ${o.closed_domain_probe_count}`,`- Grammar probes: ${o.grammar_probe_count}`,"","| Error code | Canonical code | Disposition | Evidence kinds | Probe count |","| --- | --- | --- | --- | --- |",...n,""].join(`
2
+ `)}export{g as PM_REFUSAL_CLOSURE_EXECUTABLE_CANONICAL_CODE_BASELINE,f as PM_REFUSAL_CLOSURE_EXECUTABLE_CANONICAL_CODE_BASELINE_V2,E as PM_REFUSAL_CLOSURE_EXECUTABLE_CODE_BASELINE,b as PM_REFUSAL_CLOSURE_EXECUTABLE_CODE_BASELINE_V2,v as buildPmRefusalClosureCensus,x as renderPmRefusalClosureCensusMarkdown,k as verifyPmRefusalClosureIdentityRatchet,C as verifyPmRefusalClosureRatchet};
3
3
  //# sourceMappingURL=refusal-closure-census.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="39b4e1fe-a34a-5ffc-9447-eaf8c46863c7")}catch{}})();import{PLAN_SUBCOMMANDS}from"../lifecycle/plan.js";import{PROFILE_SUBCOMMANDS}from"../profile.js";import{SCHEMA_SUBCOMMANDS}from"../schema.js";import{GRAPH_SUBCOMMAND_VALUES,MERGE_SUBCOMMAND_VALUES}from"../cli-contracts/enum-contracts.js";import{PM_COMMAND_DESTINATION_CONTRACTS,PM_COMMAND_POSITIONAL_CONTRACTS,PM_POSITIONAL_ACTION_CONTRACTS}from"../cli-contracts/grammar-contracts.js";import{resolveSubcommandFlagContractsForCommand}from"../cli-contracts/flag-contracts.js";import{resolvePmCommandOperation}from"../cli-contracts/command-aliases.js";const REJECTED_ACTION="not-a-declared-action";function positionalPlaceholder(command,slot){if(command.startsWith("assurance ")&&slot.name==="kind")return"measurement";switch(slot.value_kind){case"integer":return"1";case"item_id":return"pm-domain";case"action":throw new Error(`Cannot synthesize a preceding action value for positional slot ${slot.name}.`);default:return"example"}}function probeSlug(value){return value.replaceAll(/[^a-z0-9]+/gu,"-").replaceAll(/^-|-$/gu,"")}function listPmRequiredArgumentRefusalContracts(contracts=PM_COMMAND_POSITIONAL_CONTRACTS.filter(contract=>PM_COMMAND_DESTINATION_CONTRACTS.some(destination=>destination.command===contract.command&&destination.disposition!=="package_owned"))){const rootProbeSlugs=new Set(contracts.filter(({command})=>!command.includes(" ")).map(({command})=>probeSlug(command)));return contracts.flatMap(contract=>contract.slots.flatMap((slot,index)=>{if(!slot.required)return[];const commandArguments=contract.command.split(" "),commandSlug=probeSlug(contract.command),commandProbeId=commandArguments.length>1&&rootProbeSlugs.has(commandSlug)?commandArguments.map(probeSlug).join("--"):commandSlug,requiredFlagArguments=resolveSubcommandFlagContractsForCommand(contract.command).flatMap(flagContract=>flagContract.required?[flagContract.flag,...flagContract.value_name?["example"]:[]]:[]),isVirtualAction=PM_POSITIONAL_ACTION_CONTRACTS.some(actionContract=>actionContract.command===contract.command);return[{probe_id:`required-argument-${commandProbeId}-${probeSlug(slot.name)}`,command:contract.command,refusal_args:[...commandArguments,...contract.slots.slice(0,index).map(priorSlot=>positionalPlaceholder(contract.command,priorSlot)),...requiredFlagArguments],recovery_args:[...commandArguments,"--help"],error_code:isVirtualAction&&!contract.command.startsWith("assurance ")?"invalid_argument_value":/^extension (?:activate|adopt|deactivate|uninstall)$/u.test(contract.command)?"missing_lifecycle_target":"missing_required_argument",missing_argument:slot.name,missing_argument_index:index}]})).sort((left,right)=>left.probe_id.localeCompare(right.probe_id))}function positionalActionValues(command){switch(resolvePmCommandOperation(command)){case"assurance":case"workspace snapshot":return PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent})=>parent===command).map(({action})=>action);case"graph":return GRAPH_SUBCOMMAND_VALUES;case"merge":return MERGE_SUBCOMMAND_VALUES;case"plan":return PLAN_SUBCOMMANDS;case"profile":return PROFILE_SUBCOMMANDS;case"schema":return SCHEMA_SUBCOMMANDS;default:throw new Error(`Required positional action family ${command} has no authoritative value domain.`)}}function listPmSubcommandRefusalContracts(contracts=PM_COMMAND_POSITIONAL_CONTRACTS){return contracts.filter(({slots})=>slots[0]?.required===!0&&slots[0].value_kind==="action").map(({command})=>{const commandArguments=command.split(" ");return{probe_id:`unknown-subcommand-${probeSlug(command)}`,command,refusal_args:[...commandArguments,REJECTED_ACTION],recovery_args:[...commandArguments,"--help"],error_code:"unknown_subcommand",rejected_value:REJECTED_ACTION,allowed_values:[...positionalActionValues(command)].sort()}}).sort((left,right)=>left.probe_id.localeCompare(right.probe_id))}function sameValues(left,right){const sortedRight=[...right].sort();return left.length===right.length&&[...left].sort().every((value,index)=>value===sortedRight[index])}function scoreGrammarRefusalObservation(contract,observation){if(!observation)return[{code:"refusal_probe_missing",probe_id:contract.probe_id,detail:`${contract.probe_id} has no runtime observation.`}];const findings=[];return observation.error_code!==contract.error_code&&findings.push({code:"refusal_error_code_mismatch",probe_id:contract.probe_id,detail:`${contract.probe_id} emitted ${observation.error_code||"<none>"}; expected ${contract.error_code}.`}),observation.exit_code!==2&&findings.push({code:"refusal_exit_code_mismatch",probe_id:contract.probe_id,detail:`${contract.probe_id} exited ${observation.exit_code}; expected usage exit 2.`}),"allowed_values"in contract&&!sameValues(observation.allowed_values,contract.allowed_values)&&findings.push({code:"refusal_allowed_values_mismatch",probe_id:contract.probe_id,detail:`${contract.probe_id} did not expose its complete action domain.`}),observation.recovery_succeeded||findings.push({code:"refusal_recovery_failed",probe_id:contract.probe_id,detail:`${contract.probe_id} help recovery did not succeed.`}),observation.refusal_mutated_state&&findings.push({code:"refusal_mutated_state",probe_id:contract.probe_id,detail:`${contract.probe_id} changed tracker state while refusing input${observation.mutated_paths?.length?`: ${observation.mutated_paths.join(", ")}`:"."}`}),findings}function scorePmGrammarRefusalClosure(contracts,observations){const contractsById=new Map(contracts.map(contract=>[contract.probe_id,contract])),observationsById=new Map(observations.map(observation=>[observation.probe_id,observation])),findings=[...contracts.flatMap(contract=>scoreGrammarRefusalObservation(contract,observationsById.get(contract.probe_id))),...observations.filter(observation=>!contractsById.has(observation.probe_id)).map(observation=>({code:"unexpected_refusal_probe",probe_id:observation.probe_id,detail:`${observation.probe_id} has no declared grammar refusal contract.`}))];findings.sort((left,right)=>left.probe_id.localeCompare(right.probe_id)||left.code.localeCompare(right.code));const failedProbeIds=new Set(findings.map(({probe_id:probeId})=>probeId));return{ok:findings.length===0,probe_count:contracts.length,closed_probe_count:contracts.filter(({probe_id:probeId})=>!failedProbeIds.has(probeId)).length,findings}}export{listPmRequiredArgumentRefusalContracts,listPmSubcommandRefusalContracts,scorePmGrammarRefusalClosure};
1
+ import{PLAN_SUBCOMMANDS as f}from"../lifecycle/plan.js";import{PROFILE_SUBCOMMANDS as g}from"../profile.js";import{SCHEMA_SUBCOMMANDS as h}from"../schema.js";import{GRAPH_SUBCOMMAND_VALUES as b,MERGE_SUBCOMMAND_VALUES as A}from"../cli-contracts/enum-contracts.js";import{PM_COMMAND_DESTINATION_CONTRACTS as C,PM_COMMAND_POSITIONAL_CONTRACTS as u,PM_POSITIONAL_ACTION_CONTRACTS as l}from"../cli-contracts/grammar-contracts.js";import{resolveSubcommandFlagContractsForCommand as M}from"../cli-contracts/flag-contracts.js";import{resolvePmCommandOperation as S}from"../cli-contracts/command-aliases.js";const _="not-a-declared-action";function w(r,e){if(r.startsWith("assurance ")&&e.name==="kind")return"measurement";switch(e.value_kind){case"integer":return"1";case"item_id":return"pm-domain";case"action":throw new Error(`Cannot synthesize a preceding action value for positional slot ${e.name}.`);default:return"example"}}function m(r){return r.replaceAll(/[^a-z0-9]+/gu,"-").replaceAll(/^-|-$/gu,"")}function y(r=u.filter(e=>C.some(o=>o.command===e.command&&o.disposition!=="package_owned"))){const e=new Set(r.filter(({command:o})=>!o.includes(" ")).map(({command:o})=>m(o)));return r.flatMap(o=>o.slots.flatMap((i,d)=>{if(!i.required)return[];const n=o.command.split(" "),a=m(o.command),t=n.length>1&&e.has(a)?n.map(m).join("--"):a,p=M(o.command).flatMap(s=>s.required?[s.flag,...s.value_name?["example"]:[]]:[]),c=l.some(s=>s.command===o.command);return[{probe_id:`required-argument-${t}-${m(i.name)}`,command:o.command,refusal_args:[...n,...o.slots.slice(0,d).map(s=>w(o.command,s)),...p],recovery_args:[...n,"--help"],error_code:c&&!o.command.startsWith("assurance ")?"invalid_argument_value":/^extension (?:activate|adopt|deactivate|uninstall)$/u.test(o.command)?"missing_lifecycle_target":"missing_required_argument",missing_argument:i.name,missing_argument_index:d}]})).sort((o,i)=>o.probe_id.localeCompare(i.probe_id))}function O(r){switch(S(r)){case"assurance":case"workspace snapshot":return l.filter(({parent:e})=>e===r).map(({action:e})=>e);case"graph":return b;case"merge":return A;case"plan":return f;case"profile":return g;case"schema":return h;default:throw new Error(`Required positional action family ${r} has no authoritative value domain.`)}}function k(r=u){return r.filter(({slots:e})=>e[0]?.required===!0&&e[0].value_kind==="action").map(({command:e})=>{const o=e.split(" ");return{probe_id:`unknown-subcommand-${m(e)}`,command:e,refusal_args:[...o,_],recovery_args:[...o,"--help"],error_code:"unknown_subcommand",rejected_value:_,allowed_values:[...O(e)].sort()}}).sort((e,o)=>e.probe_id.localeCompare(o.probe_id))}function $(r,e){const o=[...e].sort();return r.length===e.length&&[...r].sort().every((i,d)=>i===o[d])}function N(r,e){if(!e)return[{code:"refusal_probe_missing",probe_id:r.probe_id,detail:`${r.probe_id} has no runtime observation.`}];const o=[];return e.error_code!==r.error_code&&o.push({code:"refusal_error_code_mismatch",probe_id:r.probe_id,detail:`${r.probe_id} emitted ${e.error_code||"<none>"}; expected ${r.error_code}.`}),e.exit_code!==2&&o.push({code:"refusal_exit_code_mismatch",probe_id:r.probe_id,detail:`${r.probe_id} exited ${e.exit_code}; expected usage exit 2.`}),"allowed_values"in r&&!$(e.allowed_values,r.allowed_values)&&o.push({code:"refusal_allowed_values_mismatch",probe_id:r.probe_id,detail:`${r.probe_id} did not expose its complete action domain.`}),e.recovery_succeeded||o.push({code:"refusal_recovery_failed",probe_id:r.probe_id,detail:`${r.probe_id} help recovery did not succeed.`}),e.refusal_mutated_state&&o.push({code:"refusal_mutated_state",probe_id:r.probe_id,detail:`${r.probe_id} changed tracker state while refusing input${e.mutated_paths?.length?`: ${e.mutated_paths.join(", ")}`:"."}`}),o}function D(r,e){const o=new Map(r.map(a=>[a.probe_id,a])),i=new Map(e.map(a=>[a.probe_id,a])),d=[...r.flatMap(a=>N(a,i.get(a.probe_id))),...e.filter(a=>!o.has(a.probe_id)).map(a=>({code:"unexpected_refusal_probe",probe_id:a.probe_id,detail:`${a.probe_id} has no declared grammar refusal contract.`}))];d.sort((a,t)=>a.probe_id.localeCompare(t.probe_id)||a.code.localeCompare(t.code));const n=new Set(d.map(({probe_id:a})=>a));return{ok:d.length===0,probe_count:r.length,closed_probe_count:r.filter(({probe_id:a})=>!n.has(a)).length,findings:d}}export{y as listPmRequiredArgumentRefusalContracts,k as listPmSubcommandRefusalContracts,D as scorePmGrammarRefusalClosure};
2
2
  //# sourceMappingURL=refusal-corpus-contracts.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e23f9ca6-9fa6-566b-9bfb-7cbe6d449a59")}catch{}})();import{levenshteinDistanceWithinLimit}from"../../core/shared/levenshtein.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";const UNKNOWN_SUBCOMMAND_COMPATIBILITY_CODES=[{code:"unknown_lifecycle_action"}];function nearestSubcommand(token,allowed){const normalized=token.trim().toLowerCase();if(normalized.length===0)return;const maxDistance=Math.floor(normalized.length/3);return allowed.map(candidate=>({candidate,distance:levenshteinDistanceWithinLimit(normalized,candidate.toLowerCase(),maxDistance)??Number.POSITIVE_INFINITY})).filter(({distance})=>Number.isFinite(distance)).sort((left,right)=>left.distance!==right.distance?left.distance-right.distance:left.candidate.localeCompare(right.candidate))[0]?.candidate}function renderCommand(tokens){return["pm",...tokens].map(token=>/^[A-Za-z0-9_./:@=-]+$/u.test(token)?token:JSON.stringify(token)).join(" ")}function createUnknownSubcommandError(options){const commandPath=options.command_path.trim().replaceAll(/\s+/gu," "),normalizedToken=options.token.trim(),token=normalizedToken.length===0?"<empty>":normalizedToken,allowed=[...new Set(options.allowed.map(value=>value.trim()))].filter(Boolean).sort((left,right)=>left.localeCompare(right));if(commandPath.length===0||token.length===0||allowed.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");const commandTokens=commandPath.split(" "),trailingArgs=options.trailing_args??[],displayName=options.display_name??`pm ${commandPath}`,tokenKind=options.token_kind??"subcommand",nearest=options.retry_command?void 0:nearestSubcommand(token,allowed),attemptedCommand=renderCommand([...commandTokens,token,...trailingArgs]),suggestedRetry=options.retry_command??(nearest?renderCommand([...commandTokens,nearest,...trailingArgs]):void 0);return new PmCliError(`Unknown ${displayName} ${tokenKind} "${token}". Allowed: ${allowed.join(", ")}${options.message_suffix??""}`,options.exit_code??EXIT_CODE.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:token,examples:[...suggestedRetry?[suggestedRetry]:[],...options.examples??[],`pm ${commandPath} --help`],nextSteps:suggestedRetry?[`Retry with the suggested command: ${suggestedRetry}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:attemptedCommand,allowed_values:allowed,suggested_retry:suggestedRetry,fallback_candidates:options.fallback_candidates}})}const _testOnly={nearestSubcommand,renderCommand};export{UNKNOWN_SUBCOMMAND_COMPATIBILITY_CODES,_testOnly,createUnknownSubcommandError};
1
+ import{levenshteinDistanceWithinLimit as p}from"../../core/shared/levenshtein.js";import{EXIT_CODE as g}from"../../core/shared/constants.js";import{PmCliError as h}from"../../core/shared/errors.js";const N=[{code:"unknown_lifecycle_action"}];function i(e,t){const o=e.trim().toLowerCase();if(o.length===0)return;const a=Math.floor(o.length/3);return t.map(n=>({candidate:n,distance:p(o,n.toLowerCase(),a)??Number.POSITIVE_INFINITY})).filter(({distance:n})=>Number.isFinite(n)).sort((n,r)=>n.distance!==r.distance?n.distance-r.distance:n.candidate.localeCompare(r.candidate))[0]?.candidate}function d(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function b(e){const t=e.command_path.trim().replaceAll(/\s+/gu," "),o=e.token.trim(),a=o.length===0?"<empty>":o,n=[...new Set(e.allowed.map(c=>c.trim()))].filter(Boolean).sort((c,w)=>c.localeCompare(w));if(t.length===0||a.length===0||n.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");const r=t.split(" "),s=e.trailing_args??[],u=e.display_name??`pm ${t}`,_=e.token_kind??"subcommand",l=e.retry_command?void 0:i(a,n),f=d([...r,a,...s]),m=e.retry_command??(l?d([...r,l,...s]):void 0);return new h(`Unknown ${u} ${_} "${a}". Allowed: ${n.join(", ")}${e.message_suffix??""}`,e.exit_code??g.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:a,examples:[...m?[m]:[],...e.examples??[],`pm ${t} --help`],nextSteps:m?[`Retry with the suggested command: ${m}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:f,allowed_values:n,suggested_retry:m,fallback_candidates:e.fallback_candidates}})}const x={nearestSubcommand:i,renderCommand:d};export{N as UNKNOWN_SUBCOMMAND_COMPATIBILITY_CODES,x as _testOnly,b as createUnknownSubcommandError};
2
2
  //# sourceMappingURL=subcommand-recovery.js.map
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0c0bb7ab-6157-5861-ad7e-a63ae62220f4")}catch{}})();import{PM_CORE_COMMAND_NAMES}from"./cli-contracts/enum-contracts.js";import{PM_COMMAND_ALIAS_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";const CORE_COMMANDS=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),STANDARD_COMMANDS=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),COMMANDS_BY_FAMILY=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),EXTENSION_COMMANDS=new Set(["extension","install","package","packages","upgrade"]);function resolvePmCommandCapabilityFamily(command){const normalized=resolvePmCommandOperation(command.trim().toLowerCase());if(normalized==="ops")return"quality";for(const[family,commands]of Object.entries(COMMANDS_BY_FAMILY))if(commands.has(normalized))return family;return EXTENSION_COMMANDS.has(normalized)?"extensions":"internal"}const PM_COMMAND_CAPABILITY_CONTRACTS=Object.freeze([...PM_CORE_COMMAND_NAMES.flatMap(command=>command==="item"?["item","item-reopen"]:[command,...PM_NAMESPACED_COMMAND_ALIASES.filter(alias=>alias.alias===command).map(alias=>alias.canonical)]).map(command=>({command,tier:CORE_COMMANDS.has(resolvePmCommandOperation(command))?"core":STANDARD_COMMANDS.has(resolvePmCommandOperation(command))?"standard":"full",family:resolvePmCommandCapabilityFamily(command)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),PM_COMMAND_VISIBILITY_CONTRACTS=PM_COMMAND_CAPABILITY_CONTRACTS,PM_CORE_HELP_BUDGET=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),PM_CORE_HELP_OPTION_FLAGS=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function measurePmCoreHelp(text){const lines=text===""?0:text.split(/\r?\n/).length,utf8Bytes=Buffer.byteLength(text,"utf8");return{lines,utf8_bytes:utf8Bytes,within_budget:lines<=PM_CORE_HELP_BUDGET.max_lines&&utf8Bytes<=PM_CORE_HELP_BUDGET.max_utf8_bytes}}const TIER_ORDER={core:0,standard:1,full:2,internal:3},COMMAND_TIER_BY_NAME=new Map(PM_COMMAND_VISIBILITY_CONTRACTS.map(({command,tier})=>[command,tier]));function resolvePmCommandVisibilityTier(command,extensionTier="standard"){return COMMAND_TIER_BY_NAME.get(command.trim().toLowerCase())??COMMAND_TIER_BY_NAME.get(resolvePmCommandOperation(command.trim().toLowerCase()))??extensionTier}function listPmCommandsForTier(tier){return listPmCommandsForTierFromContracts(tier,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForTierFromContracts(tier,contracts){const maximum=TIER_ORDER[tier];return contracts.filter(entry=>entry.tier!=="internal"&&TIER_ORDER[entry.tier]<=maximum).map(entry=>entry.command)}function listPmCommandsForFamily(family){return listPmCommandsForFamilyFromContracts(family,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmCommandsForFamilyFromContracts(family,contracts){return contracts.filter(entry=>entry.family===family).map(entry=>entry.command)}const CAPABILITY_FAMILY_ORDER=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],CAPABILITY_ROUTING_EXCLUDED_ALIASES=new Set([...PM_COMMAND_ALIAS_CONTRACTS.filter(alias=>alias.hidden).map(alias=>alias.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function listPmCommandCapabilityGroups(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){return CAPABILITY_FAMILY_ORDER.map(family=>({family,commands:listPmCommandsForFamilyFromContracts(family,contracts).filter(command=>contracts.find(entry=>entry.command===command)?.tier!=="internal"&&!CAPABILITY_ROUTING_EXCLUDED_ALIASES.has(command))})).filter(({commands})=>commands.length>0)}const PM_MCP_TOOL_COMMAND_CONTRACTS=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function listPmMcpToolsForProfile(availableTools,profile){return listPmMcpToolsForProfileFromContracts(availableTools,profile,PM_COMMAND_CAPABILITY_CONTRACTS)}function listPmMcpToolsForProfileFromContracts(availableTools,profile,contracts){if(profile==="full")return[...availableTools];const visibleCommands=new Set(listPmCommandsForTierFromContracts(profile,contracts));return availableTools.filter(tool=>{const command=PM_MCP_TOOL_COMMAND_CONTRACTS[tool];return command!==void 0&&visibleCommands.has(command)})}const PM_MCP_RESOURCE_CONTRACTS=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),PM_MCP_PROMPT_CONTRACTS=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function renderPmCommandVisibilityMarkdown(){return renderPmCommandVisibilityMarkdownFromContracts(PM_COMMAND_CAPABILITY_CONTRACTS)}function renderPmCommandVisibilityMarkdownFromContracts(contracts){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...contracts.map(({command,tier,family})=>`| \`${command}\` | ${tier} | ${family} |`),""].join(`
2
- `)}function renderPmCapabilityRoutingMarkdown(contracts=PM_COMMAND_CAPABILITY_CONTRACTS){return["# Generated agent capability routing","","Tracker: `pm-kxci8x`.","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Capability family | Commands |","| --- | --- |",...listPmCommandCapabilityGroups(contracts).map(({family,commands})=>`| ${family} | ${commands.map(command=>`\`${command}\``).join(", ")} |`),""].join(`
3
- `)}export{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CORE_HELP_BUDGET,PM_CORE_HELP_OPTION_FLAGS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandCapabilityGroups,listPmCommandsForFamily,listPmCommandsForFamilyFromContracts,listPmCommandsForTier,listPmCommandsForTierFromContracts,listPmMcpToolsForProfile,listPmMcpToolsForProfileFromContracts,measurePmCoreHelp,renderPmCapabilityRoutingMarkdown,renderPmCommandVisibilityMarkdown,renderPmCommandVisibilityMarkdownFromContracts,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier};
1
+ import{PM_CORE_COMMAND_NAMES as u}from"./cli-contracts/enum-contracts.js";import{PM_COMMAND_ALIAS_CONTRACTS as f,PM_NAMESPACED_COMMAND_ALIASES as _,resolvePmCommandOperation as r}from"./cli-contracts/command-aliases.js";const C=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),h=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),g=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),y=new Set(["extension","install","package","packages","upgrade"]);function M(e){const t=r(e.trim().toLowerCase());if(t==="ops")return"quality";for(const[n,i]of Object.entries(g))if(i.has(t))return n;return y.has(t)?"extensions":"internal"}const a=Object.freeze([...u.flatMap(e=>e==="item"?["item","item-reopen"]:[e,..._.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:C.has(r(e))?"core":h.has(r(e))?"standard":"full",family:M(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),x=a,c=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),v=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function N(e){const t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=c.max_lines&&n<=c.max_utf8_bytes}}const l={core:0,standard:1,full:2,internal:3},m=new Map(x.map(({command:e,tier:t})=>[e,t]));function R(e,t="standard"){return m.get(e.trim().toLowerCase())??m.get(r(e.trim().toLowerCase()))??t}function E(e){return p(e,a)}function p(e,t){const n=l[e];return t.filter(i=>i.tier!=="internal"&&l[i.tier]<=n).map(i=>i.command)}function I(e){return d(e,a)}function d(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}const A=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],w=new Set([...f.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function O(e=a){return A.map(t=>({family:t,commands:d(t,e).filter(n=>e.find(i=>i.command===n)?.tier!=="internal"&&!w.has(n))})).filter(({commands:t})=>t.length>0)}const T=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function D(e,t){return P(e,t,a)}function P(e,t,n){if(t==="full")return[...e];const i=new Set(p(t,n));return e.filter(o=>{const s=T[o];return s!==void 0&&i.has(s)})}const L=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),F=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function j(){return S(a)}function S(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:n,tier:i,family:o})=>`| \`${n}\` | ${i} | ${o} |`),""].join(`
2
+ `)}function B(e=a){return["# Generated agent capability routing","","Tracker: `pm-kxci8x`.","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Capability family | Commands |","| --- | --- |",...O(e).map(({family:n,commands:i})=>`| ${n} | ${i.map(o=>`\`${o}\``).join(", ")} |`),""].join(`
3
+ `)}export{a as PM_COMMAND_CAPABILITY_CONTRACTS,x as PM_COMMAND_VISIBILITY_CONTRACTS,c as PM_CORE_HELP_BUDGET,v as PM_CORE_HELP_OPTION_FLAGS,F as PM_MCP_PROMPT_CONTRACTS,L as PM_MCP_RESOURCE_CONTRACTS,T as PM_MCP_TOOL_COMMAND_CONTRACTS,O as listPmCommandCapabilityGroups,I as listPmCommandsForFamily,d as listPmCommandsForFamilyFromContracts,E as listPmCommandsForTier,p as listPmCommandsForTierFromContracts,D as listPmMcpToolsForProfile,P as listPmMcpToolsForProfileFromContracts,N as measurePmCoreHelp,B as renderPmCapabilityRoutingMarkdown,j as renderPmCommandVisibilityMarkdown,S as renderPmCommandVisibilityMarkdownFromContracts,M as resolvePmCommandCapabilityFamily,R as resolvePmCommandVisibilityTier};
4
4
  //# sourceMappingURL=agent-capability-contracts.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="38023567-8a5b-5e25-8d71-5112f74d1894")}catch{}})();import{agentSessionEnvironment,boundAgentEpisodeIdentity,runWithAgentSessionContext,resolveAgentSessionContextFromSignals}from"../core/shared/agent-session-context.js";export{agentSessionEnvironment,boundAgentEpisodeIdentity,resolveAgentSessionContextFromSignals,runWithAgentSessionContext};
1
+ import{agentSessionEnvironment as t,boundAgentEpisodeIdentity as o,runWithAgentSessionContext as s,resolveAgentSessionContextFromSignals as i}from"../core/shared/agent-session-context.js";export{t as agentSessionEnvironment,o as boundAgentEpisodeIdentity,i as resolveAgentSessionContextFromSignals,s as runWithAgentSessionContext};
2
2
  //# sourceMappingURL=agent-session-context.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="59163d45-c136-5ead-adf1-b08ebb9c27ae")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{readFile}from"node:fs/promises";import{isFileAbsentError}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{createStdinTokenResolver,parseCsvKv,shouldResolveMutationStdinTokens,transferMutationStdinTokenPolicy}from"../core/item/parse.js";import{renderPmCommand}from"../core/shared/command-line.js";import{resolvePmCommandScopeArgs}from"./command-line.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{parseLimit}from"../core/shared/numeric-parsers.js";import{nowIso}from"../core/shared/time.js";import{readCompactionMarker}from"../core/shared/text-normalization.js";import{resolveAuthor}from"../core/shared/author.js";import{locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{CANONICALLY_ORDERED_LOG_COLLECTIONS,compareLogValues}from"../core/item/item-format.js";function normalizeAnnotationTransportOptions(options){const normalized={...options,...options.full===!0?{fullHistory:!0}:{}};return delete normalized.full,transferMutationStdinTokenPolicy(options,normalized)}function isAnnotationRecord(entry){return Object.prototype.toString.call(entry)==="[object Object]"}function editedAnnotationEntry(existing,text,author,createEntry){const now=nowIso();if(!isAnnotationRecord(existing))return{...createEntry({created_at:now,author,text}),text,edited_at:now};const usable=value=>typeof value=="string"&&value!=="";return{...existing,...usable(existing.created_at)?{}:{created_at:now},...usable(existing.author)?{}:{author},text,edited_at:now}}function assertAnnotationEntryMutable(entry,operation){if(typeof entry=="object"&&entry!==null&&"format"in entry&&entry.format==="json")throw new PmCliError(`Structured context events are append-only and cannot be ${operation}.`,EXIT_CODE.USAGE,{code:"structured_event_immutable"})}function limitAnnotationEntries(values,limit){return limit===void 0?values:limit===0?[]:values.slice(Math.max(0,values.length-limit))}function readAnnotationEntries(source,collectionKey){const value=source[collectionKey];return Array.isArray(value)?value:[]}function parseAnnotationTextInput(raw,options={}){const trimmed=raw.trim();if(!trimmed)return"";const textPrefixMatch=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(trimmed);if(options.stripPlainTextPrefix===!0&&textPrefixMatch&&!trimmed.startsWith("```"))return trimmed.slice(textPrefixMatch[0].length).trim()||trimmed;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(trimmed)||trimmed.startsWith("```")))return trimmed;try{const kv=parseCsvKv(trimmed,"--add");return Object.keys(kv).map(key=>key.trim().toLowerCase()).some(key=>key!=="text")?trimmed:kv.text?.trim()||trimmed}catch{return trimmed}}function isErrnoError(error){return typeof error=="object"&&error!==null&&"code"in error}function assertAnnotationStdinTransportAvailable(options,optionName){if(!shouldResolveMutationStdinTokens(options))throw new PmCliError(`${optionName} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,EXIT_CODE.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function resolveAnnotationTextSource(options,noun){if(+(options.add!==void 0)+ +(options.stdin===!0)+ +(typeof options.file=="string")>1)throw new PmCliError(`Specify ${noun} text using only one input source: --add, --stdin, or --file`,EXIT_CODE.USAGE);const stdinResolver=createStdinTokenResolver(),resolveStdinTokens=shouldResolveMutationStdinTokens(options);if(options.add!==void 0)return{value:await stdinResolver.resolveValue(options.add,"--add",resolveStdinTokens)??"",rawValue:options.add,emptyFlag:"--add"};if(options.stdin===!0)return assertAnnotationStdinTransportAvailable(options,"--stdin"),{value:await stdinResolver.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof options.file!="string")return;const filePath=options.file.trim();if(!filePath)throw new PmCliError("--file path cannot be empty",EXIT_CODE.USAGE);if(filePath==="-")return assertAnnotationStdinTransportAvailable(options,"--file -"),{value:await stdinResolver.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await readFile(filePath,"utf8"),emptyFlag:"--file"}}catch(error){if(isErrnoError(error)&&isFileAbsentError(error))throw new PmCliError(`--file path not found: ${filePath}. Use --file - to read stdin.`,EXIT_CODE.USAGE);const detail=error instanceof Error?error.message:String(error);throw new PmCliError(`Failed to read --file path "${filePath}": ${detail}. Use --file - to read stdin.`,EXIT_CODE.USAGE)}}async function resolveAnnotationInput(options,noun){if(options.edit!==void 0&&options.delete!==void 0)throw new PmCliError("Specify only one of --edit or --delete",EXIT_CODE.USAGE);if(options.delete!==void 0){if(options.add!==void 0||options.stdin===!0||typeof options.file=="string")throw new PmCliError("--delete cannot be combined with replacement text",EXIT_CODE.USAGE);if(!Number.isInteger(options.delete)||options.delete<1)throw new PmCliError("--delete must be a positive integer",EXIT_CODE.USAGE);return{mode:"delete",index:options.delete}}if(options.edit!==void 0&&(!Number.isInteger(options.edit)||options.edit<1))throw new PmCliError("--edit must be a positive integer",EXIT_CODE.USAGE);const resolved=await resolveAnnotationTextSource(options,noun);if(options.edit!==void 0){if(!resolved)throw new PmCliError("--edit requires replacement text from --add, --stdin, or --file",EXIT_CODE.USAGE);return{mode:"edit",index:options.edit,...resolved}}return resolved?{mode:"add",...resolved}:{mode:"list"}}function wrapOwnershipConflict(error,guidance){throw error instanceof PmCliError&&error.exitCode===EXIT_CODE.CONFLICT&&error.message.includes("is assigned to")&&error.message.includes("Use --force to override")?new PmCliError(error.message,error.exitCode,{code:"ownership_conflict",required:guidance.required,examples:guidance.examples,nextSteps:guidance.nextSteps}):error}function annotationStdinHint(collectionKey){return collectionKey==="comments"?"--stdin":"--add -"}const ANNOTATION_FLAG_LIKE_VALUE_CODE="annotation_flag_like_value";function isFlagLikeAnnotationValue(raw){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(raw.trim())}function annotationSourceOptionForm(token){return token==="--file"?"--file <path>":token.startsWith("--file=")?token:token==="--stdin"?"--stdin":void 0}function createFlagLikeAnnotationValueRefusal(input){const trimmed=input.value.trim(),noun=input.collectionKey.replace(/s$/,""),sourceForm=annotationSourceOptionForm(trimmed),stdinHint=annotationStdinHint(input.collectionKey),retry=input.retryArgs===void 0?{}:{field:input.textFlag,recovery:{suggested_flags:[trimmed],suggested_retry:renderPmCommand(input.retryArgs),suggested_retry_args:[...input.retryArgs]}};if(sourceForm!==void 0){const sourceFlag=sourceForm.split(/[ =]/,1)[0],source=sourceFlag==="--file"?"that file":"stdin",operandNote=input.conflictingOperand===void 0?"":` "${input.conflictingOperand}" was read as positional text, which ${sourceFlag} cannot be combined with: drop it, or pass it as the text without ${sourceFlag}.`;return new PmCliError(`${input.textFlag} value "${trimmed}" looks like an option, not annotation text: ${input.textFlag} took ${sourceFlag} as its value. Drop ${input.textFlag} and pass ${sourceForm} on its own.${operandNote}`,EXIT_CODE.USAGE,{code:"annotation_flag_like_value",required:`Drop ${input.textFlag}: ${sourceForm} reads the ${noun} text from ${source} by itself. Use ${input.textFlag} text=${trimmed} only when the text really is "${trimmed}".`,examples:[`${input.commandPrefix} ${sourceForm}`,`${input.commandPrefix} ${input.textFlag} text=${trimmed}`],...retry})}return new PmCliError(`${input.textFlag} value "${trimmed}" looks like an option, not annotation text. Use ${stdinHint} to read stdin, or use text=${trimmed} for literal dash-leading text.`,EXIT_CODE.USAGE,{code:"annotation_flag_like_value",required:`Use ${stdinHint} for stdin input, pass plain text, or use text=${trimmed} when the text really starts with "-".`,examples:[`${input.commandPrefix} ${stdinHint}`,`${input.commandPrefix} ${input.textFlag} text=${trimmed}`],...retry})}function assertAnnotationAddValueIsNotFlagLike(raw,config){if(!((config.input.emptyFlag??"--add")!=="--add"||!isFlagLikeAnnotationValue(raw)))throw createFlagLikeAnnotationValueRefusal({collectionKey:config.collectionKey,textFlag:"--add",value:raw,commandPrefix:config.input.mode==="edit"?`pm ${config.collectionKey} <id> --edit <index>`:`pm ${config.collectionKey} <id>`})}function assertAnnotationEditTextIsNotCompacted(id,text,config,global2,pmRoot){if(config.input.mode!=="edit")return;const omitted=readCompactionMarker(text);if(omitted===void 0)return;const noun=config.collectionKey.replace(/s$/,""),index=config.input.index,scope=resolvePmCommandScopeArgs(global2)[0]==="--pm-path"?["--pm-path",pmRoot]:[];throw new PmCliError(`Replacement text for ${noun} ${index} on ${id} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${omitted} characters. Nothing was written.`,EXIT_CODE.USAGE,{code:"annotation_text_compacted",item_id:id,details:{collection:config.collectionKey,entry_index:index,omitted_characters:omitted},required:`Read the whole ${noun} with --output-budget unbounded, apply the change to the full text, and retry the edit without the trailing marker.`,why:"A budgeted read shortens long entries to a prefix plus a marker naming how many characters it left out; editing from that text would replace the stored entry with the shortened prefix.",examples:[renderPmCommand([...scope,config.collectionKey,id,"--output-budget","unbounded","--json"]),`${renderPmCommand([...scope,config.collectionKey,id,"--edit",String(index),"--file"])} <full-text-file>`]})}function assertAnnotationMessageHasTextSource(config,options){if(options.ifAbsent===!0&&!["add","stdin","file"].includes(config.input.mode))throw new PmCliError(`--if-absent requires a ${config.collectionKey.replace(/s$/,"")} append`,EXIT_CODE.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(assertAnnotationExpectationTargetsEntry(config,options),config.input.mode!=="list"||options.message===void 0)return;const noun=config.collectionKey.replace(/s$/,"");throw new PmCliError(`--message labels a ${noun} mutation but does not provide ${noun} text. Pass text positionally or with --add, --stdin, or --file.`,EXIT_CODE.USAGE,{code:"annotation_message_without_text",required:`Provide ${noun} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${config.collectionKey} <id> --add "text" --message "why"`,`pm ${config.collectionKey} <id> ${annotationStdinHint(config.collectionKey)}`]})}function assertAnnotationExpectationTargetsEntry(config,options){if(options.expectAt!==void 0){if(config.input.mode!=="edit"&&config.input.mode!=="delete")throw new PmCliError(`--expect-at guards an --edit or --delete of one ${config.collectionKey.replace(/s$/,"")}`,EXIT_CODE.USAGE,{code:"annotation_expectation_without_target",required:"Combine --expect-at with --edit <index> or --delete <index>; omit it for list and append operations.",examples:[`pm ${config.collectionKey} <id> --edit <index> --expect-at <created_at> --add "<text>"`,`pm ${config.collectionKey} <id> --delete <index> --expect-at <created_at>`]});if(typeof options.expectAt!="string"||options.expectAt.trim().length===0)throw new PmCliError("--expect-at must be the non-empty created_at timestamp of the entry you read",EXIT_CODE.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function assertExpectedAnnotationEntry(id,entries,arrayIndex,config,expectAt){if(expectAt===void 0)return;const stored=entries[arrayIndex]?.created_at,actual=typeof stored=="string"?stored:null;if(actual===expectAt)return;const matchingIndexes=entries.flatMap((entry,position)=>entry?.created_at===expectAt?[position+1]:[]),noun=config.collectionKey.replace(/s$/,""),action=config.input.mode==="delete"?"--delete":"--edit",entryIndex=arrayIndex+1,retarget=matchingIndexes.length===1?` The ${noun} created at ${expectAt} is at index ${matchingIndexes[0]}.`:matchingIndexes.length>1?` ${matchingIndexes.length} ${config.collectionKey} were created at ${expectAt}: indexes ${matchingIndexes.join(", ")}.`:` No ${noun} on ${id} was created at ${expectAt}.`;throw new PmCliError(`${noun.charAt(0).toUpperCase()}${noun.slice(1)} ${entryIndex} on ${id} was created at ${actual||"an unrecorded time (malformed entry)"}, not ${expectAt}; refusing ${action} of an entry the caller did not read. Nothing was written.${retarget}`,EXIT_CODE.CONFLICT,{code:"annotation_entry_mismatch",item_id:id,details:{collection:config.collectionKey,entry_index:entryIndex,expected_created_at:expectAt,actual_created_at:actual,matching_indexes:matchingIndexes},required:`Address the ${noun} by the index its listing row reports and keep --expect-at set to that row's created_at. When several indexes share the timestamp, inspect those rows before retrying, because the guard compares timestamps, not entry identities.`,why:"A listing page's position or count is not an entry address; only the row's index is, and the expectation checks that the entry at that index still carries the created_at that was read.",examples:[`pm ${config.collectionKey} ${id} --limit 5`,`pm ${config.collectionKey} ${id} ${action} ${matchingIndexes.length===1?matchingIndexes[0]:"<index>"} --expect-at ${expectAt}${action==="--edit"?' --add "<text>"':""}`]})}function appendAnnotationEntry(document,collectionKey,author,text,ifAbsent,createEntry){const entries=readAnnotationEntries(document.metadata,collectionKey),existingIndex=ifAbsent?entries.findIndex(entry=>isAnnotationRecord(entry)&&entry.author===author&&entry.text===text):-1;return existingIndex>=0?{changedFields:[],written:entries,position:existingIndex}:(entries.push(createEntry({created_at:nowIso(),author,text})),document.metadata[collectionKey]=entries,{changedFields:[collectionKey],written:entries,position:entries.length-1})}function canonicalAnnotationAddress(collectionKey,written,position){return CANONICALLY_ORDERED_LOG_COLLECTIONS.has(collectionKey)?written.map((_entry,index)=>index).sort((left,right)=>compareLogValues(written[left],written[right])||left-right).indexOf(position)+1:position+1}async function runAnnotationCommand(id,options,global2,config){assertAnnotationMessageHasTextSource(config,options);const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),limit=parseLimit(options.limit);if(config.input.mode==="list"){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const loaded=await readLocatedItem(located,{schema:settings.schema}),allEntries2=readAnnotationEntries(loaded.document.metadata,config.collectionKey);return renderAnnotationResult(located.id,config.collectionKey,allEntries2,limit,options.includeMeta===!0)}const author=resolveAuthor(options.author,settings.author_default);if(config.input.mode==="delete"){const op=config.deleteOp??config.op;let result2;try{result2=await mutateItem({pmRoot,settings,id,op,author,message:options.message,force:options.force,bypassAssigneeConflict:config.bypassOwnershipConflict,mutate(document){const entries=readAnnotationEntries(document.metadata,config.collectionKey),arrayIndex=resolveAnnotationIndex(config.input.index,entries.length,config.collectionKey);return assertExpectedAnnotationEntry(id,entries,arrayIndex,config,options.expectAt),assertAnnotationEntryMutable(entries[arrayIndex],"deleted"),entries.splice(arrayIndex,1),document.metadata[config.collectionKey]=entries,{changedFields:[config.collectionKey]}}})}catch(error){wrapOwnershipConflict(error,config.conflictGuidance)}const allEntries2=readAnnotationEntries(result2.item,config.collectionKey);return renderAnnotationResult(result2.item.id,config.collectionKey,allEntries2,limit,options.includeMeta===!0,{action:"delete",entryIndex:config.input.index},options.fullHistory===!0)}const rawText=config.input.rawValue??config.input.value??"";assertAnnotationAddValueIsNotFlagLike(rawText,config);const text=config.parseText(config.input.value??"");if(!text.trim())throw new PmCliError(`${config.input.emptyFlag??"--add"} text cannot be empty`,EXIT_CODE.USAGE);if(assertAnnotationEditTextIsNotCompacted(id,text,config,global2,pmRoot),config.input.mode==="edit"){const op=config.editOp??config.op;let result2,editedAddress=0;try{result2=await mutateItem({pmRoot,settings,id,op,author,message:options.message,force:options.force,bypassAssigneeConflict:config.bypassOwnershipConflict,mutate(document){const entries=readAnnotationEntries(document.metadata,config.collectionKey),arrayIndex=resolveAnnotationIndex(config.input.index,entries.length,config.collectionKey);assertExpectedAnnotationEntry(id,entries,arrayIndex,config,options.expectAt);const existing=entries[arrayIndex];return assertAnnotationEntryMutable(existing,"edited"),entries[arrayIndex]=editedAnnotationEntry(existing,text,author,config.createEntry),editedAddress=canonicalAnnotationAddress(config.collectionKey,entries,arrayIndex),document.metadata[config.collectionKey]=entries,{changedFields:[config.collectionKey]}}})}catch(error){wrapOwnershipConflict(error,config.conflictGuidance)}const allEntries2=readAnnotationEntries(result2.item,config.collectionKey),editedIndex=editedAddress;return renderAnnotationResult(result2.item.id,config.collectionKey,allEntries2,limit,options.includeMeta===!0,{action:"edit",entryIndex:editedIndex,entry:allEntries2[editedIndex-1]},options.fullHistory===!0)}let result,entryIndex=0;try{result=await mutateItem({pmRoot,settings,id,op:config.op,author,message:options.message,force:options.force,bypassAssigneeConflict:config.bypassOwnershipConflict,skipNoop:options.ifAbsent===!0,mutate(document){const appended=appendAnnotationEntry(document,config.collectionKey,author,text,options.ifAbsent===!0,config.createEntry);return entryIndex=canonicalAnnotationAddress(config.collectionKey,appended.written,appended.position),{changedFields:appended.changedFields}}})}catch(error){wrapOwnershipConflict(error,config.conflictGuidance)}const allEntries=readAnnotationEntries(result.item,config.collectionKey);return renderAnnotationResult(result.item.id,config.collectionKey,allEntries,limit,options.includeMeta===!0,{action:"add",entryIndex,entry:allEntries[entryIndex-1],changedCount:options.ifAbsent===!0?Math.min(result.changedFields.length,1):void 0},options.fullHistory===!0)}function resolveAnnotationIndex(oneBasedIndex,count,collectionKey){if(oneBasedIndex===void 0||!Number.isInteger(oneBasedIndex)||oneBasedIndex<1||oneBasedIndex>count){const singular=collectionKey.replace(/s$/,""),label=`${singular.charAt(0).toUpperCase()}${singular.slice(1)}`,noun=count===1?`1 ${singular}`:`${count} ${collectionKey}`;throw new PmCliError(`${label} index ${oneBasedIndex??"(missing)"} out of range (item has ${noun})`,EXIT_CODE.USAGE)}return oneBasedIndex-1}function renderAnnotationMutationReceipts(collectionKey,mutation,historyOmitted){return mutation===void 0?{}:{mutation_receipt:{action:mutation.action,entry_index:mutation.entryIndex,changed_count:mutation.changedCount??1,full_history_included:!historyOmitted},omission_receipt:{has_omissions:historyOmitted,omitted_field_group_count:historyOmitted?1:0,omitted_field_groups:historyOmitted?[{name:`${collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function indexAnnotationEntry(entry,index){if(Object.prototype.toString.call(entry)!=="[object Object]")return entry;const indexed={index,...entry};return indexed.index=index,indexed}function indexRetainedAnnotationEntries(allEntries,retained){const offset=allEntries.length-retained.length;return retained.map((entry,position)=>indexAnnotationEntry(entry,offset+position+1))}function renderAnnotationResult(id,collectionKey,allEntries,limit,includeMeta,mutation,fullHistory=!1){const entries=mutation===void 0||fullHistory?indexRetainedAnnotationEntries(allEntries,limitAnnotationEntries(allEntries,mutation!==void 0&&fullHistory?void 0:limit)):mutation.entry===void 0?[]:[indexAnnotationEntry(mutation.entry,mutation.entryIndex)],historyOmitted=mutation!==void 0&&entries.length<allEntries.length;return{id,[collectionKey]:entries,count:entries.length,...mutation?.changedCount===void 0?{}:{changed:mutation.changedCount===1},...[includeMeta,mutation!==void 0].includes(!0)?{total_count:allEntries.length,returned_count:entries.length,has_more:historyOmitted||entries.length<allEntries.length,...limit!==void 0?{limit}:{}}:{},...renderAnnotationMutationReceipts(collectionKey,mutation,historyOmitted)}}export{ANNOTATION_FLAG_LIKE_VALUE_CODE,assertAnnotationStdinTransportAvailable,createFlagLikeAnnotationValueRefusal,isErrnoError,isFlagLikeAnnotationValue,limitAnnotationEntries,normalizeAnnotationTransportOptions,parseAnnotationTextInput,readAnnotationEntries,resolveAnnotationIndex,resolveAnnotationInput,runAnnotationCommand,wrapOwnershipConflict};
1
+ import{assertInitializedTracker as M}from"./environment/tracker-preflight.js";import{readFile as q}from"node:fs/promises";import{isFileAbsentError as j}from"../core/fs/fs-utils.js";import{getActiveExtensionRegistrations as V}from"../core/extensions/index.js";import{resolveItemTypeRegistry as D}from"../core/item/type-registry.js";import{createStdinTokenResolver as H,parseCsvKv as z,shouldResolveMutationStdinTokens as U,transferMutationStdinTokenPolicy as W}from"../core/item/parse.js";import{renderPmCommand as v}from"../core/shared/command-line.js";import{resolvePmCommandScopeArgs as J}from"./command-line.js";import{EXIT_CODE as c}from"../core/shared/constants.js";import{PmCliError as l}from"../core/shared/errors.js";import{parseLimit as X}from"../core/shared/numeric-parsers.js";import{nowIso as O}from"../core/shared/time.js";import{readCompactionMarker as Y}from"../core/shared/text-normalization.js";import{resolveAuthor as Z}from"../core/shared/author.js";import{locateItem as Q,mutateItem as C,readLocatedItem as B}from"../core/store/item-store.js";import{resolvePmRoot as ee}from"../core/store/paths.js";import{readSettings as te}from"../core/store/settings.js";import{CANONICALLY_ORDERED_LOG_COLLECTIONS as ne,compareLogValues as re}from"../core/item/item-format.js";function Te(e){const t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,W(e,t)}function I(e){return Object.prototype.toString.call(e)==="[object Object]"}function ae(e,t,r,n){const o=O();if(!I(e))return{...n({created_at:o,author:r,text:t}),text:t,edited_at:o};const a=i=>typeof i=="string"&&i!=="";return{...e,...a(e.created_at)?{}:{created_at:o},...a(e.author)?{}:{author:r},text:t,edited_at:o}}function k(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new l(`Structured context events are append-only and cannot be ${t}.`,c.USAGE,{code:"structured_event_immutable"})}function oe(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function x(e,t){const r=e[t];return Array.isArray(r)?r:[]}function Pe(e,t={}){const r=e.trim();if(!r)return"";const n=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(r);if(t.stripPlainTextPrefix===!0&&n&&!r.startsWith("```"))return r.slice(n[0].length).trim()||r;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(r)||r.startsWith("```")))return r;try{const a=z(r,"--add");return Object.keys(a).map(s=>s.trim().toLowerCase()).some(s=>s!=="text")?r:a.text?.trim()||r}catch{return r}}function ie(e){return typeof e=="object"&&e!==null&&"code"in e}function G(e,t){if(!U(e))throw new l(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,c.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function de(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new l(`Specify ${t} text using only one input source: --add, --stdin, or --file`,c.USAGE);const n=H(),o=U(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",o)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return G(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;const a=e.file.trim();if(!a)throw new l("--file path cannot be empty",c.USAGE);if(a==="-")return G(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await q(a,"utf8"),emptyFlag:"--file"}}catch(i){if(ie(i)&&j(i))throw new l(`--file path not found: ${a}. Use --file - to read stdin.`,c.USAGE);const d=i instanceof Error?i.message:String(i);throw new l(`Failed to read --file path "${a}": ${d}. Use --file - to read stdin.`,c.USAGE)}}async function Re(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new l("Specify only one of --edit or --delete",c.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new l("--delete cannot be combined with replacement text",c.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new l("--delete must be a positive integer",c.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new l("--edit must be a positive integer",c.USAGE);const r=await de(e,t);if(e.edit!==void 0){if(!r)throw new l("--edit requires replacement text from --add, --stdin, or --file",c.USAGE);return{mode:"edit",index:e.edit,...r}}return r?{mode:"add",...r}:{mode:"list"}}function K(e,t){throw e instanceof l&&e.exitCode===c.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new l(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function N(e){return e==="comments"?"--stdin":"--add -"}const Le="annotation_flag_like_value";function se(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function le(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function ce(e){const t=e.value.trim(),r=e.collectionKey.replace(/s$/,""),n=le(t),o=N(e.collectionKey),a=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:v(e.retryArgs),suggested_retry_args:[...e.retryArgs]}};if(n!==void 0){const i=n.split(/[ =]/,1)[0],d=i==="--file"?"that file":"stdin",s=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${i} cannot be combined with: drop it, or pass it as the text without ${i}.`;return new l(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${i} as its value. Drop ${e.textFlag} and pass ${n} on its own.${s}`,c.USAGE,{code:"annotation_flag_like_value",required:`Drop ${e.textFlag}: ${n} reads the ${r} text from ${d} by itself. Use ${e.textFlag} text=${t} only when the text really is "${t}".`,examples:[`${e.commandPrefix} ${n}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...a})}return new l(`${e.textFlag} value "${t}" looks like an option, not annotation text. Use ${o} to read stdin, or use text=${t} for literal dash-leading text.`,c.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${t} when the text really starts with "-".`,examples:[`${e.commandPrefix} ${o}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...a})}function ue(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!se(e)))throw ce({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function me(e,t,r,n,o){if(r.input.mode!=="edit")return;const a=Y(t);if(a===void 0)return;const i=r.collectionKey.replace(/s$/,""),d=r.input.index,s=J(n)[0]==="--pm-path"?["--pm-path",o]:[];throw new l(`Replacement text for ${i} ${d} on ${e} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${a} characters. Nothing was written.`,c.USAGE,{code:"annotation_text_compacted",item_id:e,details:{collection:r.collectionKey,entry_index:d,omitted_characters:a},required:`Read the whole ${i} with --output-budget unbounded, apply the change to the full text, and retry the edit without the trailing marker.`,why:"A budgeted read shortens long entries to a prefix plus a marker naming how many characters it left out; editing from that text would replace the stored entry with the shortened prefix.",examples:[v([...s,r.collectionKey,e,"--output-budget","unbounded","--json"]),`${v([...s,r.collectionKey,e,"--edit",String(d),"--file"])} <full-text-file>`]})}function fe(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new l(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,c.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(pe(e,t),e.input.mode!=="list"||t.message===void 0)return;const r=e.collectionKey.replace(/s$/,"");throw new l(`--message labels a ${r} mutation but does not provide ${r} text. Pass text positionally or with --add, --stdin, or --file.`,c.USAGE,{code:"annotation_message_without_text",required:`Provide ${r} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${N(e.collectionKey)}`]})}function pe(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new l(`--expect-at guards an --edit or --delete of one ${e.collectionKey.replace(/s$/,"")}`,c.USAGE,{code:"annotation_expectation_without_target",required:"Combine --expect-at with --edit <index> or --delete <index>; omit it for list and append operations.",examples:[`pm ${e.collectionKey} <id> --edit <index> --expect-at <created_at> --add "<text>"`,`pm ${e.collectionKey} <id> --delete <index> --expect-at <created_at>`]});if(typeof t.expectAt!="string"||t.expectAt.trim().length===0)throw new l("--expect-at must be the non-empty created_at timestamp of the entry you read",c.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function T(e,t,r,n,o){if(o===void 0)return;const a=t[r]?.created_at,i=typeof a=="string"?a:null;if(i===o)return;const d=t.flatMap((g,b)=>g?.created_at===o?[b+1]:[]),s=n.collectionKey.replace(/s$/,""),A=n.input.mode==="delete"?"--delete":"--edit",h=r+1,w=d.length===1?` The ${s} created at ${o} is at index ${d[0]}.`:d.length>1?` ${d.length} ${n.collectionKey} were created at ${o}: indexes ${d.join(", ")}.`:` No ${s} on ${e} was created at ${o}.`;throw new l(`${s.charAt(0).toUpperCase()}${s.slice(1)} ${h} on ${e} was created at ${i||"an unrecorded time (malformed entry)"}, not ${o}; refusing ${A} of an entry the caller did not read. Nothing was written.${w}`,c.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:n.collectionKey,entry_index:h,expected_created_at:o,actual_created_at:i,matching_indexes:d},required:`Address the ${s} by the index its listing row reports and keep --expect-at set to that row's created_at. When several indexes share the timestamp, inspect those rows before retrying, because the guard compares timestamps, not entry identities.`,why:"A listing page's position or count is not an entry address; only the row's index is, and the expectation checks that the entry at that index still carries the created_at that was read.",examples:[`pm ${n.collectionKey} ${e} --limit 5`,`pm ${n.collectionKey} ${e} ${A} ${d.length===1?d[0]:"<index>"} --expect-at ${o}${A==="--edit"?' --add "<text>"':""}`]})}function he(e,t,r,n,o,a){const i=x(e.metadata,t),d=o?i.findIndex(s=>I(s)&&s.author===r&&s.text===n):-1;return d>=0?{changedFields:[],written:i,position:d}:(i.push(a({created_at:O(),author:r,text:n})),e.metadata[t]=i,{changedFields:[t],written:i,position:i.length-1})}function P(e,t,r){return ne.has(e)?t.map((o,a)=>a).sort((o,a)=>re(t[o],t[a])||o-a).indexOf(r)+1:r+1}async function Me(e,t,r,n){fe(n,t);const o=ee(process.cwd(),r.path);await M(o);const a=await te(o),i=D(a,V()),d=X(t.limit);if(n.input.mode==="list"){const m=await Q(o,e,a.id_prefix,a.item_format,i.type_to_folder);if(!m)throw new l(`Item ${e} not found`,c.NOT_FOUND);const u=await B(m,{schema:a.schema}),$=x(u.document.metadata,n.collectionKey);return S(m.id,n.collectionKey,$,d,t.includeMeta===!0)}const s=Z(t.author,a.author_default);if(n.input.mode==="delete"){const m=n.deleteOp??n.op;let u;try{u=await C({pmRoot:o,settings:a,id:e,op:m,author:s,message:t.message,force:t.force,bypassAssigneeConflict:n.bypassOwnershipConflict,mutate(y){const f=x(y.metadata,n.collectionKey),p=R(n.input.index,f.length,n.collectionKey);return T(e,f,p,n,t.expectAt),k(f[p],"deleted"),f.splice(p,1),y.metadata[n.collectionKey]=f,{changedFields:[n.collectionKey]}}})}catch(y){K(y,n.conflictGuidance)}const $=x(u.item,n.collectionKey);return S(u.item.id,n.collectionKey,$,d,t.includeMeta===!0,{action:"delete",entryIndex:n.input.index},t.fullHistory===!0)}const A=n.input.rawValue??n.input.value??"";ue(A,n);const h=n.parseText(n.input.value??"");if(!h.trim())throw new l(`${n.input.emptyFlag??"--add"} text cannot be empty`,c.USAGE);if(me(e,h,n,r,o),n.input.mode==="edit"){const m=n.editOp??n.op;let u,$=0;try{u=await C({pmRoot:o,settings:a,id:e,op:m,author:s,message:t.message,force:t.force,bypassAssigneeConflict:n.bypassOwnershipConflict,mutate(p){const _=x(p.metadata,n.collectionKey),E=R(n.input.index,_.length,n.collectionKey);T(e,_,E,n,t.expectAt);const F=_[E];return k(F,"edited"),_[E]=ae(F,h,s,n.createEntry),$=P(n.collectionKey,_,E),p.metadata[n.collectionKey]=_,{changedFields:[n.collectionKey]}}})}catch(p){K(p,n.conflictGuidance)}const y=x(u.item,n.collectionKey),f=$;return S(u.item.id,n.collectionKey,y,d,t.includeMeta===!0,{action:"edit",entryIndex:f,entry:y[f-1]},t.fullHistory===!0)}let w,g=0;try{w=await C({pmRoot:o,settings:a,id:e,op:n.op,author:s,message:t.message,force:t.force,bypassAssigneeConflict:n.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(m){const u=he(m,n.collectionKey,s,h,t.ifAbsent===!0,n.createEntry);return g=P(n.collectionKey,u.written,u.position),{changedFields:u.changedFields}}})}catch(m){K(m,n.conflictGuidance)}const b=x(w.item,n.collectionKey);return S(w.item.id,n.collectionKey,b,d,t.includeMeta===!0,{action:"add",entryIndex:g,entry:b[g-1],changedCount:t.ifAbsent===!0?Math.min(w.changedFields.length,1):void 0},t.fullHistory===!0)}function R(e,t,r){if(e===void 0||!Number.isInteger(e)||e<1||e>t){const n=r.replace(/s$/,""),o=`${n.charAt(0).toUpperCase()}${n.slice(1)}`,a=t===1?`1 ${n}`:`${t} ${r}`;throw new l(`${o} index ${e??"(missing)"} out of range (item has ${a})`,c.USAGE)}return e-1}function ye(e,t,r){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!r},omission_receipt:{has_omissions:r,omitted_field_group_count:r?1:0,omitted_field_groups:r?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function L(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;const r={index:t,...e};return r.index=t,r}function xe(e,t){const r=e.length-t.length;return t.map((n,o)=>L(n,r+o+1))}function S(e,t,r,n,o,a,i=!1){const d=a===void 0||i?xe(r,oe(r,a!==void 0&&i?void 0:n)):a.entry===void 0?[]:[L(a.entry,a.entryIndex)],s=a!==void 0&&d.length<r.length;return{id:e,[t]:d,count:d.length,...a?.changedCount===void 0?{}:{changed:a.changedCount===1},...[o,a!==void 0].includes(!0)?{total_count:r.length,returned_count:d.length,has_more:s||d.length<r.length,...n!==void 0?{limit:n}:{}}:{},...ye(t,a,s)}}export{Le as ANNOTATION_FLAG_LIKE_VALUE_CODE,G as assertAnnotationStdinTransportAvailable,ce as createFlagLikeAnnotationValueRefusal,ie as isErrnoError,se as isFlagLikeAnnotationValue,oe as limitAnnotationEntries,Te as normalizeAnnotationTransportOptions,Pe as parseAnnotationTextInput,x as readAnnotationEntries,R as resolveAnnotationIndex,Re as resolveAnnotationInput,Me as runAnnotationCommand,K as wrapOwnershipConflict};
2
2
  //# sourceMappingURL=annotations.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();import{createHash}from"node:crypto";import fs from"node:fs/promises";import path from"node:path";import{appendWorkspaceAuditEvent,WORKSPACE_HISTORY_ID}from"../core/history/workspace-history.js";import{readSettings}from"../core/store/settings.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{readRuntimeString,readRuntimeStringArray}from"./runtime-input.js";function refuseAuthorAcknowledgmentArgument(message,context){throw new PmCliError(message,EXIT_CODE.USAGE,context)}const HISTORY_AUTHOR_ATTRIBUTION_BASELINE="2026-07-15T06:22:12.276Z",HISTORY_AUTHOR_ATTRIBUTION_BASELINE_MS=Date.parse(HISTORY_AUTHOR_ATTRIBUTION_BASELINE),HISTORY_AUTHOR_EVENT_CLASSIFICATIONS=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],historyStringValue=value=>typeof value=="string"?value:"",classifyHistoryAuthorEvent=parsed=>{const record=parsed??{},author=historyStringValue(record.author).trim().toLowerCase(),authorClass=Number(["","unknown"].includes(author)),timestampClass=+(Date.parse(historyStringValue(record.ts))>=HISTORY_AUTHOR_ATTRIBUTION_BASELINE_MS);return HISTORY_AUTHOR_EVENT_CLASSIFICATIONS[authorClass][timestampClass]};function inspectHistoryAuthorStreamWithActionableEvents(itemId,raw,sampleLimit=20,acknowledgedEvents=new Set,includeActionableEvents=!1){const samples=[],actionableEvents=[],unknownCounts={legacy_unknown:0,actionable_unknown:0},boundedSampleLimit=Math.max(0,sampleLimit);let checkedEvents=0,unknownEvents=0,acknowledgedActionableEvents=0;for(const[index,line]of raw.split(/\r?\n/).entries()){let parsed;try{parsed=JSON.parse(line)}catch{continue}checkedEvents+=1;const classification=classifyHistoryAuthorEvent(parsed);if(classification!=="attributed"){if(unknownEvents+=1,classification==="actionable_unknown"&&acknowledgedEvents.has(`${itemId}:${index+1}`)){acknowledgedActionableEvents+=1;continue}unknownCounts[classification]+=1,includeActionableEvents&&classification==="actionable_unknown"&&actionableEvents.push({item_id:itemId,line:index+1}),samples.length<boundedSampleLimit&&samples.push({item_id:itemId,line:index+1})}}return{checked_events:checkedEvents,unknown_event_count:unknownEvents,legacy_unknown_event_count:unknownCounts.legacy_unknown,actionable_unknown_event_count:unknownCounts.actionable_unknown,acknowledged_actionable_event_count:acknowledgedActionableEvents,samples,samples_truncated:unknownCounts.legacy_unknown+unknownCounts.actionable_unknown>samples.length,actionable_events:actionableEvents}}const inspectHistoryAuthorStream=(itemId,raw,sampleLimit=20,acknowledgedEvents=new Set)=>inspectHistoryAuthorStreamWithActionableEvents(itemId,raw,sampleLimit,acknowledgedEvents);function collectAcknowledgedUnknownEvents(raw){const acknowledged=new Set;for(const line of raw.split(/\r?\n/)){let parsed;try{parsed=JSON.parse(line)}catch{continue}const acknowledgment=(typeof parsed=="object"&&parsed!==null&&typeof parsed.context=="object"&&parsed.context!==null?parsed.context:{}).author_acknowledgment;if(!(typeof acknowledgment!="object"||acknowledgment===null||!Array.isArray(acknowledgment.events)))for(const event of acknowledgment.events)typeof event=="object"&&event!==null&&typeof event.item_id=="string"&&Number.isSafeInteger(event.line)&&acknowledged.add(`${event.item_id}:${String(event.line)}`)}return acknowledged}const scanHistoryAuthorAttribution=async(pmRoot,sampleLimit=20,includeActionableEvents=!1)=>{const historyDirectory=path.join(pmRoot,"history");let fileNames;try{fileNames=(await fs.readdir(historyDirectory)).filter(fileName=>fileName.endsWith(".jsonl")).sort((left,right)=>left.localeCompare(right))}catch{fileNames=[]}const affectedItemIds=new Set,samples=[],actionableEvents=[];let checkedStreams=0,checkedEvents=0,unknownEventCount=0,legacyUnknownEventCount=0,actionableUnknownEventCount=0,acknowledgedActionableEventCount=0;const workspaceFileName="_workspace.jsonl";let acknowledgedEvents=new Set;if(fileNames.includes(workspaceFileName))try{acknowledgedEvents=collectAcknowledgedUnknownEvents(await fs.readFile(path.join(historyDirectory,workspaceFileName),"utf8"))}catch{acknowledgedEvents=new Set}for(const fileName of fileNames){let raw;try{raw=await fs.readFile(path.join(historyDirectory,fileName),"utf8")}catch{continue}const itemId=fileName.slice(0,-6),inspected=inspectHistoryAuthorStreamWithActionableEvents(itemId,raw,sampleLimit-samples.length,acknowledgedEvents,includeActionableEvents);checkedStreams+=1,checkedEvents+=inspected.checked_events,unknownEventCount+=inspected.unknown_event_count,legacyUnknownEventCount+=inspected.legacy_unknown_event_count,actionableUnknownEventCount+=inspected.actionable_unknown_event_count,acknowledgedActionableEventCount+=inspected.acknowledged_actionable_event_count,inspected.unknown_event_count>0&&affectedItemIds.add(itemId),samples.push(...inspected.samples),includeActionableEvents&&actionableEvents.push(...inspected.actionable_events)}const undispositionedUnknownEventCount=legacyUnknownEventCount+actionableUnknownEventCount;return{checked_streams:checkedStreams,checked_events:checkedEvents,unknown_event_count:unknownEventCount,legacy_unknown_event_count:legacyUnknownEventCount,actionable_unknown_event_count:actionableUnknownEventCount,acknowledged_actionable_event_count:acknowledgedActionableEventCount,affected_item_ids:[...affectedItemIds].sort((left,right)=>left.localeCompare(right)),samples,samples_truncated:undispositionedUnknownEventCount>samples.length,...includeActionableEvents?{actionable_events:actionableEvents}:{}}};function normalizeUnknownAuthorHistoryEvents(events){return[...new Map(events.map(event=>[`${event.item_id}:${event.line}`,{item_id:event.item_id,line:event.line}])).values()].sort((left,right)=>left.item_id.localeCompare(right.item_id)||left.line-right.line)}async function readAcknowledgedUnknownEvents(pmRoot){try{return collectAcknowledgedUnknownEvents(await fs.readFile(path.join(pmRoot,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function isValidUnknownAuthorHistoryEvent(event){return(event.item_id===WORKSPACE_HISTORY_ID||/^[a-z0-9][a-z0-9-]*$/iu.test(event.item_id))&&Number.isSafeInteger(event.line)&&event.line>=1}function resolveAcknowledgmentPlanCoordinate(event,acknowledgedEvents,sourceLines){const sourceLine=sourceLines[event.line-1]??"";let parsed;try{parsed=JSON.parse(sourceLine)}catch{refuseAuthorAcknowledgmentArgument(`Unknown-author acknowledgment target ${event.item_id}:${event.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return classifyHistoryAuthorEvent(parsed)!=="actionable_unknown"&&refuseAuthorAcknowledgmentArgument(`Author acknowledgment target ${event.item_id}:${event.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...event,source_event_hash:createHash("sha256").update(sourceLine).digest("hex"),disposition:acknowledgedEvents.has(`${event.item_id}:${event.line}`)?"already_acknowledged":"actionable"}}async function resolveUnknownAuthorAcknowledgmentPlan(pmRoot,selector,coordinateLimit){const explicitEvents=selector.events??[],selectorCount=+(selector.all_actionable===!0)+ +(explicitEvents.length>0);selectorCount===0&&refuseAuthorAcknowledgmentArgument("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),selectorCount>1&&refuseAuthorAcknowledgmentArgument("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(coordinateLimit)||coordinateLimit<0)&&refuseAuthorAcknowledgmentArgument("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});const selectedEvents=normalizeUnknownAuthorHistoryEvents(selector.all_actionable===!0?(await scanHistoryAuthorAttribution(pmRoot,0,!0)).actionable_events:explicitEvents),acknowledgedEvents=await readAcknowledgedUnknownEvents(pmRoot),sourceLinesByItem=new Map;for(const event of selectedEvents)if(isValidUnknownAuthorHistoryEvent(event)||refuseAuthorAcknowledgmentArgument(`Unknown-author acknowledgment target ${event.item_id}:${event.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!sourceLinesByItem.has(event.item_id))try{sourceLinesByItem.set(event.item_id,(await fs.readFile(path.join(pmRoot,"history",`${event.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{refuseAuthorAcknowledgmentArgument(`Unknown-author acknowledgment target ${event.item_id}:${event.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}const completeCoordinates=selectedEvents.map(event=>resolveAcknowledgmentPlanCoordinate(event,acknowledgedEvents,sourceLinesByItem.get(event.item_id))),kind=selector.all_actionable===!0?"all_actionable":"events",planFingerprint=createHash("sha256").update(JSON.stringify({version:1,selection:kind,coordinates:completeCoordinates})).digest("hex"),actionableCount=completeCoordinates.filter(({disposition})=>disposition==="actionable").length;return{plan:{selection:{kind},selected_count:completeCoordinates.length,actionable_count:actionableCount,already_acknowledged_count:completeCoordinates.length-actionableCount,omitted_count:Math.max(0,completeCoordinates.length-coordinateLimit),coordinates:completeCoordinates.slice(0,coordinateLimit),plan_fingerprint:planFingerprint},completeCoordinates}}async function planUnknownAuthorHistoryAcknowledgment(pmRoot,selector,coordinateLimit=50){return(await resolveUnknownAuthorAcknowledgmentPlan(pmRoot,selector,coordinateLimit)).plan}function resolveUnknownAuthorAcknowledgmentSelector(rawEvents,allActionable){const hasExplicitEvents=rawEvents.length>0;return hasExplicitEvents&&allActionable&&refuseAuthorAcknowledgmentArgument("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!hasExplicitEvents&&!allActionable&&refuseAuthorAcknowledgmentArgument("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:parseUnknownAuthorHistoryEventCoordinates(rawEvents),all_actionable:allActionable}}function parseUnknownAuthorHistoryEventCoordinates(values){return values.map(value=>{const separator=value.lastIndexOf(":"),itemId=value.slice(0,separator).trim(),line=Number(value.slice(separator+1)),validItemId=itemId===WORKSPACE_HISTORY_ID||/^[a-z0-9][a-z0-9-]*$/iu.test(itemId);return(separator<1||!validItemId||!Number.isSafeInteger(line)||line<1)&&refuseAuthorAcknowledgmentArgument(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${value}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:itemId,line}})}function acknowledgeUnknownAuthorHistoryEventsFromTransport(pmRoot,input){const selector=resolveUnknownAuthorAcknowledgmentSelector(readRuntimeStringArray(input.historyEvent),input.allActionable===!0||input.all_actionable===!0);return acknowledgeUnknownAuthorHistoryEvents(pmRoot,{events:selector.events,all_actionable:selector.all_actionable,dry_run:input.dryRun===!0||input.dry_run===!0,plan_fingerprint:readRuntimeString(input,"planFingerprint")??readRuntimeString(input,"plan_fingerprint"),coordinate_limit:typeof input.limit=="number"?input.limit:typeof input.limit=="string"?Number(input.limit):void 0,attributed_author:readRuntimeString(input,"attributedAuthor")??readRuntimeString(input,"attributed_author")??void 0,reviewer:readRuntimeString(input,"reviewer"),reason:readRuntimeString(input,"reason")})}async function acknowledgeUnknownAuthorHistoryEvents(pmRoot,options){const reviewer=options.reviewer?.trim()??"",attributedAuthor=options.attributed_author?.trim()??"",reason=options.reason?.trim()??"",resolved=await resolveUnknownAuthorAcknowledgmentPlan(pmRoot,options,options.coordinate_limit??50);if(options.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:EXIT_CODE.SUCCESS,plan:resolved.plan};if([reviewer.length>0,reviewer.toLowerCase()!=="unknown",attributedAuthor.length>0,attributedAuthor.toLowerCase()!=="unknown",reason.length>0].includes(!1)&&refuseAuthorAcknowledgmentArgument("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),options.plan_fingerprint?.trim()||refuseAuthorAcknowledgmentArgument("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),options.plan_fingerprint.trim()!==resolved.plan.plan_fingerprint)throw new PmCliError("Author acknowledgment selection changed after preview; no history was mutated.",EXIT_CODE.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});const eventsToAcknowledge=resolved.completeCoordinates.filter(({disposition})=>resolved.plan.selection.kind==="events"||disposition==="actionable").map(({item_id,line})=>({item_id,line}));if(eventsToAcknowledge.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:EXIT_CODE.NO_EFFECT,plan:resolved.plan};const settings=await readSettings(pmRoot),appended=await appendWorkspaceAuditEvent({pmRoot,op:"history:author-acknowledge",author:reviewer,context:{author_acknowledgment:{events:eventsToAcknowledge,attributed_author:attributedAuthor}},message:reason,lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms}),effectResult=resolved.plan.actionable_count>0&&resolved.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:EXIT_CODE.PARTIAL_EFFECT}:{outcome:"effect",exit_code:EXIT_CODE.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:eventsToAcknowledge.length,...effectResult,plan:resolved.plan,history_path:appended.historyPath}}export{HISTORY_AUTHOR_ATTRIBUTION_BASELINE,acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,classifyHistoryAuthorEvent,inspectHistoryAuthorStream,parseUnknownAuthorHistoryEventCoordinates,planUnknownAuthorHistoryAcknowledgment,resolveUnknownAuthorAcknowledgmentSelector,scanHistoryAuthorAttribution};
1
+ import{createHash as E}from"node:crypto";import b from"node:fs/promises";import v from"node:path";import{appendWorkspaceAuditEvent as H,WORKSPACE_HISTORY_ID as x}from"../core/history/workspace-history.js";import{readSettings as R}from"../core/store/settings.js";import{EXIT_CODE as f}from"../core/shared/constants.js";import{PmCliError as C}from"../core/shared/errors.js";import{readRuntimeString as k,readRuntimeStringArray as j}from"./runtime-input.js";function d(t,e){throw new C(t,f.USAGE,e)}const F="2026-07-15T06:22:12.276Z",q=Date.parse(F),L=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],I=t=>typeof t=="string"?t:"",N=t=>{const e=t??{},n=I(e.author).trim().toLowerCase(),o=Number(["","unknown"].includes(n)),i=+(Date.parse(I(e.ts))>=q);return L[o][i]};function T(t,e,n=20,o=new Set,i=!1){const a=[],c=[],l={legacy_unknown:0,actionable_unknown:0},s=Math.max(0,n);let _=0,h=0,u=0;for(const[r,A]of e.split(/\r?\n/).entries()){let y;try{y=JSON.parse(A)}catch{continue}_+=1;const w=N(y);if(w!=="attributed"){if(h+=1,w==="actionable_unknown"&&o.has(`${t}:${r+1}`)){u+=1;continue}l[w]+=1,i&&w==="actionable_unknown"&&c.push({item_id:t,line:r+1}),a.length<s&&a.push({item_id:t,line:r+1})}}return{checked_events:_,unknown_event_count:h,legacy_unknown_event_count:l.legacy_unknown,actionable_unknown_event_count:l.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:l.legacy_unknown+l.actionable_unknown>a.length,actionable_events:c}}const ne=(t,e,n=20,o=new Set)=>T(t,e,n,o);function U(t){const e=new Set;for(const n of t.split(/\r?\n/)){let o;try{o=JSON.parse(n)}catch{continue}const a=(typeof o=="object"&&o!==null&&typeof o.context=="object"&&o.context!==null?o.context:{}).author_acknowledgment;if(!(typeof a!="object"||a===null||!Array.isArray(a.events)))for(const c of a.events)typeof c=="object"&&c!==null&&typeof c.item_id=="string"&&Number.isSafeInteger(c.line)&&e.add(`${c.item_id}:${String(c.line)}`)}return e}const M=async(t,e=20,n=!1)=>{const o=v.join(t,"history");let i;try{i=(await b.readdir(o)).filter(m=>m.endsWith(".jsonl")).sort((m,p)=>m.localeCompare(p))}catch{i=[]}const a=new Set,c=[],l=[];let s=0,_=0,h=0,u=0,r=0,A=0;const y="_workspace.jsonl";let w=new Set;if(i.includes(y))try{w=U(await b.readFile(v.join(o,y),"utf8"))}catch{w=new Set}for(const m of i){let p;try{p=await b.readFile(v.join(o,m),"utf8")}catch{continue}const S=m.slice(0,-6),g=T(S,p,e-c.length,w,n);s+=1,_+=g.checked_events,h+=g.unknown_event_count,u+=g.legacy_unknown_event_count,r+=g.actionable_unknown_event_count,A+=g.acknowledged_actionable_event_count,g.unknown_event_count>0&&a.add(S),c.push(...g.samples),n&&l.push(...g.actionable_events)}const O=u+r;return{checked_streams:s,checked_events:_,unknown_event_count:h,legacy_unknown_event_count:u,actionable_unknown_event_count:r,acknowledged_actionable_event_count:A,affected_item_ids:[...a].sort((m,p)=>m.localeCompare(p)),samples:c,samples_truncated:O>c.length,...n?{actionable_events:l}:{}}};function V(t){return[...new Map(t.map(e=>[`${e.item_id}:${e.line}`,{item_id:e.item_id,line:e.line}])).values()].sort((e,n)=>e.item_id.localeCompare(n.item_id)||e.line-n.line)}async function P(t){try{return U(await b.readFile(v.join(t,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function z(t){return(t.item_id===x||/^[a-z0-9][a-z0-9-]*$/iu.test(t.item_id))&&Number.isSafeInteger(t.line)&&t.line>=1}function B(t,e,n){const o=n[t.line-1]??"";let i;try{i=JSON.parse(o)}catch{d(`Unknown-author acknowledgment target ${t.item_id}:${t.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return N(i)!=="actionable_unknown"&&d(`Author acknowledgment target ${t.item_id}:${t.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...t,source_event_hash:E("sha256").update(o).digest("hex"),disposition:e.has(`${t.item_id}:${t.line}`)?"already_acknowledged":"actionable"}}async function $(t,e,n){const o=e.events??[],i=+(e.all_actionable===!0)+ +(o.length>0);i===0&&d("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&d("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&d("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});const a=V(e.all_actionable===!0?(await M(t,0,!0)).actionable_events:o),c=await P(t),l=new Map;for(const r of a)if(z(r)||d(`Unknown-author acknowledgment target ${r.item_id}:${r.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!l.has(r.item_id))try{l.set(r.item_id,(await b.readFile(v.join(t,"history",`${r.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{d(`Unknown-author acknowledgment target ${r.item_id}:${r.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}const s=a.map(r=>B(r,c,l.get(r.item_id))),_=e.all_actionable===!0?"all_actionable":"events",h=E("sha256").update(JSON.stringify({version:1,selection:_,coordinates:s})).digest("hex"),u=s.filter(({disposition:r})=>r==="actionable").length;return{plan:{selection:{kind:_},selected_count:s.length,actionable_count:u,already_acknowledged_count:s.length-u,omitted_count:Math.max(0,s.length-n),coordinates:s.slice(0,n),plan_fingerprint:h},completeCoordinates:s}}async function oe(t,e,n=50){return(await $(t,e,n)).plan}function D(t,e){const n=t.length>0;return n&&e&&d("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!e&&d("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:W(t),all_actionable:e}}function W(t){return t.map(e=>{const n=e.lastIndexOf(":"),o=e.slice(0,n).trim(),i=Number(e.slice(n+1)),a=o===x||/^[a-z0-9][a-z0-9-]*$/iu.test(o);return(n<1||!a||!Number.isSafeInteger(i)||i<1)&&d(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${e}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:o,line:i}})}function ae(t,e){const n=D(j(e.historyEvent),e.allActionable===!0||e.all_actionable===!0);return J(t,{events:n.events,all_actionable:n.all_actionable,dry_run:e.dryRun===!0||e.dry_run===!0,plan_fingerprint:k(e,"planFingerprint")??k(e,"plan_fingerprint"),coordinate_limit:typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,attributed_author:k(e,"attributedAuthor")??k(e,"attributed_author")??void 0,reviewer:k(e,"reviewer"),reason:k(e,"reason")})}async function J(t,e){const n=e.reviewer?.trim()??"",o=e.attributed_author?.trim()??"",i=e.reason?.trim()??"",a=await $(t,e,e.coordinate_limit??50);if(e.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:f.SUCCESS,plan:a.plan};if([n.length>0,n.toLowerCase()!=="unknown",o.length>0,o.toLowerCase()!=="unknown",i.length>0].includes(!1)&&d("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),e.plan_fingerprint?.trim()||d("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),e.plan_fingerprint.trim()!==a.plan.plan_fingerprint)throw new C("Author acknowledgment selection changed after preview; no history was mutated.",f.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});const l=a.completeCoordinates.filter(({disposition:u})=>a.plan.selection.kind==="events"||u==="actionable").map(({item_id:u,line:r})=>({item_id:u,line:r}));if(l.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:f.NO_EFFECT,plan:a.plan};const s=await R(t),_=await H({pmRoot:t,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:o}},message:i,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms}),h=a.plan.actionable_count>0&&a.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:f.PARTIAL_EFFECT}:{outcome:"effect",exit_code:f.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:l.length,...h,plan:a.plan,history_path:_.historyPath}}export{F as HISTORY_AUTHOR_ATTRIBUTION_BASELINE,J as acknowledgeUnknownAuthorHistoryEvents,ae as acknowledgeUnknownAuthorHistoryEventsFromTransport,N as classifyHistoryAuthorEvent,ne as inspectHistoryAuthorStream,W as parseUnknownAuthorHistoryEventCoordinates,oe as planUnknownAuthorHistoryAcknowledgment,D as resolveUnknownAuthorAcknowledgmentSelector,M as scanHistoryAuthorAttribution};
2
2
  //# sourceMappingURL=author-attribution.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="10f173af-3f3d-5678-85a1-267469d22069")}catch{}})();import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"./cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand}from"./cli-contracts/flag-contracts.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{findPmNamespacedCommand,resolvePmCommandOperation}from"./cli-contracts/command-aliases.js";import{normalizeItemAddressInvocation}from"./agent/item-addressing.js";import{BOOTSTRAP_BOOLEAN_FLAGS,GLOBAL_VALUE_CONSUMING_FLAGS,consumesBootstrapValue,findBootstrapCommandTokenIndex as findContractBootstrapCommandTokenIndex,isInlineGlobalValueToken,parseBootstrapCommandName as parseContractBootstrapCommandName}from"./cli-contracts/bootstrap-command-scanner.js";const OUTPUT_VALUE_FLAGS=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]),BOOTSTRAP_OUTPUT_ENCODINGS=new Set(["toon","json"]);function consumeBootstrapGlobalToken(argv,index,state){const token=argv[index];if(BOOTSTRAP_BOOLEAN_FLAGS.has(token))return state.booleanFlags.add(token),1;const equalsIndex=token.indexOf("="),canonicalFlag=equalsIndex>0?token.slice(0,equalsIndex):token;if(!GLOBAL_VALUE_CONSUMING_FLAGS.has(canonicalFlag))return 1;const inlineValue=equalsIndex>0?token.slice(equalsIndex+1):void 0,consumesValue=inlineValue===void 0&&consumesBootstrapValue(canonicalFlag,argv[index+1]),value=inlineValue??(consumesValue?argv[index+1]:void 0);return canonicalFlag==="--author"?state.author=value??"":typeof value=="string"&&value.length>0&&(OUTPUT_VALUE_FLAGS.has(canonicalFlag)?state.outputValues:state.pathValues).set(canonicalFlag,value),consumesValue?2:1}function isBootstrapJsonOutput(state){return state.outputValues.get("--output-format")!=="toon"&&(state.booleanFlags.has("--json")||state.outputValues.get("--output-format")==="json"||state.pathValues.get("--format")?.trim().toLowerCase()==="json")}function parseBootstrapGlobalOptions(argv){const state={booleanFlags:new Set,outputValues:new Map,pathValues:new Map};let index=0;for(;index<argv.length&&argv[index]!=="--";)index+=consumeBootstrapGlobalToken(argv,index,state);return{path:state.pathValues.get("--pm-path")??state.pathValues.get("--path"),noExtensions:state.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(parseBootstrapCommandPathName(argv)??""),noPager:state.booleanFlags.has("--no-pager"),json:isBootstrapJsonOutput(state),quiet:state.booleanFlags.has("--quiet"),lean:state.booleanFlags.has("--lean"),tokenAccounting:state.booleanFlags.has("--token-accounting"),...state.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...state.outputValues.get("--output-include")===void 0?{}:{outputInclude:state.outputValues.get("--output-include")},...state.outputValues.get("--output-limit")===void 0?{}:{outputLimit:state.outputValues.get("--output-limit")},...state.outputValues.get("--output-budget")===void 0?{}:{outputBudget:state.outputValues.get("--output-budget")},...BOOTSTRAP_OUTPUT_ENCODINGS.has(state.outputValues.get("--output-format"))?{outputFormat:state.outputValues.get("--output-format")}:{},...state.outputValues.get("--output-session")===void 0?{}:{outputSession:state.outputValues.get("--output-session")},...state.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:state.outputValues.get("--output-cursor")},...state.author===""?{authorMissingValue:!0}:state.author!==void 0?{author:state.author}:{}}}function stripGlobalBootstrapTokens(argv){const remaining=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")break;if(BOOTSTRAP_BOOLEAN_FLAGS.has(token)||token==="--profile"||token==="--id-only"||token==="--full-changed-fields"||token==="--explain"){index+=1;continue}if(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)){index+=consumesBootstrapValue(token,argv[index+1])?2:1;continue}if(isInlineGlobalValueToken(token)){index+=1;continue}remaining.push(token),index+=1}return remaining}function parseBootstrapHelpRequest(argv){const stripped=stripGlobalBootstrapTokens(argv);if(stripped[0]?.trim().toLowerCase()==="help"){const commandPathTokens2=[];for(let index=1;index<stripped.length;index+=1){const token=stripped[index];if(token.startsWith("-"))break;commandPathTokens2.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens:commandPathTokens2}}if(stripped.findIndex(token=>token==="--help"||token==="-h")<0)return{requested:!1,commandPathTokens:[]};const commandPathTokens=[];for(const token of stripped){if(token.startsWith("-"))break;commandPathTokens.push(token.trim().toLowerCase())}return{requested:!0,commandPathTokens}}function findBootstrapCommandTokenIndex(argv){return findContractBootstrapCommandTokenIndex(argv)}function parseBootstrapCommandName(argv){return parseContractBootstrapCommandName(argv)}function shouldDisablePagerForInvocation(argv,bootstrapGlobal){return bootstrapGlobal.noPager?!0:process.stdout.isTTY===!0?!1:parseBootstrapHelpRequest(argv).requested}function applyBootstrapPagerPolicy(argv){const pagerEnvironmentKeys=["PAGER","MANPAGER","GIT_PAGER","LESS"],previousValues=pagerEnvironmentKeys.map(key=>process.env[key]),restore=()=>{for(const[index,key]of pagerEnvironmentKeys.entries()){const value=previousValues[index];value===void 0?delete process.env[key]:process.env[key]=value}},bootstrapGlobal=parseBootstrapGlobalOptions(argv);return shouldDisablePagerForInvocation(argv,bootstrapGlobal)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),restore}const EXTENSION_ACTION_SYNTAX_TOKENS=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function normalizeLegacyExtensionActionSyntax(argv){const extensionIndex=findBootstrapCommandTokenIndex(argv);if(extensionIndex===void 0||argv[extensionIndex]!=="extension")return[...argv];const actionToken=argv[extensionIndex+1];if(!actionToken||actionToken.startsWith("-"))return[...argv];if(!EXTENSION_ACTION_SYNTAX_TOKENS.has(actionToken))return[...argv];if(argv.includes("--help")||argv.includes("-h"))return[...argv];const forcedActionFlag=`--${actionToken}`;return argv.includes(forcedActionFlag)?[...argv]:[...argv.slice(0,extensionIndex+1),forcedActionFlag,...argv.slice(extensionIndex+2)]}const CLI_EXECUTABLE_ALIASES=new Set(["pm","pm-cli"]);function stripLeadingExecutableAlias(argv,trace){const index=findBootstrapCommandTokenIndex(argv);if(index===void 0)return argv;const token=argv[index];return CLI_EXECUTABLE_ALIASES.has(token.trim().toLowerCase())?(trace.push({from:token,to:[],reason:"executable_alias",confidence:"high"}),[...argv.slice(0,index),...argv.slice(index+1)]):argv}function rewriteCommandAlias(argv,trace){let index=findBootstrapCommandTokenIndex(argv);if(index!==void 0&&argv[index]==="help"){const offset=findBootstrapCommandTokenIndex(argv.slice(index+1));index=offset===void 0?void 0:index+1+offset}if(index===void 0)return argv;const token=argv[index],canonical=EXECUTABLE_COMMAND_ALIASES[token.trim().toLowerCase()];if(!canonical)return argv;const canonicalTokens=canonical.split(" "),rewritten=[...argv.slice(0,index),...canonicalTokens,...argv.slice(index+1)];return trace.push({from:token,to:canonicalTokens,reason:"command_alias",confidence:"high"}),rewritten}function normalizeFlagKeyToken(raw){return raw.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function toComparableFlagKey(raw){return normalizeFlagKeyToken(raw).replace(/-/g,"")}function markUnambiguousFlag(map,key,canonicalFlag){const existing=map.get(key);if(existing===void 0){map.set(key,canonicalFlag);return}existing!==canonicalFlag&&map.set(key,null)}function collectLongFlagCandidates(contract){const candidates=[],pushLongFlag=value=>{typeof value=="string"&&value.startsWith("--")&&candidates.push(value)};pushLongFlag(contract.flag);for(const alias of contract.aliases??[])pushLongFlag(alias);return candidates}function buildFlagLookup(commandName,contractsOverride){const contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName),canonicalByNormalized=new Map,canonicalByCompact=new Map,canonicalComparablesMap=new Map,listCanonicalFlags=new Set;for(const contract of contracts){const longCandidates=collectLongFlagCandidates(contract);if(longCandidates.length===0)continue;const canonicalFlag=`--${normalizeFlagKeyToken(longCandidates[0])}`;for(const candidate of longCandidates)markUnambiguousFlag(canonicalByNormalized,normalizeFlagKeyToken(candidate),canonicalFlag),markUnambiguousFlag(canonicalByCompact,toComparableFlagKey(candidate),canonicalFlag);const comparable=toComparableFlagKey(canonicalFlag);canonicalComparablesMap.has(canonicalFlag)||canonicalComparablesMap.set(canonicalFlag,comparable),contract.list===!0&&listCanonicalFlags.add(canonicalFlag)}return{canonicalByNormalized,canonicalByCompact,canonicalComparables:[...canonicalComparablesMap.entries()].map(([canonicalFlag,comparable])=>({canonicalFlag,comparable})),listCanonicalFlags}}function resolveCanonicalFlag(rawKey,lookup){const normalizedKey=normalizeFlagKeyToken(rawKey),direct=lookup.canonicalByNormalized.get(normalizedKey);if(typeof direct=="string")return{flag:direct,reason:"flag_alias",confidence:"high"};const comparableKey=normalizedKey.replace(/-/g,""),compactMatch=lookup.canonicalByCompact.get(comparableKey);if(typeof compactMatch=="string")return{flag:compactMatch,reason:"flag_alias",confidence:"high"};const maxDistance=comparableKey.length>=8?2:1;let bestDistance=Number.POSITIVE_INFINITY,bestFlag,tied=!1;for(const candidate of lookup.canonicalComparables){const distance=levenshteinDistanceWithinLimit(comparableKey,candidate.comparable,maxDistance);if(distance!==null){if(distance<bestDistance){bestDistance=distance,bestFlag=candidate.canonicalFlag,tied=!1;continue}distance===bestDistance&&bestFlag!==candidate.canonicalFlag&&(tied=!0)}}return!bestFlag||tied||!Number.isFinite(bestDistance)||bestDistance<=0?null:{flag:bestFlag,reason:"flag_typo",confidence:bestDistance>=2?"medium":"high"}}function listAliasPluralKeys(normalizedKey){const candidates=[`${normalizedKey}s`];return normalizedKey.endsWith("y")&&normalizedKey.length>1&&candidates.push(`${normalizedKey.slice(0,-1)}ies`),candidates}function parseBareKeyValueToken(token,preserve=!1){if(preserve||token.includes("://"))return null;const match=token.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!match)return null;const key=match[1],value=match[3];return value.length===0||match[2]===":"&&/\s/u.test(token)?null:{key,value}}function normalizeLongOptionToken(token,lookup,preserve=!1){if(preserve||!token.startsWith("--"))return{tokens:[token]};const equalsIndex=token.indexOf("="),key=equalsIndex>=0?token.slice(0,equalsIndex):token,inlineValue=equalsIndex>=0?token.slice(equalsIndex+1):void 0,resolution=resolveCanonicalFlag(key,lookup);if(!resolution)return{tokens:[token]};const normalizedToken=inlineValue===void 0?resolution.flag:`${resolution.flag}=${inlineValue}`;return normalizedToken===token?{tokens:[token]}:{tokens:[normalizedToken],event:{from:token,to:[normalizedToken],reason:resolution.reason,confidence:resolution.confidence}}}function collectBootstrapPathValueIndices(argv){const indices=new Set;let expectsValue=!1;for(let index=0;index<argv.length;index+=1){if(expectsValue){indices.add(index),expectsValue=!1;continue}const token=argv[index];expectsValue=token==="--path"||token==="--pm-path"}return indices}function splitCanonicalListToken(token){if(!token.startsWith("--"))return null;const equalsIndex=token.indexOf("=");return equalsIndex<0?{flag:token}:{flag:token.slice(0,equalsIndex),inlineValue:token.slice(equalsIndex+1)}}function copyValueConsumingFlag(argv,index,result){result.push(argv[index]);const next=argv[index+1];return typeof next=="string"&&next!=="--"?(result.push(next),index+2):index+1}function readListFlagOccurrence(argv,index,parsed,multiValueListFlags){if(parsed.inlineValue!==void 0)return{originalTokens:[argv[index]],value:parsed.inlineValue,consumed:1};const values=[];let valueIndex=index+1;for(;valueIndex<argv.length&&argv[valueIndex]!=="--"&&!argv[valueIndex].startsWith("-")&&(values.length===0||multiValueListFlags.has(parsed.flag));)values.push(argv[valueIndex]),valueIndex+=1;const consumed=values.length===0?1:1+values.length;return{originalTokens:argv.slice(index,index+consumed),value:values.length===0?void 0:values.join(","),consumed}}function recordListFlagOccurrence(slots,result,flag,occurrence){const existing=slots.get(flag);if(existing){existing.values.push(occurrence.value),existing.occurrences+=1;return}slots.set(flag,{outputIndex:result.length,originalTokens:occurrence.originalTokens,values:[occurrence.value],occurrences:1}),result.push(null)}function buildListFlagCoalescingSplices(slots,multiValueListFlags){const events=[],splices=[];for(const[flag,slot]of slots){if(!(slot.occurrences>=2||multiValueListFlags.has(flag)&&slot.originalTokens.length>2)){splices.push({outputIndex:slot.outputIndex,tokens:slot.originalTokens});continue}const mergedToken=`${flag}=${slot.values.join(",")}`;splices.push({outputIndex:slot.outputIndex,tokens:[mergedToken]}),events.push({from:`${flag} (x${slot.occurrences})`,to:[mergedToken],reason:"list_merge",confidence:"high"})}return{events,splices}}function applyListFlagSplices(result,splices){splices.sort((a,b)=>b.outputIndex-a.outputIndex);for(const splice of splices)result.splice(splice.outputIndex,1,...splice.tokens)}function coalesceRepeatedListFlags(argv,listFlags,valueConsumingFlags=new Set,multiValueListFlags=new Set){if(listFlags.size===0)return{argv:[...argv],events:[]};const result=[],slots=new Map;let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--"){result.push(...argv.slice(index));break}if(valueConsumingFlags.has(token)){index=copyValueConsumingFlag(argv,index,result);continue}const parsed=splitCanonicalListToken(token);if(!parsed||!listFlags.has(parsed.flag)){result.push(token),index+=1;continue}const occurrence=readListFlagOccurrence(argv,index,parsed,multiValueListFlags);if(occurrence.value===void 0){result.push(token),index+=occurrence.consumed;continue}recordListFlagOccurrence(slots,result,parsed.flag,{originalTokens:occurrence.originalTokens,value:occurrence.value}),index+=occurrence.consumed}const{events,splices}=buildListFlagCoalescingSplices(slots,multiValueListFlags);return applyListFlagSplices(result,splices),{argv:result,events}}const LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function isLinkedTestTwoTokenValuePosition(commandName,emittedTokens){if(commandName!=="test"||emittedTokens.length<2)return!1;const key=emittedTokens[emittedTokens.length-1],flag=emittedTokens[emittedTokens.length-2],keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(flag);return keys!==void 0&&keys.has(key)}function mergeLinkedTestTwoTokenEntries(argv,commandName,trace){if(commandName!=="test")return argv;const result=[];let index=0;for(;index<argv.length;){const token=argv[index];if(token==="--")return result.push(...argv.slice(index)),result;const keys=LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(token),key=keys?argv[index+1]:void 0;if(!keys||typeof key!="string"||!keys.has(key)){result.push(token),index+=1;continue}let runEnd=index+2;for(;runEnd<argv.length&&!argv[runEnd].startsWith("-");)runEnd+=1;if(runEnd-(index+2)!==1){result.push(token),index+=1;continue}const value=argv[index+2],mergedValue=`${key}=${value}`;result.push(token,mergedValue),trace.push({from:`${token} ${key} ${value}`,to:[token,mergedValue],reason:"bare_key_value",confidence:"high"}),index+=3}return result}function normalizeBootstrapTokens(argv,lookup,commandName,trace){const normalizedArgv=[],pathValueIndices=collectBootstrapPathValueIndices(argv);for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--"){normalizedArgv.push(...argv.slice(index));break}const preserveCurrentToken=pathValueIndices.has(index),previous=normalizedArgv[normalizedArgv.length-1];if(token.startsWith("--")){const normalizedToken=normalizeLongOptionToken(token,lookup,preserveCurrentToken);normalizedArgv.push(...normalizedToken.tokens),normalizedToken.event&&trace.push(normalizedToken.event);continue}const bareKeyValue=parseBareKeyValueToken(token,preserveCurrentToken);if(!bareKeyValue||typeof previous=="string"&&previous.startsWith("-")&&!previous.includes("=")||["search","comments","notes","learnings"].includes(commandName)||isLinkedTestTwoTokenValuePosition(commandName,normalizedArgv)){normalizedArgv.push(token);continue}const resolution=resolveCanonicalFlag(bareKeyValue.key,lookup);if(!resolution){normalizedArgv.push(token);continue}const replacement=bareKeyValue.value.startsWith("-")?[`${resolution.flag}=${bareKeyValue.value}`]:[resolution.flag,bareKeyValue.value];normalizedArgv.push(...replacement),trace.push({from:token,to:replacement,reason:"bare_key_value",confidence:resolution.confidence})}return normalizedArgv}function bindAttestationVerification(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--verify"){const value=argv[index+1];if(value===void 0||value==="--")throw new PmCliError("history attest --verify requires a bundle file.",EXIT_CODE.USAGE);argv.splice(index,2,`--verify=${value}`)}else(GLOBAL_VALUE_CONSUMING_FLAGS.has(token)||token==="--output"||token==="--hash-algorithm")&&(index+=1)}}function protectBootstrapHelpDiscovery(argv,command){if(!argv.some(token=>token==="--help"||token==="-h"))return;const declaredFlags=new Set(resolveSubcommandFlagContractsForCommand(command).flatMap(contract=>[contract.flag,...contract.aliases??[],...contract.short===void 0?[]:[contract.short]]));for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;token!=="--help"&&token!=="-h"||declaredFlags.has(argv[index-1])&&!BOOTSTRAP_BOOLEAN_FLAGS.has(argv[index-1])&&(argv[index-1]=token)}}function normalizeBootstrapInvocation(argv){const trace=[],executableNormalized=stripLeadingExecutableAlias(argv,trace),legacyNormalized=normalizeLegacyExtensionActionSyntax(executableNormalized);(legacyNormalized.length!==executableNormalized.length||legacyNormalized.some((token,index)=>token!==executableNormalized[index]))&&trace.push({from:executableNormalized.join(" "),to:[...legacyNormalized],reason:"legacy_extension_action",confidence:"high"});const aliasNormalized=rewriteCommandAlias(legacyNormalized,trace),itemAddress=normalizeItemAddressInvocation(aliasNormalized);if(itemAddress.conflict)throw new PmCliError("Provide the item id either positionally or with --id, not both.",EXIT_CODE.USAGE);itemAddress.changed&&trace.push({from:`--id ${itemAddress.itemId}`,to:[itemAddress.itemId],reason:"item_id_alias",confidence:"high"});const commandName=parseBootstrapCommandName(itemAddress.argv),commandPathName=parseBootstrapCommandPathName(itemAddress.argv),operationName=resolvePmCommandOperation(commandPathName??commandName??""),lookup=buildFlagLookup(commandPathName??commandName),normalizedArgv=normalizeBootstrapTokens(itemAddress.argv,lookup,operationName,trace),linkedTestNormalized=mergeLinkedTestTwoTokenEntries(normalizedArgv,operationName,trace),coalesced=coalesceRepeatedListFlags(linkedTestNormalized,lookup.listCanonicalFlags,GLOBAL_VALUE_CONSUMING_FLAGS,commandName==="create"?new Set(["--tags"]):new Set);for(const event of coalesced.events)trace.push(event);return protectBootstrapHelpDiscovery(coalesced.argv,commandPathName??commandName),commandPathName==="history attest"&&bindAttestationVerification(coalesced.argv),{argv:coalesced.argv,commandName,trace}}function parseBootstrapCommandPathName(argv){const stripped=stripGlobalBootstrapTokens(argv),first=stripped[0]?.trim().toLowerCase(),second=stripped[1]?.trim().toLowerCase(),namespaced=findPmNamespacedCommand(stripped);return namespaced?namespaced.canonical:(first==="extension"||first==="package"||first==="packages")&&typeof second=="string"&&second.length>0&&!second.startsWith("-")?`${first} ${second}`:first}function parseBootstrapTypeValue(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(token==="--")break;if(token==="--type"){const candidate=argv[index+1];if(typeof candidate=="string"&&candidate.trim().length>0)return candidate.trim();continue}if(token.startsWith("--type=")){const candidate=token.slice(7).trim();if(candidate.length>0)return candidate}}}const _testOnly={buildFlagLookup,collectBootstrapPathValueIndices,collectLongFlagCandidates,markUnambiguousFlag,normalizeLongOptionToken,resolveCanonicalFlag};export{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,_testOnly,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,findBootstrapCommandTokenIndex,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,stripGlobalBootstrapTokens};
1
+ import{EXECUTABLE_COMMAND_ALIASES as C,PM_COMMAND_ALIAS_CONTRACTS as B,renderPmCommandAliasMigrationHint as O,resolvePmCommandAlias as $}from"./cli-contracts/command-aliases.js";import{resolveSubcommandFlagContractsForCommand as b}from"./cli-contracts/flag-contracts.js";import{levenshteinDistanceWithinLimit as G}from"../core/shared/levenshtein.js";import{EXIT_CODE as y}from"../core/shared/constants.js";import{PmCliError as w}from"../core/shared/errors.js";import{findPmNamespacedCommand as M,resolvePmCommandOperation as z}from"./cli-contracts/command-aliases.js";import{normalizeItemAddressInvocation as W}from"./agent/item-addressing.js";import{BOOTSTRAP_BOOLEAN_FLAGS as x,GLOBAL_VALUE_CONSUMING_FLAGS as h,consumesBootstrapValue as A,findBootstrapCommandTokenIndex as R,isInlineGlobalValueToken as q,parseBootstrapCommandName as U}from"./cli-contracts/bootstrap-command-scanner.js";const D=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]),K=new Set(["toon","json"]);function j(e,t,o){const n=e[t];if(x.has(n))return o.booleanFlags.add(n),1;const s=n.indexOf("="),i=s>0?n.slice(0,s):n;if(!h.has(i))return 1;const a=s>0?n.slice(s+1):void 0,u=a===void 0&&A(i,e[t+1]),r=a??(u?e[t+1]:void 0);return i==="--author"?o.author=r??"":typeof r=="string"&&r.length>0&&(D.has(i)?o.outputValues:o.pathValues).set(i,r),u?2:1}function X(e){return e.outputValues.get("--output-format")!=="toon"&&(e.booleanFlags.has("--json")||e.outputValues.get("--output-format")==="json"||e.pathValues.get("--format")?.trim().toLowerCase()==="json")}function Y(e){const t={booleanFlags:new Set,outputValues:new Map,pathValues:new Map};let o=0;for(;o<e.length&&e[o]!=="--";)o+=j(e,o,t);return{path:t.pathValues.get("--pm-path")??t.pathValues.get("--path"),noExtensions:t.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(N(e)??""),noPager:t.booleanFlags.has("--no-pager"),json:X(t),quiet:t.booleanFlags.has("--quiet"),lean:t.booleanFlags.has("--lean"),tokenAccounting:t.booleanFlags.has("--token-accounting"),...t.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...t.outputValues.get("--output-include")===void 0?{}:{outputInclude:t.outputValues.get("--output-include")},...t.outputValues.get("--output-limit")===void 0?{}:{outputLimit:t.outputValues.get("--output-limit")},...t.outputValues.get("--output-budget")===void 0?{}:{outputBudget:t.outputValues.get("--output-budget")},...K.has(t.outputValues.get("--output-format"))?{outputFormat:t.outputValues.get("--output-format")}:{},...t.outputValues.get("--output-session")===void 0?{}:{outputSession:t.outputValues.get("--output-session")},...t.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:t.outputValues.get("--output-cursor")},...t.author===""?{authorMissingValue:!0}:t.author!==void 0?{author:t.author}:{}}}function S(e){const t=[];let o=0;for(;o<e.length;){const n=e[o];if(n==="--")break;if(x.has(n)||n==="--profile"||n==="--id-only"||n==="--full-changed-fields"||n==="--explain"){o+=1;continue}if(h.has(n)){o+=A(n,e[o+1])?2:1;continue}if(q(n)){o+=1;continue}t.push(n),o+=1}return t}function v(e){const t=S(e);if(t[0]?.trim().toLowerCase()==="help"){const i=[];for(let a=1;a<t.length;a+=1){const u=t[a];if(u.startsWith("-"))break;i.push(u.trim().toLowerCase())}return{requested:!0,commandPathTokens:i}}if(t.findIndex(i=>i==="--help"||i==="-h")<0)return{requested:!1,commandPathTokens:[]};const s=[];for(const i of t){if(i.startsWith("-"))break;s.push(i.trim().toLowerCase())}return{requested:!0,commandPathTokens:s}}function m(e){return R(e)}function H(e){return U(e)}function Z(e,t){return t.noPager?!0:process.stdout.isTTY===!0?!1:v(e).requested}function Ae(e){const t=["PAGER","MANPAGER","GIT_PAGER","LESS"],o=t.map(i=>process.env[i]),n=()=>{for(const[i,a]of t.entries()){const u=o[i];u===void 0?delete process.env[a]:process.env[a]=u}},s=Y(e);return Z(e,s)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),n}const J=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function Q(e){const t=m(e);if(t===void 0||e[t]!=="extension")return[...e];const o=e[t+1];if(!o||o.startsWith("-"))return[...e];if(!J.has(o))return[...e];if(e.includes("--help")||e.includes("-h"))return[...e];const n=`--${o}`;return e.includes(n)?[...e]:[...e.slice(0,t+1),n,...e.slice(t+2)]}const ee=new Set(["pm","pm-cli"]);function te(e,t){const o=m(e);if(o===void 0)return e;const n=e[o];return ee.has(n.trim().toLowerCase())?(t.push({from:n,to:[],reason:"executable_alias",confidence:"high"}),[...e.slice(0,o),...e.slice(o+1)]):e}function ne(e,t){let o=m(e);if(o!==void 0&&e[o]==="help"){const u=m(e.slice(o+1));o=u===void 0?void 0:o+1+u}if(o===void 0)return e;const n=e[o],s=C[n.trim().toLowerCase()];if(!s)return e;const i=s.split(" "),a=[...e.slice(0,o),...i,...e.slice(o+1)];return t.push({from:n,to:i,reason:"command_alias",confidence:"high"}),a}function g(e){return e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function I(e){return g(e).replace(/-/g,"")}function T(e,t,o){const n=e.get(t);if(n===void 0){e.set(t,o);return}n!==o&&e.set(t,null)}function _(e){const t=[],o=n=>{typeof n=="string"&&n.startsWith("--")&&t.push(n)};o(e.flag);for(const n of e.aliases??[])o(n);return t}function L(e,t){const o=t??b(e),n=new Map,s=new Map,i=new Map,a=new Set;for(const u of o){const r=_(u);if(r.length===0)continue;const c=`--${g(r[0])}`;for(const f of r)T(n,g(f),c),T(s,I(f),c);const l=I(c);i.has(c)||i.set(c,l),u.list===!0&&a.add(c)}return{canonicalByNormalized:n,canonicalByCompact:s,canonicalComparables:[...i.entries()].map(([u,r])=>({canonicalFlag:u,comparable:r})),listCanonicalFlags:a}}function k(e,t){const o=g(e),n=t.canonicalByNormalized.get(o);if(typeof n=="string")return{flag:n,reason:"flag_alias",confidence:"high"};const s=o.replace(/-/g,""),i=t.canonicalByCompact.get(s);if(typeof i=="string")return{flag:i,reason:"flag_alias",confidence:"high"};const a=s.length>=8?2:1;let u=Number.POSITIVE_INFINITY,r,c=!1;for(const l of t.canonicalComparables){const f=G(s,l.comparable,a);if(f!==null){if(f<u){u=f,r=l.canonicalFlag,c=!1;continue}f===u&&r!==l.canonicalFlag&&(c=!0)}}return!r||c||!Number.isFinite(u)||u<=0?null:{flag:r,reason:"flag_typo",confidence:u>=2?"medium":"high"}}function Se(e){const t=[`${e}s`];return e.endsWith("y")&&e.length>1&&t.push(`${e.slice(0,-1)}ies`),t}function oe(e,t=!1){if(t||e.includes("://"))return null;const o=e.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!o)return null;const n=o[1],s=o[3];return s.length===0||o[2]===":"&&/\s/u.test(e)?null:{key:n,value:s}}function V(e,t,o=!1){if(o||!e.startsWith("--"))return{tokens:[e]};const n=e.indexOf("="),s=n>=0?e.slice(0,n):e,i=n>=0?e.slice(n+1):void 0,a=k(s,t);if(!a)return{tokens:[e]};const u=i===void 0?a.flag:`${a.flag}=${i}`;return u===e?{tokens:[e]}:{tokens:[u],event:{from:e,to:[u],reason:a.reason,confidence:a.confidence}}}function E(e){const t=new Set;let o=!1;for(let n=0;n<e.length;n+=1){if(o){t.add(n),o=!1;continue}const s=e[n];o=s==="--path"||s==="--pm-path"}return t}function se(e){if(!e.startsWith("--"))return null;const t=e.indexOf("=");return t<0?{flag:e}:{flag:e.slice(0,t),inlineValue:e.slice(t+1)}}function ie(e,t,o){o.push(e[t]);const n=e[t+1];return typeof n=="string"&&n!=="--"?(o.push(n),t+2):t+1}function ae(e,t,o,n){if(o.inlineValue!==void 0)return{originalTokens:[e[t]],value:o.inlineValue,consumed:1};const s=[];let i=t+1;for(;i<e.length&&e[i]!=="--"&&!e[i].startsWith("-")&&(s.length===0||n.has(o.flag));)s.push(e[i]),i+=1;const a=s.length===0?1:1+s.length;return{originalTokens:e.slice(t,t+a),value:s.length===0?void 0:s.join(","),consumed:a}}function ue(e,t,o,n){const s=e.get(o);if(s){s.values.push(n.value),s.occurrences+=1;return}e.set(o,{outputIndex:t.length,originalTokens:n.originalTokens,values:[n.value],occurrences:1}),t.push(null)}function re(e,t){const o=[],n=[];for(const[s,i]of e){if(!(i.occurrences>=2||t.has(s)&&i.originalTokens.length>2)){n.push({outputIndex:i.outputIndex,tokens:i.originalTokens});continue}const u=`${s}=${i.values.join(",")}`;n.push({outputIndex:i.outputIndex,tokens:[u]}),o.push({from:`${s} (x${i.occurrences})`,to:[u],reason:"list_merge",confidence:"high"})}return{events:o,splices:n}}function ce(e,t){t.sort((o,n)=>n.outputIndex-o.outputIndex);for(const o of t)e.splice(o.outputIndex,1,...o.tokens)}function le(e,t,o=new Set,n=new Set){if(t.size===0)return{argv:[...e],events:[]};const s=[],i=new Map;let a=0;for(;a<e.length;){const c=e[a];if(c==="--"){s.push(...e.slice(a));break}if(o.has(c)){a=ie(e,a,s);continue}const l=se(c);if(!l||!t.has(l.flag)){s.push(c),a+=1;continue}const f=ae(e,a,l,n);if(f.value===void 0){s.push(c),a+=f.consumed;continue}ue(i,s,l.flag,{originalTokens:f.originalTokens,value:f.value}),a+=f.consumed}const{events:u,splices:r}=re(i,n);return ce(s,r),{argv:s,events:u}}const F=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function fe(e,t){if(e!=="test"||t.length<2)return!1;const o=t[t.length-1],n=t[t.length-2],s=F.get(n);return s!==void 0&&s.has(o)}function pe(e,t,o){if(t!=="test")return e;const n=[];let s=0;for(;s<e.length;){const i=e[s];if(i==="--")return n.push(...e.slice(s)),n;const a=F.get(i),u=a?e[s+1]:void 0;if(!a||typeof u!="string"||!a.has(u)){n.push(i),s+=1;continue}let r=s+2;for(;r<e.length&&!e[r].startsWith("-");)r+=1;if(r-(s+2)!==1){n.push(i),s+=1;continue}const c=e[s+2],l=`${u}=${c}`;n.push(i,l),o.push({from:`${i} ${u} ${c}`,to:[i,l],reason:"bare_key_value",confidence:"high"}),s+=3}return n}function de(e,t,o,n){const s=[],i=E(e);for(let a=0;a<e.length;a+=1){const u=e[a];if(u==="--"){s.push(...e.slice(a));break}const r=i.has(a),c=s[s.length-1];if(u.startsWith("--")){const d=V(u,t,r);s.push(...d.tokens),d.event&&n.push(d.event);continue}const l=oe(u,r);if(!l||typeof c=="string"&&c.startsWith("-")&&!c.includes("=")||["search","comments","notes","learnings"].includes(o)||fe(o,s)){s.push(u);continue}const f=k(l.key,t);if(!f){s.push(u);continue}const p=l.value.startsWith("-")?[`${f.flag}=${l.value}`]:[f.flag,l.value];s.push(...p),n.push({from:u,to:p,reason:"bare_key_value",confidence:f.confidence})}return s}function he(e){for(let t=0;t<e.length;t+=1){const o=e[t];if(o==="--")break;if(o==="--verify"){const n=e[t+1];if(n===void 0||n==="--")throw new w("history attest --verify requires a bundle file.",y.USAGE);e.splice(t,2,`--verify=${n}`)}else(h.has(o)||o==="--output"||o==="--hash-algorithm")&&(t+=1)}}function me(e,t){if(!e.some(n=>n==="--help"||n==="-h"))return;const o=new Set(b(t).flatMap(n=>[n.flag,...n.aliases??[],...n.short===void 0?[]:[n.short]]));for(let n=0;n<e.length;n+=1){const s=e[n];if(s==="--")break;s!=="--help"&&s!=="-h"||o.has(e[n-1])&&!x.has(e[n-1])&&(e[n-1]=s)}}function Ie(e){const t=[],o=te(e,t),n=Q(o);(n.length!==o.length||n.some((d,P)=>d!==o[P]))&&t.push({from:o.join(" "),to:[...n],reason:"legacy_extension_action",confidence:"high"});const s=ne(n,t),i=W(s);if(i.conflict)throw new w("Provide the item id either positionally or with --id, not both.",y.USAGE);i.changed&&t.push({from:`--id ${i.itemId}`,to:[i.itemId],reason:"item_id_alias",confidence:"high"});const a=H(i.argv),u=N(i.argv),r=z(u??a??""),c=L(u??a),l=de(i.argv,c,r,t),f=pe(l,r,t),p=le(f,c.listCanonicalFlags,h,a==="create"?new Set(["--tags"]):new Set);for(const d of p.events)t.push(d);return me(p.argv,u??a),u==="history attest"&&he(p.argv),{argv:p.argv,commandName:a,trace:t}}function N(e){const t=S(e),o=t[0]?.trim().toLowerCase(),n=t[1]?.trim().toLowerCase(),s=M(t);return s?s.canonical:(o==="extension"||o==="package"||o==="packages")&&typeof n=="string"&&n.length>0&&!n.startsWith("-")?`${o} ${n}`:o}function _e(e){for(let t=0;t<e.length;t+=1){const o=e[t];if(o==="--")break;if(o==="--type"){const n=e[t+1];if(typeof n=="string"&&n.trim().length>0)return n.trim();continue}if(o.startsWith("--type=")){const n=o.slice(7).trim();if(n.length>0)return n}}}const Le={buildFlagLookup:L,collectBootstrapPathValueIndices:E,collectLongFlagCandidates:_,markUnambiguousFlag:T,normalizeLongOptionToken:V,resolveCanonicalFlag:k};export{C as EXECUTABLE_COMMAND_ALIASES,B as PM_COMMAND_ALIAS_CONTRACTS,Le as _testOnly,Ae as applyBootstrapPagerPolicy,le as coalesceRepeatedListFlags,m as findBootstrapCommandTokenIndex,Se as listAliasPluralKeys,pe as mergeLinkedTestTwoTokenEntries,Ie as normalizeBootstrapInvocation,Q as normalizeLegacyExtensionActionSyntax,H as parseBootstrapCommandName,Y as parseBootstrapGlobalOptions,v as parseBootstrapHelpRequest,_e as parseBootstrapTypeValue,O as renderPmCommandAliasMigrationHint,$ as resolvePmCommandAlias,S as stripGlobalBootstrapTokens};
2
2
  //# sourceMappingURL=cli-bootstrap.js.map