@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]="54fb9d4c-c1aa-53dc-bcbe-4b0e3ebf87ba")}catch{}})();import crypto from"node:crypto";import{ITEM_MUTATION_FACET_OPTION_MAPPINGS}from"./lifecycle/mutation-facet-contracts.js";import{normalizeItemId,normalizePrefix}from"../core/item/id.js";import{preserveMutationStdinTokenFields,preserveMutationStdinTokenLiterals}from"../core/item/parse.js";import{preserveLiteralMutationInputFields}from"../core/item/literal-mutation-input.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{levenshteinDistanceWithinLimit}from"../core/shared/levenshtein.js";import{describeUnknownError}from"./error-runtime.js";import{CLOSE_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS}from"./cli-contracts/flag-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"./cli-contracts/commander-mutation-options.js";import{runtimeFieldOptionTarget}from"../core/schema/runtime-schema.js";import{CORE_ITEM_FIELD_KEYS as ITEM_FIELD_KEYS,resolveCoreUpsertMetadataKey}from"./lifecycle/core-item-fields.js";import{DEFERRABLE_ITEM_FIELDS}from"../core/item/deferred-fields.js";import{parseCreateUnsetTargets}from"./lifecycle/shared-unset-fields.js";import{readRuntimeFieldOptionValue}from"../core/schema/runtime-field-values.js";import{assertMutationOptionValueTypes}from"./lifecycle/mutation-option-validation.js";const MUTATION_ROW_KEYS=["op","id","reason","options","unique","match"],REFERENCED_MUTATION_ROW_KEYS=[...MUTATION_ROW_KEYS,"ref"],DOCUMENT_MUTATION_ROW_KEYS=[...REFERENCED_MUTATION_ROW_KEYS,"item"],DERIVED_TRANSACTION_ID_PREFIX="mutate-",SYNTHESIZED_REFERENCE_PREFIX="row-",MUTATION_DOCUMENT_KEYS=["schema_version","mutations"],MUTATION_REFERENCE_SOURCE="[a-z][a-z0-9._-]{0,63}",MUTATION_REFERENCE_PATTERN=new RegExp(`^${MUTATION_REFERENCE_SOURCE}$`,"u"),MUTATION_DEPENDENCY_REFERENCE_PATTERN=new RegExp(`(^|,)id=@(${MUTATION_REFERENCE_SOURCE})(?=,|$)`,"gu"),flagToOptionKey=flag=>flag.slice(2).replaceAll(/-([a-z])/gu,(_match,letter)=>letter.toUpperCase()),ITEM_ENVELOPE_KEYS=["item","item_hash","linked","schedule","claim_state","children","omission_receipt","row_contract","context_intent"],READ_ONLY_ITEM_KEYS=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count","pm_format_version","claim_principal","test_runs","deferred_fields"]),UPDATE_READ_ONLY_ITEM_KEYS=new Set([...READ_ONLY_ITEM_KEYS,"completed_at","id"]),MUTATION_OPTION_KEYS={create:CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS.map(contract=>contract.target),update:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS.map(contract=>contract.target),close:CLOSE_FLAG_CONTRACTS.map(contract=>flagToOptionKey(contract.flag)).filter(key=>key!=="reason"),release:RELEASE_FLAG_CONTRACTS.map(contract=>flagToOptionKey(contract.flag))};function deriveMutationTransactionId(input){const digest=crypto.createHash("sha256").update(input).digest("hex");return`${DERIVED_TRANSACTION_ID_PREFIX}${digest.slice(0,24)}`}function parseAtomicMutationControls(value){const controls={},compensation=value.createCompensation;if(compensation!==void 0){if(compensation!=="close"&&compensation!=="delete")throw new PmCliError("createCompensation must be close or delete.",EXIT_CODE.USAGE);controls.createCompensation=compensation}for(const key of["lockTtlSeconds","lockWaitMs"]){const raw=value[key];if(raw===void 0)continue;const parsed=typeof raw=="number"||typeof raw=="string"&&raw.trim().length>0?Number(raw):Number.NaN;if(!Number.isSafeInteger(parsed)||parsed<=0)throw new PmCliError(`${key} must be a positive safe integer.`,EXIT_CODE.USAGE);controls[key]=parsed}return controls}function isPlainObject(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function nearestKey(key,candidates){const limit=Math.max(1,Math.min(3,Math.floor(key.length/4)+1));let best;for(const candidate of candidates){const distance=levenshteinDistanceWithinLimit(key,candidate,limit);distance!==null&&(best===void 0||distance<best.distance)&&(best={key:candidate,distance})}return best?.key}function unknownKeyError(scope,key,candidates){const suggestion=nearestKey(key,candidates);return new PmCliError(suggestion===void 0?`${scope} does not recognize key "${key}". Allowed keys: ${candidates.join(", ")}.`:`${scope} does not recognize key "${key}". Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"stdin_json_unknown_key",required:`Use documented ${scope} keys only.`,why:"Strict structured input prevents silent typos from creating incomplete or unintended mutations.",nextSteps:[suggestion===void 0?`Remove or correct "${key}".`:`Replace "${key}" with "${suggestion}".`]})}function parseJsonValue(input,label){try{return JSON.parse(input)}catch(error){const detail=error instanceof Error?error.message:String(error);throw new PmCliError(`${label} must be valid JSON: ${detail}`,EXIT_CODE.USAGE,{code:"stdin_json_invalid",required:`Pipe one valid JSON ${label.toLowerCase()} into stdin.`,why:"Structured mutation input must parse deterministically before any tracker write begins."})}}function validateMutationObject(value,index){if(!isPlainObject(value))throw new PmCliError(`Mutation ${index+1} must be an object.`,EXIT_CODE.USAGE);for(const key of Object.keys(value))if(!MUTATION_ROW_KEYS.includes(key))throw unknownKeyError(`mutation ${index+1}`,key,MUTATION_ROW_KEYS);return value}function validateMutationOptions(options,op,index,runtimeFields){if(options===void 0)return;if(!isPlainObject(options))throw new PmCliError(`Mutation ${index+1} options must be an object.`,EXIT_CODE.USAGE);const allowed=[...MUTATION_OPTION_KEYS[op],...runtimeFieldOptionKeys(op,runtimeFields)];for(const key of Object.keys(options))if(!allowed.includes(key))throw unknownKeyError(`mutation ${index+1} ${op} options`,key,allowed);return assertMutationOptionValueTypes(options,op,index),options}function validateMutationKeyGuard(value,op,index,field){if(value===void 0)return;const allowedOp=field==="unique"?"create":"update";if(op!==allowedOp)throw new PmCliError(`Mutation ${index+1} ${field} is only valid for ${allowedOp} operations.`,EXIT_CODE.USAGE);const key=isPlainObject(value)&&typeof value.key=="string"?value.key.trim():"";if(!isPlainObject(value)||key.length===0||value.value===void 0||value.value===null)throw new PmCliError(`Mutation ${index+1} ${field} must be an object with a non-empty key and a value.`,EXIT_CODE.USAGE);return{key,value:value.value}}function validateMutationRow(value,index,runtimeFields){const mutation=validateMutationObject(value,index),{op,id,reason}=mutation;if(op!=="create"&&op!=="update"&&op!=="close"&&op!=="release")throw new PmCliError(`Mutation ${index+1} op must be create, update, close, or release.`,EXIT_CODE.USAGE);const options=validateMutationOptions(mutation.options,op,index,runtimeFields),unique=validateMutationKeyGuard(mutation.unique,op,index,"unique"),match=validateMutationKeyGuard(mutation.match,op,index,"match");if(typeof id!="string"||id.trim().length===0)throw new PmCliError(`Mutation ${index+1} requires a non-empty id.`,EXIT_CODE.USAGE);const normalizedId=id.trim();if(op==="close"){if(typeof reason!="string"||reason.trim().length===0)throw new PmCliError(`Mutation ${index+1} close requires a non-empty reason.`,EXIT_CODE.USAGE);return{op,id:normalizedId,reason:reason.trim(),...options===void 0?{}:{options}}}if(op==="release")return{op,id:normalizedId,...options===void 0?{}:{options}};if(!isPlainObject(options))throw new PmCliError(`Mutation ${index+1} ${op} requires an options object.`,EXIT_CODE.USAGE);return{op,id:normalizedId,options,...unique===void 0?{}:{unique},...match===void 0?{}:{match}}}function parseItemMutationBatch(input,parseOptions={}){const parsed=parseJsonValue(input,"Mutation batch"),rows=Array.isArray(parsed)?parsed:isPlainObject(parsed)&&Array.isArray(parsed.mutations)?parsed.mutations:void 0;if(rows===void 0||rows.length===0)throw new PmCliError("Mutation batch must be a non-empty JSON array or an object with a non-empty mutations array.",EXIT_CODE.USAGE);const runtimeFields=parseOptions.runtimeFields??[];return rows.map((row,index)=>{const mutation=validateMutationRow(row,index,runtimeFields);return mutation.options!==void 0&&preserveMutationStdinTokenLiterals(mutation.options),mutation})}function deriveReferencedItemId(transactionId,reference,idPrefix){const digest=crypto.createHash("sha256").update(transactionId).update("\0").update(reference).digest("hex"),token=BigInt(`0x${digest.slice(0,16)}`).toString(36).padStart(13,"0").slice(-12);return`${normalizePrefix(idPrefix)}${token}`}function replaceExactMutationReference(value,references){if(typeof value!="string"||!value.startsWith("@"))return value;const reference=value.slice(1),resolved=references[reference];if(resolved===void 0)throw new PmCliError(`Unknown mutation reference "${value}".`,EXIT_CODE.USAGE);return resolved}function replaceDependencyReference(value,references){if(typeof value!="string")return value;const resolvedValue=value.replace(MUTATION_DEPENDENCY_REFERENCE_PATTERN,(_match,prefix,reference)=>{const resolved=references[reference];if(resolved===void 0)throw new PmCliError(`Unknown mutation reference "@${reference}".`,EXIT_CODE.USAGE);return`${prefix}id=${resolved}`});if(/(^|,)id=@/u.test(resolvedValue))throw new PmCliError(`Malformed mutation reference in dependency "${value}".`,EXIT_CODE.USAGE);return resolvedValue}function referencedAliases(value){return typeof value!="string"?[]:value.startsWith("@")?[value.slice(1)]:[...value.matchAll(MUTATION_DEPENDENCY_REFERENCE_PATTERN)].map(match=>match[1]).filter(reference=>reference!==void 0)}function assertAcyclicCreateReferences(rows,inputReferences){const graph=new Map;for(const[index,row]of rows.entries()){const reference=inputReferences[index];if(reference===void 0)continue;const mutationOptions=isPlainObject(row.options)?row.options:{},dependencies=Array.isArray(mutationOptions.dep)?mutationOptions.dep:mutationOptions.dep===void 0?[]:[mutationOptions.dep];graph.set(reference,[mutationOptions.parent,mutationOptions.blockedBy,...dependencies].flatMap(referencedAliases))}const visiting=new Set,visited=new Set,visit=reference=>{if(visiting.has(reference))throw new PmCliError(`Mutation reference cycle includes "@${reference}".`,EXIT_CODE.USAGE);if(!visited.has(reference)){visiting.add(reference);for(const dependency of graph.get(reference))graph.has(dependency)&&visit(dependency);visiting.delete(reference),visited.add(reference)}};for(const reference of graph.keys())visit(reference)}function parseJsonLinesRows(input){const candidates=input.split(/\r?\n/u).map((line,index)=>({line:line.trim(),number:index+1})).filter(entry=>entry.line.length>0);if(candidates.length<2)return null;const parsed=candidates.map(entry=>{try{return{...entry,ok:!0,value:JSON.parse(entry.line)}}catch(error){return{...entry,ok:!1,error}}}),first=parsed[0];if(!first.ok&&(first.line.startsWith("[")||first.line==="{"||parsed.at(-1).line==="}")||!parsed.some(entry=>entry.ok&&isPlainObject(entry.value)))return null;const rows=[];for(const entry of parsed){if(!entry.ok)throw new PmCliError(`Mutation document line ${entry.number} must be one valid JSON object: ${describeUnknownError(entry.error)}`,EXIT_CODE.USAGE,{code:"stdin_json_invalid",required:"Provide one JSON object per line (JSON Lines), a JSON array, or a {schema_version, mutations} document.",why:"Structured mutation input must parse deterministically before any tracker write begins."});if(!isPlainObject(entry.value))throw new PmCliError(`Mutation document line ${entry.number} must be a JSON object.`,EXIT_CODE.USAGE);rows.push(entry.value)}return rows}function isMutationEnvelope(value){return Object.hasOwn(value,"mutations")||Object.hasOwn(value,"schema_version")}function parseMutationDocumentEnvelope(input){let parsed;try{parsed=parseJsonValue(input,"Mutation document")}catch(error){const rows=parseJsonLinesRows(input);if(rows===null)throw error;return{schema_version:1,mutations:rows}}return Array.isArray(parsed)?{schema_version:1,mutations:parsed}:isPlainObject(parsed)&&!isMutationEnvelope(parsed)?{schema_version:1,mutations:[parsed]}:parsed}function normalizeDocumentRow(row,index){const normalized=Object.hasOwn(row,"op")?validateOperationRow(row,index):normalizeCreateDocumentRow(row,index);if(normalized.op==="create"&&normalized.id===void 0&&isPlainObject(normalized.item)&&normalized.item.id!==void 0){if(typeof normalized.item.id!="string")throw new PmCliError(`Mutation ${index+1} item id must be a string.`,EXIT_CODE.USAGE);normalized.id=normalized.item.id}return normalized}function validateOperationRow(row,index){for(const key of Object.keys(row))if(!DOCUMENT_MUTATION_ROW_KEYS.includes(key))throw unknownKeyError(`mutation ${index+1}`,key,DOCUMENT_MUTATION_ROW_KEYS);if(row.item!==void 0&&row.op!=="create")throw new PmCliError(`Mutation ${index+1} item documents are only valid for create operations.`,EXIT_CODE.USAGE);if(row.item!==void 0&&row.options!==void 0)throw new PmCliError(`Mutation ${index+1} must declare either item or options, not both.`,EXIT_CODE.USAGE);return{...row}}function normalizeCreateDocumentRow(row,index){const{ref,id,item,...fields}=row,document=item!==void 0?item:fields;if(item!==void 0&&Object.keys(fields).length>0)throw new PmCliError(`Mutation ${index+1} must not mix item document keys with top-level fields.`,EXIT_CODE.USAGE);if(!isPlainObject(document))throw new PmCliError(`Mutation ${index+1} item document must be an object.`,EXIT_CODE.USAGE);return{op:"create",...ref===void 0?{}:{ref},...id===void 0?{}:{id},item:document}}function parseMutationDocumentRows(input){const envelope=parseMutationDocumentEnvelope(input);if(!isPlainObject(envelope))throw new PmCliError("Mutation document must be a JSON array or object.",EXIT_CODE.USAGE);for(const key of Object.keys(envelope))if(!MUTATION_DOCUMENT_KEYS.includes(key))throw unknownKeyError("mutation document",key,MUTATION_DOCUMENT_KEYS);if(envelope.schema_version!==void 0&&envelope.schema_version!==1)throw new PmCliError("Mutation document schema_version must be 1.",EXIT_CODE.USAGE);if(!Array.isArray(envelope.mutations)||envelope.mutations.length===0)throw new PmCliError("Mutation document requires a non-empty mutations array.",EXIT_CODE.USAGE);return envelope.mutations.map((row,index)=>{if(!isPlainObject(row))throw new PmCliError(`Mutation ${index+1} must be an object.`,EXIT_CODE.USAGE);return normalizeDocumentRow(row,index)})}function excludeOwnCreateIds(upsert,rows,options){const ownIds=new Set(Object.values(collectMutationReferences(rows,options,Object.create(null))));for(const row of rows)row.op==="create"&&typeof row.id=="string"&&row.id.trim().length>0&&ownIds.add(normalizeItemId(row.id,options.idPrefix));return{...upsert,existing:upsert.existing.filter(candidate=>!ownIds.has(candidate.id))}}function synthesizeMissingReferences(rows){const declared=new Set(rows.map(row=>row.ref).filter(ref=>typeof ref=="string"));for(const[index,row]of rows.entries()){if(row.op!=="create"||row.ref!==void 0||typeof row.id=="string"&&row.id.trim().length>0)continue;const synthesized=`${SYNTHESIZED_REFERENCE_PREFIX}${index+1}`;if(declared.has(synthesized))throw new PmCliError(`Mutation ${index+1} receives the synthesized ref "${synthesized}", but another row declares that ref. Rename it or give mutation ${index+1} its own ref; ${SYNTHESIZED_REFERENCE_PREFIX}<n> aliases are reserved for rows without one.`,EXIT_CODE.USAGE);row.ref=synthesized}}function itemDocumentToBatchOptions(item,mode,runtimeFields){const converted=itemDocumentToMutationOptions(JSON.stringify(item),mode,{},runtimeFields);return delete converted.stdinJson,delete converted.documentAnnotationSnapshot,converted}function runtimeFieldOptionKeys(op,runtimeFields){return op!=="create"&&op!=="update"?[]:runtimeFields.filter(definition=>definition.commands.includes(op)).map(definition=>runtimeFieldOptionTarget(definition))}function convertItemDocumentRows(rows,runtimeFields){for(const row of rows)isPlainObject(row.item)&&(row.options=itemDocumentToBatchOptions(row.item,"create",runtimeFields),delete row.item)}function itemDocumentMetadataKey(key,runtimeFields){return runtimeFields.some(field=>field.metadata_key===key)?key:resolveCoreUpsertMetadataKey(key)}function readUpsertKeyValue(row,key,runtimeFields){const camel=key.replaceAll(/_([a-z])/gu,(_match,letter)=>letter.toUpperCase());if(isPlainObject(row.item)){if(row.item[key]!==void 0)return row.item[key];if(itemDocumentMetadataKey(camel,runtimeFields)===key&&row.item[camel]!==void 0)return row.item[camel]}const options=isPlainObject(row.options)?row.options:{},declared=runtimeFields.find(field=>field.metadata_key===key);return declared!==void 0&&options[runtimeFieldOptionTarget(declared)]!==void 0?options[runtimeFieldOptionTarget(declared)]:options[key]!==void 0?options[key]:options[camel]!==void 0?options[camel]:(Array.isArray(options.field)?options.field:[]).map(String).find(entry=>entry.startsWith(`${key}=`))?.slice(key.length+1)}function compareCodeUnits(left,right){return left<right?-1:+(left!==right)}function canonicalizeUpsertValue(value){return Array.isArray(value)?value.map(canonicalizeUpsertValue):isPlainObject(value)?Object.fromEntries(Object.entries(value).sort(([left],[right])=>compareCodeUnits(left,right)).map(([key,nested])=>[key,canonicalizeUpsertValue(nested)])):value}function stableUpsertValue(value){return typeof value=="string"?value.trim():JSON.stringify(canonicalizeUpsertValue(value))}function applyKeyedUpsert(rows,upsert,idPrefix,runtimeFields,references){const key=upsert.key.trim();if(key.length===0)throw new PmCliError("Upsert key must be a non-empty field name.",EXIT_CODE.USAGE);const existingByValue=indexUpsertCandidates(upsert.existing),seen=new Map,upserted=new Set;for(const[index,row]of rows.entries()){if(row.op!=="create")continue;const stable=readStableUpsertKey(row,key,index,seen,runtimeFields),match=resolveUpsertMatch(existingByValue.get(stable)??[],key,stable);if(match===void 0){row.unique={key,value:readUpsertKeyValue(row,key,runtimeFields)};continue}const id=normalizeItemId(match,idPrefix);typeof row.ref=="string"&&(references[row.ref]=id),convertRowToUpsertUpdate(row,id,runtimeFields,{key,value:readUpsertKeyValue(row,key,runtimeFields)}),upserted.add(index)}return upserted}function indexUpsertCandidates(existing){const existingByValue=new Map;for(const candidate of existing){if(candidate.value===void 0||candidate.value===null)continue;const stable=stableUpsertValue(candidate.value);existingByValue.set(stable,[...existingByValue.get(stable)??[],candidate.id])}return existingByValue}function readStableUpsertKey(row,key,index,seen,runtimeFields){const value=readUpsertKeyValue(row,key,runtimeFields);if(value==null||value==="")throw new PmCliError(`Mutation ${index+1} is missing the upsert key "${key}".`,EXIT_CODE.USAGE,{code:"upsert_key_missing",required:`Every create record must carry a non-empty "${key}" value when --upsert-key ${key} is set.`,why:"Keyed upsert identifies existing items by that field; a record without it cannot be matched or safely created."});const stable=stableUpsertValue(value),previous=seen.get(stable);if(previous!==void 0)throw new PmCliError(`Mutations ${previous+1} and ${index+1} share the upsert key value ${JSON.stringify(stable)} for "${key}".`,EXIT_CODE.USAGE,{code:"upsert_key_duplicate",required:"Each record must carry a distinct upsert key value within one batch.",why:"Two records with the same key would race for the same existing item."});return seen.set(stable,index),stable}function resolveUpsertMatch(matches,key,stable){if(matches.length>1)throw new PmCliError(`Upsert key "${key}" value ${JSON.stringify(stable)} matches ${matches.length} existing items: ${matches.join(", ")}.`,EXIT_CODE.CONFLICT,{code:"upsert_key_ambiguous",required:"Resolve the duplicate existing items or choose a key that is unique per item.",why:"An ambiguous key cannot select one item to update without guessing."});return matches[0]}function convertRowToUpsertUpdate(row,id,runtimeFields,match){const updateKeys=new Set([...MUTATION_OPTION_KEYS.update,...runtimeFieldOptionKeys("update",runtimeFields)]),options=isPlainObject(row.item)?itemDocumentToBatchOptions(row.item,"update",runtimeFields):Object.fromEntries(Object.entries(row.options).filter(([optionKey])=>updateKeys.has(optionKey)));delete row.item,delete row.ref,row.op="update",row.id=id,row.options=options,row.match=match}function collectMutationReferences(rows,options,references){for(const[index,row]of rows.entries())if(row.ref!==void 0){if(row.op!=="create")throw new PmCliError(`Mutation ${index+1} ref is only valid for create operations.`,EXIT_CODE.USAGE);if(typeof row.ref!="string"||!MUTATION_REFERENCE_PATTERN.test(row.ref))throw new PmCliError(`Mutation ${index+1} ref must match ${MUTATION_REFERENCE_PATTERN.source}.`,EXIT_CODE.USAGE);if(references[row.ref]!==void 0)throw new PmCliError(`Duplicate mutation ref "${row.ref}".`,EXIT_CODE.USAGE);references[row.ref]=typeof row.id=="string"&&row.id.trim().length>0?normalizeItemId(row.id,options.idPrefix):deriveReferencedItemId(options.transactionId,row.ref,options.idPrefix)}return references}function resolveItemMutationDocument(input,options){const rows=parseMutationDocumentRows(input);synthesizeMissingReferences(rows);const inputReferences=rows.map(row=>typeof row.ref=="string"?row.ref:void 0),references=Object.create(null),upserted=options.upsert===void 0?new Set:applyKeyedUpsert(rows,excludeOwnCreateIds(options.upsert,rows,options),options.idPrefix,options.runtimeFields??[],references);convertItemDocumentRows(rows,options.runtimeFields??[]),collectMutationReferences(rows,options,references),assertAcyclicCreateReferences(rows,inputReferences);const resolvedRows=rows.map(row=>{const resolved={...row},reference=typeof resolved.ref=="string"?resolved.ref:void 0;if(delete resolved.ref,reference!==void 0?resolved.id=references[reference]:resolved.id=replaceExactMutationReference(resolved.id,references),isPlainObject(resolved.options)){const mutationOptions={...resolved.options};for(const key of["parent","blockedBy"])mutationOptions[key]!==void 0&&(mutationOptions[key]=replaceExactMutationReference(mutationOptions[key],references));Array.isArray(mutationOptions.dep)?mutationOptions.dep=mutationOptions.dep.map(entry=>replaceDependencyReference(entry,references)):mutationOptions.dep!==void 0&&(mutationOptions.dep=replaceDependencyReference(mutationOptions.dep,references)),resolved.options=mutationOptions}return resolved}),mutations=parseItemMutationBatch(JSON.stringify(resolvedRows),{runtimeFields:options.runtimeFields??[]}),createIds=mutations.filter(mutation=>mutation.op==="create").map(mutation=>mutation.id);if(new Set(createIds).size!==createIds.length)throw new PmCliError("Duplicate resolved create id in mutation document.",EXIT_CODE.USAGE);const receiptRows=mutations.map((mutation,index)=>{const reference=inputReferences[index];return{index,...typeof reference=="string"?{ref:reference}:{},id:mutation.id,op:mutation.op,...upserted.has(index)?{upserted:!0}:{}}});return{schema_version:1,mutations,references,rows:receiptRows}}function serializePairs(value,keys){return keys.filter(key=>value[key]!==void 0&&value[key]!==null).map(key=>{const rendered=String(value[key]);return`${key}=${/[",\n\r\\]/u.test(rendered)?JSON.stringify(rendered):rendered}`}).join(",")}function serializeObjectArray(value,keys,label){if(value!==void 0){if(!Array.isArray(value)||!value.every(isPlainObject))throw new PmCliError(`${label} must be an array of objects.`,EXIT_CODE.USAGE);return value.map(entry=>serializePairs(entry,keys))}}function scalarItemOption(key,value){return key==="tags"&&Array.isArray(value)&&value.every(entry=>typeof entry=="string")?JSON.stringify(value):typeof value=="number"||typeof value=="boolean"?String(value):value}function appendFacetOptions(target,source,skipPersistedAnnotations=!1){for(const[sourceKey,targetKey,keys]of ITEM_MUTATION_FACET_OPTION_MAPPINGS){const sourceValue=source[sourceKey],serialized=serializeObjectArray(skipPersistedAnnotations&&["comments","notes","learnings"].includes(sourceKey)&&Array.isArray(sourceValue)?sourceValue.filter(entry=>!isPlainObject(entry)||entry.created_at===void 0):sourceValue,keys,sourceKey);serialized!==void 0&&serialized.length>0&&(target[targetKey]=serialized)}}function validateItemDocumentKeys(parsed,envelope){for(const key of Object.keys(parsed)){if(envelope){if(!ITEM_ENVELOPE_KEYS.includes(key))throw unknownKeyError("item envelope",key,ITEM_ENVELOPE_KEYS);continue}if(!ITEM_FIELD_KEYS.has(key)&&nearestKey(key,[...ITEM_FIELD_KEYS])===void 0&&nearestKey(key,ITEM_ENVELOPE_KEYS)==="item")throw unknownKeyError("item envelope",key,ITEM_ENVELOPE_KEYS)}}function resolveItemDocument(parsed){const envelope=Object.hasOwn(parsed,"item");validateItemDocumentKeys(parsed,envelope);const item=envelope?parsed.item:parsed;if(!isPlainObject(item))throw new PmCliError("Item document item must be an object.",EXIT_CODE.USAGE);return{item,...envelope&&isPlainObject(parsed.linked)?{linked:parsed.linked}:{}}}function appendItemDocumentEntry(documentOptions,key,value,mode,runtimeFields,explicitOptions){if((mode==="update"?UPDATE_READ_ONLY_ITEM_KEYS:READ_ONLY_ITEM_KEYS).has(key))return;const definition=runtimeFields.find(field=>field.metadata_key===key&&field.commands.includes(mode));if(definition!==void 0){const explicitValue=readRuntimeFieldOptionValue(explicitOptions,definition);documentOptions[runtimeFieldOptionTarget(definition)]=explicitValue!==void 0?explicitValue:definition.type==="array"||definition.type==="object"?JSON.stringify(value):value;return}if(!ITEM_FIELD_KEYS.has(key)){if(nearestKey(key,[...ITEM_FIELD_KEYS])!==void 0)throw unknownKeyError("item document",key,[...ITEM_FIELD_KEYS]);const fields=Array.isArray(documentOptions.field)?documentOptions.field:[];fields.push(`${key}=${typeof value=="string"?value:JSON.stringify(value)}`),documentOptions.field=fields;return}["dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"].includes(key)||(documentOptions[key.replaceAll(/_([a-z])/gu,(_match,letter)=>letter.toUpperCase())]=scalarItemOption(key,value))}function createFieldRegistry(runtimeFields){return{command_to_fields:new Map([["create",runtimeFields.filter(definition=>definition.commands.includes("create"))]])}}function documentDeferralOptions(value,explicitKeys,explicitUnset,runtimeFields){const createFields=runtimeFields.filter(definition=>definition.commands.includes("create")),overridden=new Set([...DEFERRABLE_ITEM_FIELDS.filter(entry=>explicitKeys.has(entry.option)).map(entry=>entry.field),...createFields.filter(definition=>explicitKeys.has(runtimeFieldOptionTarget(definition))).map(definition=>definition.metadata_key),...parseCreateUnsetTargets(Array.isArray(explicitUnset)?explicitUnset.map(String):[],createFieldRegistry(createFields)).metadataKeys]),entries=(Array.isArray(value)?value:[]).filter(isPlainObject).filter(entry=>typeof entry.field=="string"&&!overridden.has(entry.field));if(entries.length===0)return{};const reasons=entries.map(entry=>typeof entry.reason=="string"?entry.reason.trim():""),defer=entries.map(entry=>entry.field);return explicitKeys.has("deferReason")?{defer}:reasons.every(reason=>reason.length>0)?{defer,deferReason:[...new Set(reasons)].join("; ")}:{defer}}function explicitDocumentOptionKeys(explicitOptions,mode,runtimeFields){const explicitKeys=new Set(Object.entries(explicitOptions).filter(([,value])=>value!==void 0).map(([key])=>key)),contracts=mode==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS;for(const{target,keys}of contracts)keys.some(key=>explicitKeys.has(key))&&explicitKeys.add(target);for(const definition of runtimeFields.filter(candidate=>candidate.commands.includes(mode)))readRuntimeFieldOptionValue(explicitOptions,definition)!==void 0&&explicitKeys.add(runtimeFieldOptionTarget(definition));return explicitKeys}function removeOverriddenDocumentOptions(documentOptions,mode,explicitKeys){const contracts=mode==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS;for(const{target}of contracts)target!=="field"&&explicitKeys.has(target)&&delete documentOptions[target]}function itemDocumentToMutationOptions(input,mode,explicitOptions={},runtimeFields=[]){const parsed=parseJsonValue(input,"Item document");if(!isPlainObject(parsed))throw new PmCliError("Item document must be a JSON object.",EXIT_CODE.USAGE);const{item,linked}=resolveItemDocument(parsed),documentOptions={};for(const[key,value]of Object.entries(item)){const metadataKey=itemDocumentMetadataKey(key,runtimeFields);metadataKey!==key&&Object.hasOwn(item,metadataKey)||appendItemDocumentEntry(documentOptions,metadataKey,value,mode,runtimeFields,explicitOptions)}appendFacetOptions(documentOptions,item,mode==="update"),linked!==void 0&&appendFacetOptions(documentOptions,linked);const explicitKeys=explicitDocumentOptionKeys(explicitOptions,mode,runtimeFields);if(removeOverriddenDocumentOptions(documentOptions,mode,explicitKeys),mode==="create"&&!explicitKeys.has("defer")&&Object.assign(documentOptions,documentDeferralOptions(item.deferred_fields,explicitKeys,explicitOptions.unset,runtimeFields)),mode==="update"){const annotations=Object.fromEntries(["comments","notes","learnings"].filter(key=>Object.hasOwn(item,key)&&!explicitKeys.has(key.slice(0,-1))).map(key=>[key,item[key].filter(entry=>isPlainObject(entry)&&entry.created_at!==void 0)]));Object.keys(annotations).length>0&&(documentOptions.documentAnnotationSnapshot=annotations)}const merged={...documentOptions,...Object.fromEntries(Object.entries(explicitOptions).filter(([,value])=>value!==void 0)),...Array.isArray(documentOptions.field)&&Array.isArray(explicitOptions.field)?{field:[...documentOptions.field,...explicitOptions.field]}:{},stdinJson:void 0},literalKeys=Object.keys(documentOptions).filter(key=>!explicitKeys.has(key));return preserveMutationStdinTokenFields(preserveLiteralMutationInputFields(merged,literalKeys),literalKeys)}function validateItemMutationRows(value){return parseItemMutationBatch(JSON.stringify(value))}export{deriveMutationTransactionId,itemDocumentToMutationOptions,parseAtomicMutationControls,parseItemMutationBatch,resolveItemMutationDocument,stableUpsertValue,validateItemMutationRows};
1
+ import R from"node:crypto";import{ITEM_MUTATION_FACET_OPTION_MAPPINGS as X}from"./lifecycle/mutation-facet-contracts.js";import{normalizeItemId as O,normalizePrefix as Z}from"../core/item/id.js";import{preserveMutationStdinTokenFields as Q,preserveMutationStdinTokenLiterals as ee}from"../core/item/parse.js";import{preserveLiteralMutationInputFields as te}from"../core/item/literal-mutation-input.js";import{EXIT_CODE as u}from"../core/shared/constants.js";import{PmCliError as f}from"../core/shared/errors.js";import{levenshteinDistanceWithinLimit as ne}from"../core/shared/levenshtein.js";import{describeUnknownError as ie}from"./error-runtime.js";import{CLOSE_FLAG_CONTRACTS as re,RELEASE_FLAG_CONTRACTS as oe}from"./cli-contracts/flag-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as b,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as M}from"./cli-contracts/commander-mutation-options.js";import{runtimeFieldOptionTarget as E}from"../core/schema/runtime-schema.js";import{CORE_ITEM_FIELD_KEYS as A,resolveCoreUpsertMetadataKey as se}from"./lifecycle/core-item-fields.js";import{DEFERRABLE_ITEM_FIELDS as ae}from"../core/item/deferred-fields.js";import{parseCreateUnsetTargets as ce}from"./lifecycle/shared-unset-fields.js";import{readRuntimeFieldOptionValue as I}from"../core/schema/runtime-field-values.js";import{assertMutationOptionValueTypes as ue}from"./lifecycle/mutation-option-validation.js";const $=["op","id","reason","options","unique","match"],fe=[...$,"ref"],j=[...fe,"item"],de="mutate-",v="row-",G=["schema_version","mutations"],C="[a-z][a-z0-9._-]{0,63}",k=new RegExp(`^${C}$`,"u"),D=new RegExp(`(^|,)id=@(${C})(?=,|$)`,"gu"),K=e=>e.slice(2).replaceAll(/-([a-z])/gu,(t,n)=>n.toUpperCase()),S=["item","item_hash","linked","schedule","claim_state","children","omission_receipt","row_contract","context_intent"],J=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count","pm_format_version","claim_principal","test_runs","deferred_fields"]),me=new Set([...J,"completed_at","id"]),P={create:b.map(e=>e.target),update:M.map(e=>e.target),close:re.map(e=>K(e.flag)).filter(e=>e!=="reason"),release:oe.map(e=>K(e.flag))};function ut(e){const t=R.createHash("sha256").update(e).digest("hex");return`${de}${t.slice(0,24)}`}function ft(e){const t={},n=e.createCompensation;if(n!==void 0){if(n!=="close"&&n!=="delete")throw new f("createCompensation must be close or delete.",u.USAGE);t.createCompensation=n}for(const i of["lockTtlSeconds","lockWaitMs"]){const r=e[i];if(r===void 0)continue;const o=typeof r=="number"||typeof r=="string"&&r.trim().length>0?Number(r):Number.NaN;if(!Number.isSafeInteger(o)||o<=0)throw new f(`${i} must be a positive safe integer.`,u.USAGE);t[i]=o}return t}function p(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function _(e,t){const n=Math.max(1,Math.min(3,Math.floor(e.length/4)+1));let i;for(const r of t){const o=ne(e,r,n);o!==null&&(i===void 0||o<i.distance)&&(i={key:r,distance:o})}return i?.key}function w(e,t,n){const i=_(t,n);return new f(i===void 0?`${e} does not recognize key "${t}". Allowed keys: ${n.join(", ")}.`:`${e} does not recognize key "${t}". Did you mean "${i}"?`,u.USAGE,{code:"stdin_json_unknown_key",required:`Use documented ${e} keys only.`,why:"Strict structured input prevents silent typos from creating incomplete or unintended mutations.",nextSteps:[i===void 0?`Remove or correct "${t}".`:`Replace "${t}" with "${i}".`]})}function U(e,t){try{return JSON.parse(e)}catch(n){const i=n instanceof Error?n.message:String(n);throw new f(`${t} must be valid JSON: ${i}`,u.USAGE,{code:"stdin_json_invalid",required:`Pipe one valid JSON ${t.toLowerCase()} into stdin.`,why:"Structured mutation input must parse deterministically before any tracker write begins."})}}function le(e,t){if(!p(e))throw new f(`Mutation ${t+1} must be an object.`,u.USAGE);for(const n of Object.keys(e))if(!$.includes(n))throw w(`mutation ${t+1}`,n,$);return e}function pe(e,t,n,i){if(e===void 0)return;if(!p(e))throw new f(`Mutation ${n+1} options must be an object.`,u.USAGE);const r=[...P[t],...V(t,i)];for(const o of Object.keys(e))if(!r.includes(o))throw w(`mutation ${n+1} ${t} options`,o,r);return ue(e,t,n),e}function z(e,t,n,i){if(e===void 0)return;const r=i==="unique"?"create":"update";if(t!==r)throw new f(`Mutation ${n+1} ${i} is only valid for ${r} operations.`,u.USAGE);const o=p(e)&&typeof e.key=="string"?e.key.trim():"";if(!p(e)||o.length===0||e.value===void 0||e.value===null)throw new f(`Mutation ${n+1} ${i} must be an object with a non-empty key and a value.`,u.USAGE);return{key:o,value:e.value}}function he(e,t,n){const i=le(e,t),{op:r,id:o,reason:s}=i;if(r!=="create"&&r!=="update"&&r!=="close"&&r!=="release")throw new f(`Mutation ${t+1} op must be create, update, close, or release.`,u.USAGE);const a=pe(i.options,r,t,n),d=z(i.unique,r,t,"unique"),c=z(i.match,r,t,"match");if(typeof o!="string"||o.trim().length===0)throw new f(`Mutation ${t+1} requires a non-empty id.`,u.USAGE);const m=o.trim();if(r==="close"){if(typeof s!="string"||s.trim().length===0)throw new f(`Mutation ${t+1} close requires a non-empty reason.`,u.USAGE);return{op:r,id:m,reason:s.trim(),...a===void 0?{}:{options:a}}}if(r==="release")return{op:r,id:m,...a===void 0?{}:{options:a}};if(!p(a))throw new f(`Mutation ${t+1} ${r} requires an options object.`,u.USAGE);return{op:r,id:m,options:a,...d===void 0?{}:{unique:d},...c===void 0?{}:{match:c}}}function F(e,t={}){const n=U(e,"Mutation batch"),i=Array.isArray(n)?n:p(n)&&Array.isArray(n.mutations)?n.mutations:void 0;if(i===void 0||i.length===0)throw new f("Mutation batch must be a non-empty JSON array or an object with a non-empty mutations array.",u.USAGE);const r=t.runtimeFields??[];return i.map((o,s)=>{const a=he(o,s,r);return a.options!==void 0&&ee(a.options),a})}function ye(e,t,n){const i=R.createHash("sha256").update(e).update("\0").update(t).digest("hex"),r=BigInt(`0x${i.slice(0,16)}`).toString(36).padStart(13,"0").slice(-12);return`${Z(n)}${r}`}function L(e,t){if(typeof e!="string"||!e.startsWith("@"))return e;const n=e.slice(1),i=t[n];if(i===void 0)throw new f(`Unknown mutation reference "${e}".`,u.USAGE);return i}function q(e,t){if(typeof e!="string")return e;const n=e.replace(D,(i,r,o)=>{const s=t[o];if(s===void 0)throw new f(`Unknown mutation reference "@${o}".`,u.USAGE);return`${r}id=${s}`});if(/(^|,)id=@/u.test(n))throw new f(`Malformed mutation reference in dependency "${e}".`,u.USAGE);return n}function we(e){return typeof e!="string"?[]:e.startsWith("@")?[e.slice(1)]:[...e.matchAll(D)].map(t=>t[1]).filter(t=>t!==void 0)}function Ee(e,t){const n=new Map;for(const[s,a]of e.entries()){const d=t[s];if(d===void 0)continue;const c=p(a.options)?a.options:{},m=Array.isArray(c.dep)?c.dep:c.dep===void 0?[]:[c.dep];n.set(d,[c.parent,c.blockedBy,...m].flatMap(we))}const i=new Set,r=new Set,o=s=>{if(i.has(s))throw new f(`Mutation reference cycle includes "@${s}".`,u.USAGE);if(!r.has(s)){i.add(s);for(const a of n.get(s))n.has(a)&&o(a);i.delete(s),r.add(s)}};for(const s of n.keys())o(s)}function ge(e){const n=e.split(/\r?\n/u).map((s,a)=>({line:s.trim(),number:a+1})).filter(s=>s.line.length>0);if(n.length<2)return null;const i=n.map(s=>{try{return{...s,ok:!0,value:JSON.parse(s.line)}}catch(a){return{...s,ok:!1,error:a}}}),r=i[0];if(!r.ok&&(r.line.startsWith("[")||r.line==="{"||i.at(-1).line==="}")||!i.some(s=>s.ok&&p(s.value)))return null;const o=[];for(const s of i){if(!s.ok)throw new f(`Mutation document line ${s.number} must be one valid JSON object: ${ie(s.error)}`,u.USAGE,{code:"stdin_json_invalid",required:"Provide one JSON object per line (JSON Lines), a JSON array, or a {schema_version, mutations} document.",why:"Structured mutation input must parse deterministically before any tracker write begins."});if(!p(s.value))throw new f(`Mutation document line ${s.number} must be a JSON object.`,u.USAGE);o.push(s.value)}return o}function Ae(e){return Object.hasOwn(e,"mutations")||Object.hasOwn(e,"schema_version")}function Se(e){let t;try{t=U(e,"Mutation document")}catch(n){const i=ge(e);if(i===null)throw n;return{schema_version:1,mutations:i}}return Array.isArray(t)?{schema_version:1,mutations:t}:p(t)&&!Ae(t)?{schema_version:1,mutations:[t]}:t}function _e(e,t){const n=Object.hasOwn(e,"op")?Oe(e,t):be(e,t);if(n.op==="create"&&n.id===void 0&&p(n.item)&&n.item.id!==void 0){if(typeof n.item.id!="string")throw new f(`Mutation ${t+1} item id must be a string.`,u.USAGE);n.id=n.item.id}return n}function Oe(e,t){for(const n of Object.keys(e))if(!j.includes(n))throw w(`mutation ${t+1}`,n,j);if(e.item!==void 0&&e.op!=="create")throw new f(`Mutation ${t+1} item documents are only valid for create operations.`,u.USAGE);if(e.item!==void 0&&e.options!==void 0)throw new f(`Mutation ${t+1} must declare either item or options, not both.`,u.USAGE);return{...e}}function be(e,t){const{ref:n,id:i,item:r,...o}=e,s=r!==void 0?r:o;if(r!==void 0&&Object.keys(o).length>0)throw new f(`Mutation ${t+1} must not mix item document keys with top-level fields.`,u.USAGE);if(!p(s))throw new f(`Mutation ${t+1} item document must be an object.`,u.USAGE);return{op:"create",...n===void 0?{}:{ref:n},...i===void 0?{}:{id:i},item:s}}function Me(e){const t=Se(e);if(!p(t))throw new f("Mutation document must be a JSON array or object.",u.USAGE);for(const n of Object.keys(t))if(!G.includes(n))throw w("mutation document",n,G);if(t.schema_version!==void 0&&t.schema_version!==1)throw new f("Mutation document schema_version must be 1.",u.USAGE);if(!Array.isArray(t.mutations)||t.mutations.length===0)throw new f("Mutation document requires a non-empty mutations array.",u.USAGE);return t.mutations.map((n,i)=>{if(!p(n))throw new f(`Mutation ${i+1} must be an object.`,u.USAGE);return _e(n,i)})}function $e(e,t,n){const i=new Set(Object.values(B(t,n,Object.create(null))));for(const r of t)r.op==="create"&&typeof r.id=="string"&&r.id.trim().length>0&&i.add(O(r.id,n.idPrefix));return{...e,existing:e.existing.filter(r=>!i.has(r.id))}}function Ue(e){const t=new Set(e.map(n=>n.ref).filter(n=>typeof n=="string"));for(const[n,i]of e.entries()){if(i.op!=="create"||i.ref!==void 0||typeof i.id=="string"&&i.id.trim().length>0)continue;const r=`${v}${n+1}`;if(t.has(r))throw new f(`Mutation ${n+1} receives the synthesized ref "${r}", but another row declares that ref. Rename it or give mutation ${n+1} its own ref; ${v}<n> aliases are reserved for rows without one.`,u.USAGE);i.ref=r}}function Y(e,t,n){const i=Ye(JSON.stringify(e),t,{},n);return delete i.stdinJson,delete i.documentAnnotationSnapshot,i}function V(e,t){return e!=="create"&&e!=="update"?[]:t.filter(n=>n.commands.includes(e)).map(n=>E(n))}function Ne(e,t){for(const n of e)p(n.item)&&(n.options=Y(n.item,"create",t),delete n.item)}function x(e,t){return t.some(n=>n.metadata_key===e)?e:se(e)}function N(e,t,n){const i=t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase());if(p(e.item)){if(e.item[t]!==void 0)return e.item[t];if(x(i,n)===t&&e.item[i]!==void 0)return e.item[i]}const r=p(e.options)?e.options:{},o=n.find(d=>d.metadata_key===t);return o!==void 0&&r[E(o)]!==void 0?r[E(o)]:r[t]!==void 0?r[t]:r[i]!==void 0?r[i]:(Array.isArray(r.field)?r.field:[]).map(String).find(d=>d.startsWith(`${t}=`))?.slice(t.length+1)}function Te(e,t){return e<t?-1:+(e!==t)}function T(e){return Array.isArray(e)?e.map(T):p(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>Te(t,n)).map(([t,n])=>[t,T(n)])):e}function W(e){return typeof e=="string"?e.trim():JSON.stringify(T(e))}function Re(e,t,n,i,r){const o=t.key.trim();if(o.length===0)throw new f("Upsert key must be a non-empty field name.",u.USAGE);const s=Ie(t.existing),a=new Map,d=new Set;for(const[c,m]of e.entries()){if(m.op!=="create")continue;const l=je(m,o,c,a,i),y=ve(s.get(l)??[],o,l);if(y===void 0){m.unique={key:o,value:N(m,o,i)};continue}const h=O(y,n);typeof m.ref=="string"&&(r[m.ref]=h),Ge(m,h,i,{key:o,value:N(m,o,i)}),d.add(c)}return d}function Ie(e){const t=new Map;for(const n of e){if(n.value===void 0||n.value===null)continue;const i=W(n.value);t.set(i,[...t.get(i)??[],n.id])}return t}function je(e,t,n,i,r){const o=N(e,t,r);if(o==null||o==="")throw new f(`Mutation ${n+1} is missing the upsert key "${t}".`,u.USAGE,{code:"upsert_key_missing",required:`Every create record must carry a non-empty "${t}" value when --upsert-key ${t} is set.`,why:"Keyed upsert identifies existing items by that field; a record without it cannot be matched or safely created."});const s=W(o),a=i.get(s);if(a!==void 0)throw new f(`Mutations ${a+1} and ${n+1} share the upsert key value ${JSON.stringify(s)} for "${t}".`,u.USAGE,{code:"upsert_key_duplicate",required:"Each record must carry a distinct upsert key value within one batch.",why:"Two records with the same key would race for the same existing item."});return i.set(s,n),s}function ve(e,t,n){if(e.length>1)throw new f(`Upsert key "${t}" value ${JSON.stringify(n)} matches ${e.length} existing items: ${e.join(", ")}.`,u.CONFLICT,{code:"upsert_key_ambiguous",required:"Resolve the duplicate existing items or choose a key that is unique per item.",why:"An ambiguous key cannot select one item to update without guessing."});return e[0]}function Ge(e,t,n,i){const r=new Set([...P.update,...V("update",n)]),o=p(e.item)?Y(e.item,"update",n):Object.fromEntries(Object.entries(e.options).filter(([s])=>r.has(s)));delete e.item,delete e.ref,e.op="update",e.id=t,e.options=o,e.match=i}function B(e,t,n){for(const[i,r]of e.entries())if(r.ref!==void 0){if(r.op!=="create")throw new f(`Mutation ${i+1} ref is only valid for create operations.`,u.USAGE);if(typeof r.ref!="string"||!k.test(r.ref))throw new f(`Mutation ${i+1} ref must match ${k.source}.`,u.USAGE);if(n[r.ref]!==void 0)throw new f(`Duplicate mutation ref "${r.ref}".`,u.USAGE);n[r.ref]=typeof r.id=="string"&&r.id.trim().length>0?O(r.id,t.idPrefix):ye(t.transactionId,r.ref,t.idPrefix)}return n}function dt(e,t){const n=Me(e);Ue(n);const i=n.map(m=>typeof m.ref=="string"?m.ref:void 0),r=Object.create(null),o=t.upsert===void 0?new Set:Re(n,$e(t.upsert,n,t),t.idPrefix,t.runtimeFields??[],r);Ne(n,t.runtimeFields??[]),B(n,t,r),Ee(n,i);const s=n.map(m=>{const l={...m},y=typeof l.ref=="string"?l.ref:void 0;if(delete l.ref,y!==void 0?l.id=r[y]:l.id=L(l.id,r),p(l.options)){const h={...l.options};for(const g of["parent","blockedBy"])h[g]!==void 0&&(h[g]=L(h[g],r));Array.isArray(h.dep)?h.dep=h.dep.map(g=>q(g,r)):h.dep!==void 0&&(h.dep=q(h.dep,r)),l.options=h}return l}),a=F(JSON.stringify(s),{runtimeFields:t.runtimeFields??[]}),d=a.filter(m=>m.op==="create").map(m=>m.id);if(new Set(d).size!==d.length)throw new f("Duplicate resolved create id in mutation document.",u.USAGE);const c=a.map((m,l)=>{const y=i[l];return{index:l,...typeof y=="string"?{ref:y}:{},id:m.id,op:m.op,...o.has(l)?{upserted:!0}:{}}});return{schema_version:1,mutations:a,references:r,rows:c}}function Ce(e,t){return t.filter(n=>e[n]!==void 0&&e[n]!==null).map(n=>{const i=String(e[n]);return`${n}=${/[",\n\r\\]/u.test(i)?JSON.stringify(i):i}`}).join(",")}function ke(e,t,n){if(e!==void 0){if(!Array.isArray(e)||!e.every(p))throw new f(`${n} must be an array of objects.`,u.USAGE);return e.map(i=>Ce(i,t))}}function De(e,t){return e==="tags"&&Array.isArray(t)&&t.every(n=>typeof n=="string")?JSON.stringify(t):typeof t=="number"||typeof t=="boolean"?String(t):t}function H(e,t,n=!1){for(const[i,r,o]of X){const s=t[i],a=ke(n&&["comments","notes","learnings"].includes(i)&&Array.isArray(s)?s.filter(d=>!p(d)||d.created_at===void 0):s,o,i);a!==void 0&&a.length>0&&(e[r]=a)}}function Ke(e,t){for(const n of Object.keys(e)){if(t){if(!S.includes(n))throw w("item envelope",n,S);continue}if(!A.has(n)&&_(n,[...A])===void 0&&_(n,S)==="item")throw w("item envelope",n,S)}}function Je(e){const t=Object.hasOwn(e,"item");Ke(e,t);const n=t?e.item:e;if(!p(n))throw new f("Item document item must be an object.",u.USAGE);return{item:n,...t&&p(e.linked)?{linked:e.linked}:{}}}function Pe(e,t,n,i,r,o){if((i==="update"?me:J).has(t))return;const a=r.find(d=>d.metadata_key===t&&d.commands.includes(i));if(a!==void 0){const d=I(o,a);e[E(a)]=d!==void 0?d:a.type==="array"||a.type==="object"?JSON.stringify(n):n;return}if(!A.has(t)){if(_(t,[...A])!==void 0)throw w("item document",t,[...A]);const c=Array.isArray(e.field)?e.field:[];c.push(`${t}=${typeof n=="string"?n:JSON.stringify(n)}`),e.field=c;return}["dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"].includes(t)||(e[t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase())]=De(t,n))}function ze(e){return{command_to_fields:new Map([["create",e.filter(t=>t.commands.includes("create"))]])}}function Fe(e,t,n,i){const r=i.filter(c=>c.commands.includes("create")),o=new Set([...ae.filter(c=>t.has(c.option)).map(c=>c.field),...r.filter(c=>t.has(E(c))).map(c=>c.metadata_key),...ce(Array.isArray(n)?n.map(String):[],ze(r)).metadataKeys]),s=(Array.isArray(e)?e:[]).filter(p).filter(c=>typeof c.field=="string"&&!o.has(c.field));if(s.length===0)return{};const a=s.map(c=>typeof c.reason=="string"?c.reason.trim():""),d=s.map(c=>c.field);return t.has("deferReason")?{defer:d}:a.every(c=>c.length>0)?{defer:d,deferReason:[...new Set(a)].join("; ")}:{defer:d}}function Le(e,t,n){const i=new Set(Object.entries(e).filter(([,o])=>o!==void 0).map(([o])=>o)),r=t==="create"?b:M;for(const{target:o,keys:s}of r)s.some(a=>i.has(a))&&i.add(o);for(const o of n.filter(s=>s.commands.includes(t)))I(e,o)!==void 0&&i.add(E(o));return i}function qe(e,t,n){const i=t==="create"?b:M;for(const{target:r}of i)r!=="field"&&n.has(r)&&delete e[r]}function Ye(e,t,n={},i=[]){const r=U(e,"Item document");if(!p(r))throw new f("Item document must be a JSON object.",u.USAGE);const{item:o,linked:s}=Je(r),a={};for(const[l,y]of Object.entries(o)){const h=x(l,i);h!==l&&Object.hasOwn(o,h)||Pe(a,h,y,t,i,n)}H(a,o,t==="update"),s!==void 0&&H(a,s);const d=Le(n,t,i);if(qe(a,t,d),t==="create"&&!d.has("defer")&&Object.assign(a,Fe(o.deferred_fields,d,n.unset,i)),t==="update"){const l=Object.fromEntries(["comments","notes","learnings"].filter(y=>Object.hasOwn(o,y)&&!d.has(y.slice(0,-1))).map(y=>[y,o[y].filter(h=>p(h)&&h.created_at!==void 0)]));Object.keys(l).length>0&&(a.documentAnnotationSnapshot=l)}const c={...a,...Object.fromEntries(Object.entries(n).filter(([,l])=>l!==void 0)),...Array.isArray(a.field)&&Array.isArray(n.field)?{field:[...a.field,...n.field]}:{},stdinJson:void 0},m=Object.keys(a).filter(l=>!d.has(l));return Q(te(c,m),m)}function mt(e){return F(JSON.stringify(e))}export{ut as deriveMutationTransactionId,Ye as itemDocumentToMutationOptions,ft as parseAtomicMutationControls,F as parseItemMutationBatch,dt as resolveItemMutationDocument,W as stableUpsertValue,mt as validateItemMutationRows};
2
2
  //# sourceMappingURL=structured-mutations.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]="4534b1c9-de27-5745-88f2-641b00b94714")}catch{}})();import{flushTelemetryQueueNow}from"../core/telemetry/runtime.js";async function flushTelemetryQueue(){await flushTelemetryQueueNow()}export{flushTelemetryQueue};
1
+ import{flushTelemetryQueueNow as e}from"../core/telemetry/runtime.js";async function t(){await e()}export{t as flushTelemetryQueue};
2
2
  //# sourceMappingURL=telemetry-flush.js.map
@@ -1,5 +1,5 @@
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]="bc3145a3-5949-5c61-b275-a5376881b91f")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{pathExists,readFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{resolveGlobalPmRoot}from"../core/store/paths.js";import{readSettings,writeSettings}from"../core/store/settings.js";import{effectiveTelemetryEndpoint,redactTelemetryEndpoint,resolveTelemetryEnvironmentPolicy,telemetryRuntimeFileName}from"../core/telemetry/policy.js";import{flushTelemetryQueueNow,withTelemetryQueueMutation}from"../core/telemetry/runtime.js";import{createUnknownSubcommandError}from"./agent/subcommand-recovery.js";import{PM_COMMAND_ALIAS_CONTRACTS}from"./cli-contracts/command-aliases.js";const TELEMETRY_STATE_RELATIVE_PATH=path.join("runtime","telemetry","state.json"),TELEMETRY_RUNTIME_RELATIVE_PATH=path.join("runtime","telemetry"),DEFAULT_STATS_LIMIT=20,DEPRECATED_ALIASES=PM_COMMAND_ALIAS_CONTRACTS.filter(contract=>contract.lifecycle==="deprecated"),TELEMETRY_SUBCOMMANDS=["status","flush","stats","clear"],nearestRankPercentile=(sortedAscending,fraction)=>{const rank=Math.ceil(fraction*sortedAscending.length),index=Math.min(sortedAscending.length-1,Math.max(0,rank-1));return sortedAscending[index]},normalizeTelemetryText=(value,fallback)=>typeof value!="string"?fallback:value.trim().length>0?value:fallback,normalizeFiniteInteger=value=>{if(!(typeof value!="number"||!Number.isFinite(value)))return Math.trunc(value)},normalizeTelemetryQueueEntry=entry=>({command:normalizeTelemetryText(entry.event.command,"<unknown>"),eventType:normalizeTelemetryText(entry.event.event_type,"unknown"),eventSchemaVersion:normalizeFiniteInteger(entry.event.schema_version),clientSchemaVersion:normalizeFiniteInteger(entry.client_schema_version)}),createTelemetryStatsAccumulator=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),readTelemetryDuration=payload=>{const value=payload?.duration_ms;return typeof value=="number"&&Number.isFinite(value)?value:void 0},readTelemetryResolution=payload=>{const value=payload?.command_resolution;return normalizeTelemetryText(value,"")||void 0},incrementTelemetryCount=(counts,key)=>{counts[key]=(counts[key]??0)+1},recordTelemetryFinishPayload=(current,payload)=>{const durationMs=readTelemetryDuration(payload);durationMs!==void 0&&current.finish_durations_ms.push(durationMs),payload?.ok===!0?current.ok_count+=1:current.error_count+=1;const resolution=readTelemetryResolution(payload);resolution!==void 0&&incrementTelemetryCount(current.resolution_counts,resolution)},normalizeTelemetryAttempts=attempts=>Number.isFinite(attempts)?Math.max(0,Math.trunc(attempts)):0,addTelemetryDimension=(values,value)=>{value!==void 0&&values.add(value)},recordTelemetryQueueEntry=(grouped,entry)=>{const normalized=normalizeTelemetryQueueEntry(entry),current=grouped.get(normalized.command)??createTelemetryStatsAccumulator();current.count+=1,current.max_attempts=Math.max(current.max_attempts,normalizeTelemetryAttempts(entry.attempts)),incrementTelemetryCount(current.event_type_counts,normalized.eventType),addTelemetryDimension(current.event_schema_versions,normalized.eventSchemaVersion),addTelemetryDimension(current.client_schema_versions,normalized.clientSchemaVersion),normalized.eventType==="command_finish"&&recordTelemetryFinishPayload(current,entry.event.payload),grouped.set(normalized.command,current)},buildTelemetryStatsBucket=(command,value)=>{const finishCount=value.ok_count+value.error_count,sortedDurations=[...value.finish_durations_ms].sort((left,right)=>left-right),resolutionEntries=Object.entries(value.resolution_counts).sort((left,right)=>left[0].localeCompare(right[0]));return{command,count:value.count,event_type_counts:Object.fromEntries(Object.entries(value.event_type_counts).sort((left,right)=>left[0].localeCompare(right[0]))),max_attempts:value.max_attempts,event_schema_versions:[...value.event_schema_versions].sort((left,right)=>left-right),client_schema_versions:[...value.client_schema_versions].sort((left,right)=>left-right),...sortedDurations.length>0?{duration_p50_ms:nearestRankPercentile(sortedDurations,.5),duration_p95_ms:nearestRankPercentile(sortedDurations,.95),duration_max_ms:sortedDurations[sortedDurations.length-1]}:{},...finishCount>0?{ok_count:value.ok_count,error_count:value.error_count,error_rate:value.error_count/finishCount}:{},...resolutionEntries.length>0?{command_resolution_counts:Object.fromEntries(resolutionEntries)}:{}}},normalizeTelemetrySubcommand=value=>{const normalized=(value??"status").trim().toLowerCase();if(TELEMETRY_SUBCOMMANDS.includes(normalized))return normalized;throw createUnknownSubcommandError({command_path:"telemetry",token:value?.trim()||"<empty>",allowed:TELEMETRY_SUBCOMMANDS,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},throwInvalidTelemetryLimit=()=>{throw new PmCliError("--limit must be a positive integer",EXIT_CODE.USAGE)},requirePositiveTelemetryLimit=value=>[!Number.isFinite(value),!Number.isInteger(value),value<=0].includes(!0)?throwInvalidTelemetryLimit():value,parseTelemetryStringLimit=raw=>{const trimmed=raw.trim();return[trimmed.length===0,!/^\d+$/.test(trimmed)].includes(!0)?throwInvalidTelemetryLimit():requirePositiveTelemetryLimit(Number.parseInt(trimmed,10))},parseTelemetryStatsLimit=raw=>raw===void 0?DEFAULT_STATS_LIMIT:typeof raw=="number"?requirePositiveTelemetryLimit(raw):typeof raw=="string"?parseTelemetryStringLimit(raw):throwInvalidTelemetryLimit(),isTelemetryQueueEntry=value=>{if(typeof value!="object"||value===null)return!1;const candidate=value;return typeof candidate.attempts=="number"&&typeof candidate.event=="object"&&candidate.event!==null},parseTelemetryQueueRow=row=>{try{const parsed=JSON.parse(row);return isTelemetryQueueEntry(parsed)?parsed:void 0}catch{return}},splitTelemetryQueueRows=raw=>raw===null?[]:raw.split(`
2
- `).map(line=>line.trim()).filter(line=>line.length>0),parseTelemetryQueue=raw=>{const rows=splitTelemetryQueueRows(raw),entries=[];let invalidRows=0;for(const row of rows){const parsed=parseTelemetryQueueRow(row);parsed===void 0?invalidRows+=1:entries.push(parsed)}return{rows_total:rows.length,valid_entries:entries.length,invalid_rows:invalidRows,entries}},isTelemetryRuntimeState=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),parseTelemetryRuntimeState=raw=>{try{const parsed=JSON.parse(raw);return isTelemetryRuntimeState(parsed)?parsed:{}}catch{return{}}},readTelemetryRuntimeState=async statePath=>{const stateRaw=await readFileIfExists(statePath);return stateRaw===null||stateRaw.trim().length===0?{}:parseTelemetryRuntimeState(stateRaw)};function aliasUsageCutoff(retentionDays){const now=new Date;return new Date(Date.UTC(now.getUTCFullYear(),now.getUTCMonth(),now.getUTCDate()-Math.max(1,Math.trunc(retentionDays))+1)).toISOString().slice(0,10)}function normalizeAliasUsageDays(value,cutoff,today){const days=Object.create(null);for(const[day,entry]of Object.entries(value)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(day)||day<cutoff||day>today||typeof entry!="object"||entry===null||Array.isArray(entry))continue;const observation=entry;!Number.isSafeInteger(observation.count)||observation.count<1||typeof observation.last_seen!="string"||!observation.last_seen.startsWith(day)||(days[day]={count:observation.count,last_seen:observation.last_seen})}return days}function normalizeAliasUsage(value,cutoff){const result=Object.create(null);if(typeof value!="object"||value===null||Array.isArray(value))return result;const stored=value,today=new Date().toISOString().slice(0,10);for(const contract of DEPRECATED_ALIASES){const candidate=stored[contract.alias];if(typeof candidate!="object"||candidate===null||Array.isArray(candidate))continue;const row=candidate;if(row.canonical!==contract.canonical||typeof row.days!="object"||row.days===null||Array.isArray(row.days))continue;const days=normalizeAliasUsageDays(row.days,cutoff,today);Object.keys(days).length>0&&(result[contract.alias]={canonical:contract.canonical,days})}return result}async function readRetainedAliasUsage(globalPmRoot,statePath,retentionDays){const cutoff=aliasUsageCutoff(retentionDays),state=await readTelemetryRuntimeState(statePath),usage=normalizeAliasUsage(state.alias_usage,cutoff);if(JSON.stringify(state.alias_usage??{})===JSON.stringify(usage))return usage;try{await withTelemetryQueueMutation(async()=>{const current=await readTelemetryRuntimeState(statePath);if(current.alias_usage===void 0)return;const retained=normalizeAliasUsage(current.alias_usage,cutoff);JSON.stringify(current.alias_usage)!==JSON.stringify(retained)&&await writeFileAtomic(statePath,`${JSON.stringify({...current,alias_usage:retained},null,2)}
3
- `)},globalPmRoot,250)}catch{}return usage}async function recordDeprecatedAliasUsage(alias){const contract=DEPRECATED_ALIASES.find(entry=>entry.alias===alias);if(!contract||resolveTelemetryEnvironmentPolicy().telemetry_disabled)return!1;const globalPmRoot=resolveGlobalPmRoot(process.cwd());try{return await withTelemetryQueueMutation(async()=>{const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled||resolveTelemetryEnvironmentPolicy().telemetry_disabled)return!1;const statePath=path.join(globalPmRoot,TELEMETRY_STATE_RELATIVE_PATH),state=await readTelemetryRuntimeState(statePath),usage=normalizeAliasUsage(state.alias_usage,aliasUsageCutoff(settings.telemetry.retention_days)),day=new Date().toISOString().slice(0,10),previous=usage[alias]?.days[day];return usage[alias]={canonical:contract.canonical,days:{...usage[alias]?.days,[day]:{count:Math.min(Number.MAX_SAFE_INTEGER,(previous?.count??0)+1),last_seen:nowIso()}}},await writeFileAtomic(statePath,`${JSON.stringify({...state,alias_usage:usage},null,2)}
4
- `),!0},globalPmRoot,250)}catch{return!1}}const nullableTelemetryStateValue=value=>value??null,buildTelemetryStatusSummary=async globalPmRoot=>{const settings=await readSettings(globalPmRoot),queuePath=path.join(globalPmRoot,TELEMETRY_RUNTIME_RELATIVE_PATH,telemetryRuntimeFileName("events.jsonl")),statePath=path.join(globalPmRoot,TELEMETRY_RUNTIME_RELATIVE_PATH,telemetryRuntimeFileName("state.json")),queueRaw=await readFileIfExists(queuePath),queue=parseTelemetryQueue(queueRaw),runtimeState=await readTelemetryRuntimeState(statePath),environmentPolicy=resolveTelemetryEnvironmentPolicy();return{enabled:settings.telemetry.enabled&&!environmentPolicy.telemetry_disabled,configured_enabled:settings.telemetry.enabled,env_overrides:environmentPolicy,endpoint:redactTelemetryEndpoint(effectiveTelemetryEndpoint(settings.telemetry.endpoint)),queue_path:queuePath,state_path:statePath,queue_rows_total:queue.rows_total,queue_entries:queue.valid_entries,queue_invalid_rows:queue.invalid_rows,queue_size_bytes:Buffer.byteLength(queueRaw??"","utf8"),last_attempted_flush_at:nullableTelemetryStateValue(runtimeState.last_attempted_flush_at),last_successful_flush_at:nullableTelemetryStateValue(runtimeState.last_successful_flush_at),last_failed_flush_at:nullableTelemetryStateValue(runtimeState.last_failed_flush_at),last_failed_flush_error:nullableTelemetryStateValue(runtimeState.last_failed_flush_error)}},buildTelemetryStatsBuckets=entries=>{const grouped=new Map;for(const entry of entries)recordTelemetryQueueEntry(grouped,entry);return[...grouped.entries()].map(([command,value])=>buildTelemetryStatsBucket(command,value)).sort((left,right)=>right.count-left.count||left.command.localeCompare(right.command))},runTelemetryStatus=async(_options,context)=>({action:"telemetry",subcommand:"status",status:await buildTelemetryStatusSummary(context.globalPmRoot),generated_at:nowIso()}),runTelemetryFlush=async(_options,context)=>{const before=await buildTelemetryStatusSummary(context.globalPmRoot);await flushTelemetryQueueNow(context.globalPmRoot);const after=await buildTelemetryStatusSummary(context.globalPmRoot),queueEntriesDrained=Math.max(0,before.queue_entries-after.queue_entries),queueEmpty=after.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:before.queue_entries,queue_entries_after:after.queue_entries,queue_entries_drained:queueEntriesDrained,queue_progressed:queueEntriesDrained>0,queue_empty:queueEmpty,queue_drained:queueEmpty,status:after,generated_at:nowIso()}},runTelemetryStats=async(options,context)=>{const limit=parseTelemetryStatsLimit(options.limit),queueRaw=await readFileIfExists(context.queuePath),queue=parseTelemetryQueue(queueRaw),buckets=buildTelemetryStatsBuckets(queue.entries),selected=buckets.slice(0,limit),settings=await readSettings(context.globalPmRoot),usage=await readRetainedAliasUsage(context.globalPmRoot,path.join(context.globalPmRoot,TELEMETRY_STATE_RELATIVE_PATH),settings.telemetry.retention_days),aliasUsage=Object.entries(usage).map(([alias,entry])=>{const days=Object.values(entry.days);return{alias,canonical:entry.canonical,count:days.reduce((total,day)=>Math.min(Number.MAX_SAFE_INTEGER,total+day.count),0),last_seen:days.map(day=>day.last_seen).sort().at(-1)}}).sort((left,right)=>right.count-left.count||left.alias.localeCompare(right.alias));return{action:"telemetry",subcommand:"stats",limit,total_commands:buckets.length,queue_entries:queue.valid_entries,queue_invalid_rows:queue.invalid_rows,queue_rows_total:queue.rows_total,truncated:buckets.length>selected.length,stats:selected,alias_usage:aliasUsage,zero_use_aliases:DEPRECATED_ALIASES.map(entry=>entry.alias).filter(alias=>usage[alias]===void 0),alias_usage_retention_days:settings.telemetry.retention_days,generated_at:nowIso()}},runTelemetryClear=async(_options,context)=>withTelemetryQueueMutation(async()=>{const settings=await readSettings(context.globalPmRoot),settingsChanged=[settings.telemetry.enabled!==!1,settings.telemetry.installation_id!=="",settings.telemetry.first_run_prompt_completed!==!0].includes(!0);settings.telemetry.enabled=!1,settings.telemetry.first_run_prompt_completed=!0,settings.telemetry.installation_id="",settingsChanged&&await writeSettings(context.globalPmRoot,settings,"telemetry:clear");const telemetryRuntimePath=path.join(context.globalPmRoot,TELEMETRY_RUNTIME_RELATIVE_PATH),existed=await pathExists(telemetryRuntimePath);return await fs.rm(telemetryRuntimePath,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:settingsChanged,runtime_dir_removed:existed&&!await pathExists(telemetryRuntimePath),queue_exists_after:await pathExists(context.queuePath),state_exists_after:await pathExists(context.statePath),status:await buildTelemetryStatusSummary(context.globalPmRoot),generated_at:nowIso()}},context.globalPmRoot),TELEMETRY_COMMAND_HANDLERS={status:runTelemetryStatus,flush:runTelemetryFlush,stats:runTelemetryStats,clear:runTelemetryClear};async function runTelemetry(options,_global){const subcommand=normalizeTelemetrySubcommand(options.subcommand),globalPmRoot=resolveGlobalPmRoot(process.cwd());return TELEMETRY_COMMAND_HANDLERS[subcommand](options,{globalPmRoot,queuePath:path.join(globalPmRoot,TELEMETRY_RUNTIME_RELATIVE_PATH,telemetryRuntimeFileName("events.jsonl")),statePath:path.join(globalPmRoot,TELEMETRY_RUNTIME_RELATIVE_PATH,telemetryRuntimeFileName("state.json"))})}export{TELEMETRY_SUBCOMMANDS,recordDeprecatedAliasUsage,runTelemetry};
1
+ import J from"node:fs/promises";import u from"node:path";import{pathExists as y,readFileIfExists as w,writeFileAtomic as M}from"../core/fs/fs-utils.js";import{EXIT_CODE as Q}from"../core/shared/constants.js";import{PmCliError as V}from"../core/shared/errors.js";import{nowIso as _}from"../core/shared/time.js";import{resolveGlobalPmRoot as P}from"../core/store/paths.js";import{readSettings as f,writeSettings as Y}from"../core/store/settings.js";import{effectiveTelemetryEndpoint as B,redactTelemetryEndpoint as G,resolveTelemetryEnvironmentPolicy as S,telemetryRuntimeFileName as p}from"../core/telemetry/policy.js";import{flushTelemetryQueueNow as $,withTelemetryQueueMutation as E}from"../core/telemetry/runtime.js";import{createUnknownSubcommandError as H}from"./agent/subcommand-recovery.js";import{PM_COMMAND_ALIAS_CONTRACTS as X}from"./cli-contracts/command-aliases.js";const N=u.join("runtime","telemetry","state.json"),d=u.join("runtime","telemetry"),W=20,R=X.filter(t=>t.lifecycle==="deprecated"),O=["status","flush","stats","clear"],C=(t,e)=>{const s=Math.ceil(e*t.length),n=Math.min(t.length-1,Math.max(0,s-1));return t[n]},A=(t,e)=>typeof t!="string"?e:t.trim().length>0?t:e,D=t=>{if(!(typeof t!="number"||!Number.isFinite(t)))return Math.trunc(t)},K=t=>({command:A(t.event.command,"<unknown>"),eventType:A(t.event.event_type,"unknown"),eventSchemaVersion:D(t.event.schema_version),clientSchemaVersion:D(t.client_schema_version)}),Z=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),ee=t=>{const e=t?.duration_ms;return typeof e=="number"&&Number.isFinite(e)?e:void 0},te=t=>{const e=t?.command_resolution;return A(e,"")||void 0},I=(t,e)=>{t[e]=(t[e]??0)+1},ne=(t,e)=>{const s=ee(e);s!==void 0&&t.finish_durations_ms.push(s),e?.ok===!0?t.ok_count+=1:t.error_count+=1;const n=te(e);n!==void 0&&I(t.resolution_counts,n)},se=t=>Number.isFinite(t)?Math.max(0,Math.trunc(t)):0,L=(t,e)=>{e!==void 0&&t.add(e)},re=(t,e)=>{const s=K(e),n=t.get(s.command)??Z();n.count+=1,n.max_attempts=Math.max(n.max_attempts,se(e.attempts)),I(n.event_type_counts,s.eventType),L(n.event_schema_versions,s.eventSchemaVersion),L(n.client_schema_versions,s.clientSchemaVersion),s.eventType==="command_finish"&&ne(n,e.event.payload),t.set(s.command,n)},oe=(t,e)=>{const s=e.ok_count+e.error_count,n=[...e.finish_durations_ms].sort((r,o)=>r-o),a=Object.entries(e.resolution_counts).sort((r,o)=>r[0].localeCompare(o[0]));return{command:t,count:e.count,event_type_counts:Object.fromEntries(Object.entries(e.event_type_counts).sort((r,o)=>r[0].localeCompare(o[0]))),max_attempts:e.max_attempts,event_schema_versions:[...e.event_schema_versions].sort((r,o)=>r-o),client_schema_versions:[...e.client_schema_versions].sort((r,o)=>r-o),...n.length>0?{duration_p50_ms:C(n,.5),duration_p95_ms:C(n,.95),duration_max_ms:n[n.length-1]}:{},...s>0?{ok_count:e.ok_count,error_count:e.error_count,error_rate:e.error_count/s}:{},...a.length>0?{command_resolution_counts:Object.fromEntries(a)}:{}}},ae=t=>{const e=(t??"status").trim().toLowerCase();if(O.includes(e))return e;throw H({command_path:"telemetry",token:t?.trim()||"<empty>",allowed:O,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},v=()=>{throw new V("--limit must be a positive integer",Q.USAGE)},U=t=>[!Number.isFinite(t),!Number.isInteger(t),t<=0].includes(!0)?v():t,ie=t=>{const e=t.trim();return[e.length===0,!/^\d+$/.test(e)].includes(!0)?v():U(Number.parseInt(e,10))},ue=t=>t===void 0?W:typeof t=="number"?U(t):typeof t=="string"?ie(t):v(),ce=t=>{if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.attempts=="number"&&typeof e.event=="object"&&e.event!==null},le=t=>{try{const e=JSON.parse(t);return ce(e)?e:void 0}catch{return}},me=t=>t===null?[]:t.split(`
2
+ `).map(e=>e.trim()).filter(e=>e.length>0),k=t=>{const e=me(t),s=[];let n=0;for(const a of e){const r=le(a);r===void 0?n+=1:s.push(r)}return{rows_total:e.length,valid_entries:s.length,invalid_rows:n,entries:s}},_e=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),de=t=>{try{const e=JSON.parse(t);return _e(e)?e:{}}catch{return{}}},h=async t=>{const e=await w(t);return e===null||e.trim().length===0?{}:de(e)};function F(t){const e=new Date;return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()-Math.max(1,Math.trunc(t))+1)).toISOString().slice(0,10)}function ye(t,e,s){const n=Object.create(null);for(const[a,r]of Object.entries(t)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(a)||a<e||a>s||typeof r!="object"||r===null||Array.isArray(r))continue;const o=r;!Number.isSafeInteger(o.count)||o.count<1||typeof o.last_seen!="string"||!o.last_seen.startsWith(a)||(n[a]={count:o.count,last_seen:o.last_seen})}return n}function j(t,e){const s=Object.create(null);if(typeof t!="object"||t===null||Array.isArray(t))return s;const n=t,a=new Date().toISOString().slice(0,10);for(const r of R){const o=n[r.alias];if(typeof o!="object"||o===null||Array.isArray(o))continue;const i=o;if(i.canonical!==r.canonical||typeof i.days!="object"||i.days===null||Array.isArray(i.days))continue;const l=ye(i.days,e,a);Object.keys(l).length>0&&(s[r.alias]={canonical:r.canonical,days:l})}return s}async function fe(t,e,s){const n=F(s),a=await h(e),r=j(a.alias_usage,n);if(JSON.stringify(a.alias_usage??{})===JSON.stringify(r))return r;try{await E(async()=>{const o=await h(e);if(o.alias_usage===void 0)return;const i=j(o.alias_usage,n);JSON.stringify(o.alias_usage)!==JSON.stringify(i)&&await M(e,`${JSON.stringify({...o,alias_usage:i},null,2)}
3
+ `)},t,250)}catch{}return r}async function De(t){const e=R.find(n=>n.alias===t);if(!e||S().telemetry_disabled)return!1;const s=P(process.cwd());try{return await E(async()=>{const n=await f(s);if(!n.telemetry.enabled||S().telemetry_disabled)return!1;const a=u.join(s,N),r=await h(a),o=j(r.alias_usage,F(n.telemetry.retention_days)),i=new Date().toISOString().slice(0,10),l=o[t]?.days[i];return o[t]={canonical:e.canonical,days:{...o[t]?.days,[i]:{count:Math.min(Number.MAX_SAFE_INTEGER,(l?.count??0)+1),last_seen:_()}}},await M(a,`${JSON.stringify({...r,alias_usage:o},null,2)}
4
+ `),!0},s,250)}catch{return!1}}const g=t=>t??null,b=async t=>{const e=await f(t),s=u.join(t,d,p("events.jsonl")),n=u.join(t,d,p("state.json")),a=await w(s),r=k(a),o=await h(n),i=S();return{enabled:e.telemetry.enabled&&!i.telemetry_disabled,configured_enabled:e.telemetry.enabled,env_overrides:i,endpoint:G(B(e.telemetry.endpoint)),queue_path:s,state_path:n,queue_rows_total:r.rows_total,queue_entries:r.valid_entries,queue_invalid_rows:r.invalid_rows,queue_size_bytes:Buffer.byteLength(a??"","utf8"),last_attempted_flush_at:g(o.last_attempted_flush_at),last_successful_flush_at:g(o.last_successful_flush_at),last_failed_flush_at:g(o.last_failed_flush_at),last_failed_flush_error:g(o.last_failed_flush_error)}},pe=t=>{const e=new Map;for(const s of t)re(e,s);return[...e.entries()].map(([s,n])=>oe(s,n)).sort((s,n)=>n.count-s.count||s.command.localeCompare(n.command))},he=async(t,e)=>({action:"telemetry",subcommand:"status",status:await b(e.globalPmRoot),generated_at:_()}),ge=async(t,e)=>{const s=await b(e.globalPmRoot);await $(e.globalPmRoot);const n=await b(e.globalPmRoot),a=Math.max(0,s.queue_entries-n.queue_entries),r=n.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:s.queue_entries,queue_entries_after:n.queue_entries,queue_entries_drained:a,queue_progressed:a>0,queue_empty:r,queue_drained:r,status:n,generated_at:_()}},be=async(t,e)=>{const s=ue(t.limit),n=await w(e.queuePath),a=k(n),r=pe(a.entries),o=r.slice(0,s),i=await f(e.globalPmRoot),l=await fe(e.globalPmRoot,u.join(e.globalPmRoot,N),i.telemetry.retention_days),x=Object.entries(l).map(([c,m])=>{const q=Object.values(m.days);return{alias:c,canonical:m.canonical,count:q.reduce((T,z)=>Math.min(Number.MAX_SAFE_INTEGER,T+z.count),0),last_seen:q.map(T=>T.last_seen).sort().at(-1)}}).sort((c,m)=>m.count-c.count||c.alias.localeCompare(m.alias));return{action:"telemetry",subcommand:"stats",limit:s,total_commands:r.length,queue_entries:a.valid_entries,queue_invalid_rows:a.invalid_rows,queue_rows_total:a.rows_total,truncated:r.length>o.length,stats:o,alias_usage:x,zero_use_aliases:R.map(c=>c.alias).filter(c=>l[c]===void 0),alias_usage_retention_days:i.telemetry.retention_days,generated_at:_()}},Te=async(t,e)=>E(async()=>{const s=await f(e.globalPmRoot),n=[s.telemetry.enabled!==!1,s.telemetry.installation_id!=="",s.telemetry.first_run_prompt_completed!==!0].includes(!0);s.telemetry.enabled=!1,s.telemetry.first_run_prompt_completed=!0,s.telemetry.installation_id="",n&&await Y(e.globalPmRoot,s,"telemetry:clear");const a=u.join(e.globalPmRoot,d),r=await y(a);return await J.rm(a,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:n,runtime_dir_removed:r&&!await y(a),queue_exists_after:await y(e.queuePath),state_exists_after:await y(e.statePath),status:await b(e.globalPmRoot),generated_at:_()}},e.globalPmRoot),we={status:he,flush:ge,stats:be,clear:Te};async function Ie(t,e){const s=ae(t.subcommand),n=P(process.cwd());return we[s](t,{globalPmRoot:n,queuePath:u.join(n,d,p("events.jsonl")),statePath:u.join(n,d,p("state.json"))})}export{O as TELEMETRY_SUBCOMMANDS,De as recordDeprecatedAliasUsage,Ie as runTelemetry};
5
5
  //# sourceMappingURL=telemetry.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]="4e476a2f-8735-53e9-88c3-b43bfc34e1f5")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{pathExists,readFileIfExists}from"../core/fs/fs-utils.js";import{writeWorkspaceJsonWithHistory}from"../core/history/workspace-history.js";import{resolveAuthor}from"../core/shared/author.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{resolvePriority}from"../core/item/priority.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS}from"./cli-contracts.js";const TEMPLATE_DIRECTORY_NAME="templates",TEMPLATE_FILE_EXTENSION=".json",TEMPLATE_NAME_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,TEMPLATE_OPTION_REPEATABLE_KEYS=CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS.map(entry=>entry.target).filter(target=>target!=="acceptanceCriteria"),TEMPLATE_OPTION_REPEATABLE_KEY_SET=new Set(TEMPLATE_OPTION_REPEATABLE_KEYS),BUILTIN_TEMPLATE_TIMESTAMP="1970-01-01T00:00:00.000Z",BUILTIN_TEMPLATES={bug:{type:"Issue",priority:"1",tags:"bug",acceptanceCriteria:"Bug no longer reproduces with the steps below and a regression test guards it.",expectedResult:"Describe the correct behavior.",actualResult:"Describe the observed (buggy) behavior.",body:`## Repro steps
1
+ import{assertInitializedTracker as x}from"./environment/tracker-preflight.js";import g from"node:fs/promises";import A from"node:path";import{pathExists as b,readFileIfExists as I}from"../core/fs/fs-utils.js";import{writeWorkspaceJsonWithHistory as N}from"../core/history/workspace-history.js";import{resolveAuthor as M}from"../core/shared/author.js";import{EXIT_CODE as p}from"../core/shared/constants.js";import{PmCliError as u}from"../core/shared/errors.js";import{nowIso as O}from"../core/shared/time.js";import{resolvePriority as $}from"../core/item/priority.js";import{resolvePmRoot as T}from"../core/store/paths.js";import{readSettings as U}from"../core/store/settings.js";import{CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS as D}from"./cli-contracts.js";const F="templates",h=".json",R=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,j=D.map(n=>n.target).filter(n=>n!=="acceptanceCriteria"),G=new Set(j),v="1970-01-01T00:00:00.000Z",C={bug:{type:"Issue",priority:"1",tags:"bug",acceptanceCriteria:"Bug no longer reproduces with the steps below and a regression test guards it.",expectedResult:"Describe the correct behavior.",actualResult:"Describe the observed (buggy) behavior.",body:`## Repro steps
2
2
  1.
3
3
  2.
4
4
  3.
@@ -22,6 +22,6 @@
22
22
  `},chore:{type:"Chore",priority:"3",tags:"chore",acceptanceCriteria:"Maintenance task done with no behavior change and green checks.",body:`## What
23
23
 
24
24
  ## Why
25
- `}},_testOnly={normalizeTemplateName,extractTemplateOptions,parseStoredTemplateDocument,builtinTemplateDocument,readStoredTemplateDocument};function normalizeTemplateName(rawName){const name=rawName.trim();if(!TEMPLATE_NAME_PATTERN.test(name))throw new PmCliError(`Invalid template name "${rawName}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,EXIT_CODE.USAGE);return name}function templatesDirectory(pmRoot){return path.join(pmRoot,TEMPLATE_DIRECTORY_NAME)}function templatePath(pmRoot,normalizedName){return path.join(templatesDirectory(pmRoot),`${normalizedName}${TEMPLATE_FILE_EXTENSION}`)}async function ensureTrackerInitialized(pmRoot){await assertInitializedTracker(pmRoot)}function sortTemplateOptions(options){return Object.fromEntries(Object.entries(options).sort(([left],[right])=>left.localeCompare(right)))}function extractTemplateOptions(rawOptions){const next={};for(const[key,value]of Object.entries(rawOptions))if(value!==void 0){if(key==="priority"){next[key]=String(resolvePriority(value));continue}if(TEMPLATE_OPTION_REPEATABLE_KEY_SET.has(key)){if(typeof value=="string"){next[key]=[value];continue}if(!Array.isArray(value))continue;const values=value.filter(entry=>typeof entry=="string");values.length>0&&(next[key]=values);continue}if(typeof value=="string"){next[key]=value;continue}Array.isArray(value)&&value.every(entry=>typeof entry=="string")&&(next[key]=[...value])}return sortTemplateOptions(next)}function parseStoredTemplateOptions(rawOptions,templateName){if(typeof rawOptions!="object"||rawOptions===null||Array.isArray(rawOptions))throw new PmCliError(`Template "${templateName}" has invalid options payload.`,EXIT_CODE.GENERIC_FAILURE);const optionsRecord=rawOptions,normalized={};for(const[key,value]of Object.entries(optionsRecord)){const normalizedKey=key.trim();if(normalizedKey.length===0)throw new PmCliError(`Template "${templateName}" contains an empty option key.`,EXIT_CODE.GENERIC_FAILURE);if(typeof value=="string"){normalized[normalizedKey]=value;continue}if(Array.isArray(value)&&value.every(entry=>typeof entry=="string")){normalized[normalizedKey]=[...value];continue}throw new PmCliError(`Template "${templateName}" contains invalid value for option "${normalizedKey}".`,EXIT_CODE.GENERIC_FAILURE)}return sortTemplateOptions(normalized)}function parseStoredTemplateDocument(raw,normalizedName){let parsed;try{parsed=JSON.parse(raw)}catch{throw new PmCliError(`Template "${normalizedName}" contains invalid JSON.`,EXIT_CODE.GENERIC_FAILURE)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new PmCliError(`Template "${normalizedName}" has invalid document shape.`,EXIT_CODE.GENERIC_FAILURE);const record=parsed,options=parseStoredTemplateOptions(record.options,normalizedName),now=nowIso();return{name:typeof record.name=="string"&&record.name.trim().length>0?record.name.trim():normalizedName,created_at:typeof record.created_at=="string"?record.created_at:now,updated_at:typeof record.updated_at=="string"?record.updated_at:now,options}}function builtinTemplateDocument(normalizedName){const options=BUILTIN_TEMPLATES[normalizedName];return options?{name:normalizedName,created_at:BUILTIN_TEMPLATE_TIMESTAMP,updated_at:BUILTIN_TEMPLATE_TIMESTAMP,options:sortTemplateOptions({...options})}:null}async function resolveTemplateDocument(pmRoot,normalizedName){const raw=await readFileIfExists(templatePath(pmRoot,normalizedName));if(raw!==null)return{document:parseStoredTemplateDocument(raw,normalizedName),source:"user"};const builtin=builtinTemplateDocument(normalizedName);if(builtin)return{document:builtin,source:"builtin"};throw new PmCliError(`Template "${normalizedName}" not found`,EXIT_CODE.NOT_FOUND)}async function readStoredTemplateDocument(pmRoot,normalizedName){const raw=await readFileIfExists(templatePath(pmRoot,normalizedName));if(raw===null)throw new PmCliError(`Template "${normalizedName}" not found`,EXIT_CODE.NOT_FOUND);return parseStoredTemplateDocument(raw,normalizedName)}async function loadCreateTemplateOptions(pmRoot,rawTemplateName){const normalizedName=normalizeTemplateName(rawTemplateName),{document}=await resolveTemplateDocument(pmRoot,normalizedName);return document.options}async function runTemplatesSave(rawTemplateName,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureTrackerInitialized(pmRoot);const normalizedName=normalizeTemplateName(rawTemplateName),nextOptions=extractTemplateOptions(options);if(Object.keys(nextOptions).length===0)throw new PmCliError("templates save requires at least one create option flag",EXIT_CODE.USAGE);const now=nowIso(),storedPath=templatePath(pmRoot,normalizedName);let createdAt=now;await pathExists(storedPath)&&(createdAt=(await readStoredTemplateDocument(pmRoot,normalizedName)).created_at);const document={name:normalizedName,created_at:createdAt,updated_at:now,options:nextOptions},settings=await readSettings(pmRoot);return await fs.mkdir(templatesDirectory(pmRoot),{recursive:!0}),await writeWorkspaceJsonWithHistory({pmRoot,filePath:storedPath,raw:`${JSON.stringify(document,null,2)}
26
- `,op:"templates:save",author:resolveAuthor(void 0,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms}),{name:document.name,created_at:document.created_at,updated_at:document.updated_at,path:storedPath,options:document.options}}async function readUserTemplateNames(pmRoot){const dirPath=templatesDirectory(pmRoot);return await pathExists(dirPath)?(await fs.readdir(dirPath)).filter(entry=>entry.toLowerCase().endsWith(TEMPLATE_FILE_EXTENSION)).map(entry=>entry.slice(0,-TEMPLATE_FILE_EXTENSION.length)).filter(entry=>TEMPLATE_NAME_PATTERN.test(entry)):[]}async function runTemplatesList(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureTrackerInitialized(pmRoot);const userTemplates=await readUserTemplateNames(pmRoot),userTemplateSet=new Set(userTemplates),builtinTemplates=Object.keys(BUILTIN_TEMPLATES).filter(name=>!userTemplateSet.has(name)),sortedUser=[...userTemplates].sort((left,right)=>left.localeCompare(right)),sortedBuiltin=[...builtinTemplates].sort((left,right)=>left.localeCompare(right)),templates=[...new Set([...sortedUser,...sortedBuiltin])].sort((left,right)=>left.localeCompare(right));return{templates,count:templates.length,builtin_templates:sortedBuiltin,user_templates:sortedUser}}async function runTemplatesShow(rawTemplateName,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureTrackerInitialized(pmRoot);const normalizedName=normalizeTemplateName(rawTemplateName),{document,source}=await resolveTemplateDocument(pmRoot,normalizedName);return{name:document.name,source,created_at:document.created_at,updated_at:document.updated_at,path:source==="builtin"?`builtin:${normalizedName}`:templatePath(pmRoot,normalizedName),options:document.options}}export{_testOnly,loadCreateTemplateOptions,runTemplatesList,runTemplatesSave,runTemplatesShow};
25
+ `}},rt={normalizeTemplateName:d,extractTemplateOptions:S,parseStoredTemplateDocument:_,builtinTemplateDocument:P,readStoredTemplateDocument:k};function d(n){const e=n.trim();if(!R.test(e))throw new u(`Invalid template name "${n}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,p.USAGE);return e}function y(n){return A.join(n,F)}function m(n,e){return A.join(y(n),`${e}${h}`)}async function E(n){await x(n)}function w(n){return Object.fromEntries(Object.entries(n).sort(([e],[o])=>e.localeCompare(o)))}function S(n){const e={};for(const[o,t]of Object.entries(n))if(t!==void 0){if(o==="priority"){e[o]=String($(t));continue}if(G.has(o)){if(typeof t=="string"){e[o]=[t];continue}if(!Array.isArray(t))continue;const r=t.filter(a=>typeof a=="string");r.length>0&&(e[o]=r);continue}if(typeof t=="string"){e[o]=t;continue}Array.isArray(t)&&t.every(r=>typeof r=="string")&&(e[o]=[...t])}return w(e)}function B(n,e){if(typeof n!="object"||n===null||Array.isArray(n))throw new u(`Template "${e}" has invalid options payload.`,p.GENERIC_FAILURE);const o=n,t={};for(const[r,a]of Object.entries(o)){const s=r.trim();if(s.length===0)throw new u(`Template "${e}" contains an empty option key.`,p.GENERIC_FAILURE);if(typeof a=="string"){t[s]=a;continue}if(Array.isArray(a)&&a.every(l=>typeof l=="string")){t[s]=[...a];continue}throw new u(`Template "${e}" contains invalid value for option "${s}".`,p.GENERIC_FAILURE)}return w(t)}function _(n,e){let o;try{o=JSON.parse(n)}catch{throw new u(`Template "${e}" contains invalid JSON.`,p.GENERIC_FAILURE)}if(typeof o!="object"||o===null||Array.isArray(o))throw new u(`Template "${e}" has invalid document shape.`,p.GENERIC_FAILURE);const t=o,r=B(t.options,e),a=O();return{name:typeof t.name=="string"&&t.name.trim().length>0?t.name.trim():e,created_at:typeof t.created_at=="string"?t.created_at:a,updated_at:typeof t.updated_at=="string"?t.updated_at:a,options:r}}function P(n){const e=C[n];return e?{name:n,created_at:v,updated_at:v,options:w({...e})}:null}async function L(n,e){const o=await I(m(n,e));if(o!==null)return{document:_(o,e),source:"user"};const t=P(e);if(t)return{document:t,source:"builtin"};throw new u(`Template "${e}" not found`,p.NOT_FOUND)}async function k(n,e){const o=await I(m(n,e));if(o===null)throw new u(`Template "${e}" not found`,p.NOT_FOUND);return _(o,e)}async function at(n,e){const o=d(e),{document:t}=await L(n,o);return t.options}async function it(n,e,o){const t=T(process.cwd(),o.path);await E(t);const r=d(n),a=S(e);if(Object.keys(a).length===0)throw new u("templates save requires at least one create option flag",p.USAGE);const s=O(),l=m(t,r);let c=s;await b(l)&&(c=(await k(t,r)).created_at);const i={name:r,created_at:c,updated_at:s,options:a},f=await U(t);return await g.mkdir(y(t),{recursive:!0}),await N({pmRoot:t,filePath:l,raw:`${JSON.stringify(i,null,2)}
26
+ `,op:"templates:save",author:M(void 0,f.author_default),lockTtlSeconds:f.locks.ttl_seconds,lockWaitMs:f.locks.wait_ms}),{name:i.name,created_at:i.created_at,updated_at:i.updated_at,path:l,options:i.options}}async function W(n){const e=y(n);return await b(e)?(await g.readdir(e)).filter(t=>t.toLowerCase().endsWith(h)).map(t=>t.slice(0,-h.length)).filter(t=>R.test(t)):[]}async function st(n){const e=T(process.cwd(),n.path);await E(e);const o=await W(e),t=new Set(o),r=Object.keys(C).filter(c=>!t.has(c)),a=[...o].sort((c,i)=>c.localeCompare(i)),s=[...r].sort((c,i)=>c.localeCompare(i)),l=[...new Set([...a,...s])].sort((c,i)=>c.localeCompare(i));return{templates:l,count:l.length,builtin_templates:s,user_templates:a}}async function ct(n,e){const o=T(process.cwd(),e.path);await E(o);const t=d(n),{document:r,source:a}=await L(o,t);return{name:r.name,source:a,created_at:r.created_at,updated_at:r.updated_at,path:a==="builtin"?`builtin:${t}`:m(o,t),options:r.options}}export{rt as _testOnly,at as loadCreateTemplateOptions,st as runTemplatesList,it as runTemplatesSave,ct as runTemplatesShow};
27
27
  //# sourceMappingURL=templates.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]="bc840a99-3b4c-5386-81e2-5480897f2d19")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{assertLinkedTestCommand}from"./entry.js";import{createLinkedTestSetupGate,isLinkedTestSetup,orderLinkedTestsSetupFirst}from"./run-phases.js";import{isItemRevisionConflict}from"../lifecycle/item-revision.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{parseOptionalNumber}from"../../core/item/parse.js";import{normalizeStatusInput}from"../../core/item/status.js";import{resolveRuntimeStatusRegistry}from"../../core/schema/runtime-schema.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{stableStringify}from"../../core/shared/serialization.js";import{nowIso}from"../../core/shared/time.js";import{listAllItemMetadataLight}from"../../core/store/item-store.js";import{resolveGlobalPmRoot,resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{appendTrackedTestRunSummary}from"../../core/test/item-test-run-tracking.js";import{resolveAuthor}from"../../core/shared/author.js";import{countFailureCategories,runLinkedTests,runTest,summarizeContextPreflight}from"./execution.js";const parseStatus=(raw,statusRegistry)=>{if(raw===void 0)return;const normalized=normalizeStatusInput(raw,statusRegistry);if(!normalized){const allowedStatuses=statusRegistry.definitions.map(definition=>definition.id);throw new PmCliError(`Invalid --status value "${raw}". Allowed: ${allowedStatuses.join(", ")}`,EXIT_CODE.USAGE)}return normalized},parseTimeout=raw=>{if(raw===void 0)return;const parsed=parseOptionalNumber(raw,"timeout");if(parsed<=0)throw new PmCliError("timeout must be a positive number",EXIT_CODE.USAGE);return parsed},parseNonNegativeInteger=(raw,flag)=>{if(raw===void 0)return;const parsed=Number(raw);if(!Number.isInteger(parsed)||parsed<0)throw new PmCliError(`${flag} must be a non-negative integer`,EXIT_CODE.USAGE);return parsed},formatTrackingError=error=>error instanceof Error?error.message:String(error),resolveTrackedRunId=()=>{const fromEnv=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return fromEnv&&fromEnv.length>0?fromEnv:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},normalizeCommand=command=>command.trim().replaceAll(/\s+/g," "),normalizeEnvSetSignature=value=>!value||Object.keys(value).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)))),normalizeEnvClearSignature=value=>!value||value.length===0?"[]":JSON.stringify([...value].sort((left,right)=>left.localeCompare(right))),normalizePmContextModeSignature=value=>{const normalized=value?.trim().toLowerCase();return normalized&&normalized.length>0?normalized:"none"},normalizeWorkspaceContextModeSignature=value=>{const normalized=value?.trim().toLowerCase();return normalized&&normalized.length>0?normalized:"source"},normalizeAssertionStrings=values=>[...new Set(values??[])].sort((left,right)=>left.localeCompare(right)),normalizeAssertionMap=value=>Object.fromEntries(Object.entries(value??{}).sort(([left],[right])=>left.localeCompare(right))),normalizeAssertionLineCount=value=>typeof value=="number"?value:void 0,normalizeAssertionSignature=test=>{const normalized={assert_stdout_contains:normalizeAssertionStrings(test.assert_stdout_contains),assert_stdout_regex:normalizeAssertionStrings(test.assert_stdout_regex),assert_stderr_contains:normalizeAssertionStrings(test.assert_stderr_contains),assert_stderr_regex:normalizeAssertionStrings(test.assert_stderr_regex),assert_stdout_min_lines:normalizeAssertionLineCount(test.assert_stdout_min_lines),assert_json_field_equals:normalizeAssertionMap(test.assert_json_field_equals),assert_json_field_gte:normalizeAssertionMap(test.assert_json_field_gte)};return JSON.stringify(normalized)},resolveLinkedTestTargetSignature=test=>{const command=resolveOptionalEnvironmentValue(test.command);return command!==void 0?`command:${test.scope}:${normalizeCommand(command)}`:`path:${test.scope}:${resolveOptionalEnvironmentValue(test.path)??""}`},buildLinkedTestKey=test=>{const envSet=normalizeEnvSetSignature(test.env_set),envClear=normalizeEnvClearSignature(test.env_clear),pmContextMode=normalizePmContextModeSignature(test.pm_context_mode),workspaceContextMode=normalizeWorkspaceContextModeSignature(test.workspace_context_mode),sharedHostSafe=test.shared_host_safe===!0?"true":"false",assertions=normalizeAssertionSignature(test);return`${resolveLinkedTestTargetSignature(test)}:${envSet}:${envClear}:${pmContextMode}:${workspaceContextMode}:${sharedHostSafe}:${assertions}`},maxTimeoutSeconds=(current,candidate)=>candidate===void 0?current:current===void 0||candidate>current?candidate:current,countStatuses=runResults=>{let passed=0,failed=0,skipped=0;for(const result of runResults){if(result.status==="passed"){passed+=1;continue}if(result.status==="failed"||result.status==="refused"){failed+=1;continue}skipped+=1}return{passed,failed,skipped}},mergeFailureCategoryCounts=(target,source)=>{for(const[key,value]of Object.entries(source))target[key]+=value},emitTestAllProgress=(options,message)=>{if(options.progress===!0)try{process.stderr.write(`[pm test-all] ${message}
2
- `)}catch{}},collectTestAllItemTests=async(filteredItems,global2,pmRoot)=>{const itemTests=[];let linkedTests=0;for(const item of filteredItems){const readResult=await runTest(item.id,{run:!1},{...global2,path:pmRoot});linkedTests+=readResult.tests.length,itemTests.push({item,tests:readResult.tests})}return{itemTests,linkedTests}},selectTestAllItems=async params=>{const statusRegistry=resolveRuntimeStatusRegistry(params.settings.schema),typeRegistry=resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()),statusFilter=parseStatus(params.options.status,statusRegistry),limitFilter=parseNonNegativeInteger(params.options.limit,"--limit"),offsetFilter=parseNonNegativeInteger(params.options.offset,"--offset")??0,statusFilteredItems=(await listAllItemMetadataLight(params.pmRoot,params.settings.item_format,typeRegistry.type_to_folder,void 0,params.settings.schema)).filter(item=>statusFilter?item.status===statusFilter:!0).sort((a,b)=>a.id.localeCompare(b.id));return{filteredItems:limitFilter===void 0?statusFilteredItems.slice(offsetFilter):statusFilteredItems.slice(offsetFilter,offsetFilter+limitFilter),statusFilter,limitFilter,offsetFilter}},resolveSetupSignature=tests=>{const setups=tests.filter(isLinkedTestSetup).map(({provenance:_provenance,provenance_invalid:_invalid,updated_by:_by,updated_at:_at,note:_note,timeout_seconds:_timeout,...definition})=>definition);return setups.length===0?"":stableStringify(setups)},buildTestAllDedupeKey=(test,setupSignature)=>setupSignature.length===0?buildLinkedTestKey(test):`${buildLinkedTestKey(test)}:setup[${setupSignature}]`,buildEffectiveTimeoutByKey=itemTests=>{const effectiveTimeoutByKey=new Map;for(const{tests}of itemTests){const setupSignature=resolveSetupSignature(tests);for(const test of tests){if(isLinkedTestSetup(test))continue;const key=buildTestAllDedupeKey(test,setupSignature);if(!effectiveTimeoutByKey.has(key)){effectiveTimeoutByKey.set(key,test.timeout_seconds);continue}effectiveTimeoutByKey.set(key,maxTimeoutSeconds(effectiveTimeoutByKey.get(key),test.timeout_seconds))}}return effectiveTimeoutByKey};function resolveTestAllCommandRefusal(test,itemId){try{assertLinkedTestCommand(test.command);return}catch(error){if(!(error instanceof PmCliError)||error.code!=="linked_test_command_not_executable")throw error;return{command:test.command,path:test.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${itemId}: ${error.message}`}}}const planTestAllItemEntries=(entry,context)=>{const testsToRun=[],reservedKeys=[],ordered=orderLinkedTestsSetupFirst(entry.tests),setupSignature=resolveSetupSignature(ordered),setupGate=createLinkedTestSetupGate();return{plans:ordered.map(test=>{const setup=isLinkedTestSetup(test),key=setup?buildLinkedTestKey(test):buildTestAllDedupeKey(test,setupSignature),blocked=setupGate.blocked(test);if(blocked)return{test,key,duplicate:!1,refusal:blocked};const refusal=resolveTestAllCommandRefusal(test,entry.item.id);if(refusal)return{test,key,duplicate:!1,refusal:setupGate.record(test,refusal)};if(setup)return testsToRun.push(test),{test,key,duplicate:!1,refusal:void 0};if(context.seenTestKeys.has(key))return{test,key,duplicate:!0,refusal:void 0};context.seenTestKeys.add(key),reservedKeys.push(key);const effectiveTimeoutSeconds=context.effectiveTimeoutByKey.get(key);return testsToRun.push(effectiveTimeoutSeconds===void 0?test:{...test,timeout_seconds:effectiveTimeoutSeconds}),{test,key,duplicate:!1,refusal:void 0}}),testsToRun,reservedKeys}},releaseBlockedReservations=(executedResults,reservedKeys,context)=>{if(executedResults.some(row=>row.phase==="setup"&&row.status!=="passed"))for(const key of reservedKeys)context.seenTestKeys.delete(key)},runTestAllItem=async(entry,context)=>{const{plans:keyedTests,testsToRun,reservedKeys}=planTestAllItemEntries(entry,context),executedResults=testsToRun.length>0?await runLinkedTests(testsToRun,context.defaultTimeoutSeconds,{progress:context.options.progress,sourceRoots:context.sourceRoots,envSet:context.options.envSet,envClear:context.options.envClear,sharedHostSafe:context.options.sharedHostSafe,pmContext:context.options.pmContext,overrideLinkedPmContext:context.options.overrideLinkedPmContext,failOnContextMismatch:context.options.failOnContextMismatch,failOnEmptyTestRun:context.options.failOnEmptyTestRun,requireAssertionsForPm:context.options.requireAssertionsForPm,checkContext:context.options.checkContext,autoPmContext:context.options.autoPmContext,workspaceContext:context.options.workspaceContext,overrideLinkedWorkspaceContext:context.options.overrideLinkedWorkspaceContext,pmRoot:context.pmRoot,allowUntrustedLinkedTests:context.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:context.settings.testing.allow_untrusted_linked_tests}):[];releaseBlockedReservations(executedResults,reservedKeys,context);let executedIndex=0;const runtimeGate=createLinkedTestSetupGate(),runResults=keyedTests.map(({test,key,duplicate,refusal})=>{if(refusal)return runtimeGate.blocked(test)??refusal;if(!duplicate){const executed=executedResults[executedIndex];return executedIndex+=1,runtimeGate.blocked(test)??runtimeGate.record(test,executed)}return runtimeGate.blocked(test)??{command:test.command,path:test.path,status:"skipped",error:`Duplicate linked test skipped (key=${key}).`}}),summary=countStatuses(runResults),failureCategories=countFailureCategories(runResults),trackingWarnings=await appendTestAllItemTracking(entry,summary,runResults,context);return{passed:summary.passed,failed:summary.failed,skipped:summary.skipped,trackingWarnings,failureCategories,result:{ok:summary.failed===0&&!(context.options.failOnSkipped===!0&&summary.skipped>0),id:entry.item.id,status:entry.item.status,test_count:entry.tests.length,passed:summary.passed,failed:summary.failed,skipped:summary.skipped,run_results:runResults,failure_categories:failureCategories}}},trackedRunFailed=(summary,options)=>[summary.failed>0,options.failOnSkipped===!0&&summary.skipped>0].includes(!0),optionalTrue=value=>value?!0:void 0,appendTestAllItemTracking=async(entry,summary,runResults,context)=>{if(!context.trackingEnabled)return[];try{const failed=trackedRunFailed(summary,context.options);await appendTrackedTestRunSummary({pmRoot:context.pmRoot,settings:context.settings,itemId:entry.item.id,author:context.trackingAuthor,message:`Track test-all run summary (${context.trackingRunId})`,entry:{run_id:context.trackingRunId,kind:"test-all",status:failed?"failed":"passed",started_at:context.runStartedAt,finished_at:nowIso(),recorded_at:nowIso(),attempt:context.trackingAttempt,resumed_from:context.trackingResumedFrom,passed:summary.passed,failed:summary.failed,skipped:summary.skipped,items:1,linked_tests:entry.tests.length,fail_on_skipped_triggered:optionalTrue(context.options.failOnSkipped===!0&&summary.skipped>0),executions:runResults.filter(result=>result.command?.trim()).slice(0,32).map(result=>({command:result.command.trim(),requested_pm_context_mode:result.execution_context?.requested_pm_context_mode,pm_context_mode:result.execution_context?.pm_context_mode,workspace_context_mode:result.execution_context?.workspace_context_mode,trust_reason:result.execution_context?.trust.reason}))}})}catch(error){return isItemRevisionConflict(error)?(context.revisionConflicts.push(error),[]):[`test_result_tracking_failed:${entry.item.id}:${formatTrackingError(error)}`]}return[]},resolveTrackingAttempt=()=>{const raw=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),parsed=raw?Number.parseInt(raw,10):Number.NaN;return Number.isFinite(parsed)&&parsed>=1?parsed:void 0},resolveOptionalEnvironmentValue=value=>{const trimmed=value?.trim();return trimmed&&trimmed.length>0?trimmed:void 0},buildTestAllItemRunContext=params=>({pmRoot:params.pmRoot,settings:params.settings,options:params.options,defaultTimeoutSeconds:params.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:params.pmRoot,globalPmRoot:resolveGlobalPmRoot(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:buildEffectiveTimeoutByKey(params.itemTests),trackingEnabled:params.settings.testing.record_results_to_items===!0,trackingAuthor:resolveAuthor(params.options.author,params.settings.author_default),trackingRunId:resolveTrackedRunId(),trackingAttempt:resolveTrackingAttempt(),trackingResumedFrom:resolveOptionalEnvironmentValue(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:params.runStartedAt,revisionConflicts:[]}),initializeTestAllAccumulation=(options,linkedTests,filteredItems)=>{const accumulation={results:[],passed:0,failed:0,skipped:0,failureCategories:countFailureCategories([]),trackingWarnings:[]},failOnEmptyTestRunTriggered=options.failOnEmptyTestRun===!0&&linkedTests===0;return failOnEmptyTestRunTriggered&&(accumulation.failed+=1,accumulation.failureCategories.empty_run+=1,accumulation.trackingWarnings.push(`empty_linked_test_selection:items=${filteredItems.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation,failOnEmptyTestRunTriggered}},runTestAllItems=async(itemTests,context,accumulation)=>{for(const[itemIndex,entry]of itemTests.entries()){emitTestAllProgress(context.options,`item ${itemIndex+1}/${itemTests.length} start id=${entry.item.id} linked_tests=${entry.tests.length}`);const execution=await runTestAllItem(entry,context);mergeFailureCategoryCounts(accumulation.failureCategories,execution.failureCategories),accumulation.passed+=execution.passed,accumulation.failed+=execution.failed,accumulation.skipped+=execution.skipped,accumulation.trackingWarnings.push(...execution.trackingWarnings),accumulation.results.push(execution.result),emitTestAllProgress(context.options,`item ${itemIndex+1}/${itemTests.length} end id=${entry.item.id} status=${execution.failed===0?"passed":"failed"} passed=${execution.passed} failed=${execution.failed} skipped=${execution.skipped}`)}const[conflict]=context.revisionConflicts;if(conflict!==void 0)throw conflict},appendContextPreflightWarning=(options,accumulation)=>{if(options.checkContext!==!0)return;const allRunResults=accumulation.results.flatMap(entry=>entry.run_results),preflight=summarizeContextPreflight(allRunResults);accumulation.trackingWarnings.push(`context_preflight:checked_pm_commands=${preflight.checked_pm_commands};tracker_read_commands=${preflight.tracker_read_commands};mismatches=${preflight.mismatches};auto_remediated=${preflight.auto_remediated}`)},buildTestAllResult=params=>({ok:params.ok,totals:{items:params.filteredItems.length,linked_tests:params.linkedTests,passed:params.accumulation.passed,failed:params.accumulation.failed,skipped:params.accumulation.skipped,failure_categories:params.accumulation.failureCategories},failed:params.accumulation.failed,passed:params.accumulation.passed,skipped:params.accumulation.skipped,fail_on_skipped_triggered:params.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:params.failOnEmptyTestRunTriggered?!0:void 0,warnings:params.accumulation.trackingWarnings.length>0?params.accumulation.trackingWarnings:void 0,results:params.accumulation.results}),buildTestAllSelectionProgress=params=>[`selection items=${params.filteredItems.length}`,`linked_tests=${params.linkedTests}`,params.statusFilter===void 0?"":`status=${params.statusFilter}`,params.limitFilter===void 0?"":`limit=${params.limitFilter}`,params.offsetFilter>0?`offset=${params.offsetFilter}`:""].filter(entry=>entry.length>0).join(" "),prepareTestAllRun=async(options,global2)=>{const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),selection=await selectTestAllItems({pmRoot,settings,options}),defaultTimeoutSeconds=parseTimeout(options.timeout),runStartedAt=nowIso(),collected=await collectTestAllItemTests(selection.filteredItems,global2,pmRoot);return emitTestAllProgress(options,buildTestAllSelectionProgress({...selection,linkedTests:collected.linkedTests})),{pmRoot,settings,filteredItems:selection.filteredItems,itemTests:collected.itemTests,linkedTests:collected.linkedTests,defaultTimeoutSeconds,runStartedAt}},resolveTestAllOutcome=params=>{const failOnSkippedTriggered=params.options.failOnSkipped===!0&&params.accumulation.skipped>0,ok=![params.accumulation.failed>0,failOnSkippedTriggered,params.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered,ok}},runTestAll=async(options,global2)=>{const prepared=await prepareTestAllRun(options,global2),{accumulation,failOnEmptyTestRunTriggered}=initializeTestAllAccumulation(options,prepared.linkedTests,prepared.filteredItems),itemRunContext=buildTestAllItemRunContext({pmRoot:prepared.pmRoot,settings:prepared.settings,options,itemTests:prepared.itemTests,defaultTimeoutSeconds:prepared.defaultTimeoutSeconds,runStartedAt:prepared.runStartedAt});await runTestAllItems(prepared.itemTests,itemRunContext,accumulation),appendContextPreflightWarning(options,accumulation);const outcome=resolveTestAllOutcome({options,accumulation,failOnEmptyTestRunTriggered});return emitTestAllProgress(options,`end status=${outcome.ok?"passed":"failed"} items=${prepared.filteredItems.length} linked_tests=${prepared.linkedTests} passed=${accumulation.passed} failed=${accumulation.failed} skipped=${accumulation.skipped}`),buildTestAllResult({ok:outcome.ok,filteredItems:prepared.filteredItems,linkedTests:prepared.linkedTests,accumulation,failOnSkippedTriggered:outcome.failOnSkippedTriggered,failOnEmptyTestRunTriggered})},_testOnlyTestAll={buildLinkedTestKey,buildEffectiveTimeoutByKey,formatTrackingError};export{_testOnlyTestAll,runTestAll};
1
+ import{assertInitializedTracker as x}from"../environment/tracker-preflight.js";import{assertLinkedTestCommand as F}from"./entry.js";import{createLinkedTestSetupGate as y,isLinkedTestSetup as T,orderLinkedTestsSetupFirst as L}from"./run-phases.js";import{isItemRevisionConflict as N}from"../lifecycle/item-revision.js";import{getActiveExtensionRegistrations as z}from"../../core/extensions/index.js";import{resolveItemTypeRegistry as M}from"../../core/item/type-registry.js";import{parseOptionalNumber as K}from"../../core/item/parse.js";import{normalizeStatusInput as j}from"../../core/item/status.js";import{resolveRuntimeStatusRegistry as U}from"../../core/schema/runtime-schema.js";import{EXIT_CODE as h}from"../../core/shared/constants.js";import{PmCliError as p}from"../../core/shared/errors.js";import{stableStringify as W}from"../../core/shared/serialization.js";import{nowIso as S}from"../../core/shared/time.js";import{listAllItemMetadataLight as G}from"../../core/store/item-store.js";import{resolveGlobalPmRoot as D,resolvePmRoot as B}from"../../core/store/paths.js";import{readSettings as q}from"../../core/store/settings.js";import{appendTrackedTestRunSummary as H}from"../../core/test/item-test-run-tracking.js";import{resolveAuthor as J}from"../../core/shared/author.js";import{countFailureCategories as $,runLinkedTests as V,runTest as X,summarizeContextPreflight as Q}from"./execution.js";const Y=(e,t)=>{if(e===void 0)return;const s=j(e,t);if(!s){const n=t.definitions.map(i=>i.id);throw new p(`Invalid --status value "${e}". Allowed: ${n.join(", ")}`,h.USAGE)}return s},Z=e=>{if(e===void 0)return;const t=K(e,"timeout");if(t<=0)throw new p("timeout must be a positive number",h.USAGE);return t},v=(e,t)=>{if(e===void 0)return;const s=Number(e);if(!Number.isInteger(s)||s<0)throw new p(`${t} must be a non-negative integer`,h.USAGE);return s},A=e=>e instanceof Error?e.message:String(e),ee=()=>{const e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},te=e=>e.trim().replaceAll(/\s+/g," "),se=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[s])=>t.localeCompare(s)))),ne=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,s)=>t.localeCompare(s))),ie=e=>{const t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},oe=e=>{const t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},g=e=>[...new Set(e??[])].sort((t,s)=>t.localeCompare(s)),I=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[s])=>t.localeCompare(s))),re=e=>typeof e=="number"?e:void 0,de=e=>{const t={assert_stdout_contains:g(e.assert_stdout_contains),assert_stdout_regex:g(e.assert_stdout_regex),assert_stderr_contains:g(e.assert_stderr_contains),assert_stderr_regex:g(e.assert_stderr_regex),assert_stdout_min_lines:re(e.assert_stdout_min_lines),assert_json_field_equals:I(e.assert_json_field_equals),assert_json_field_gte:I(e.assert_json_field_gte)};return JSON.stringify(t)},ae=e=>{const t=R(e.command);return t!==void 0?`command:${e.scope}:${te(t)}`:`path:${e.scope}:${R(e.path)??""}`},_=e=>{const t=se(e.env_set),s=ne(e.env_clear),n=ie(e.pm_context_mode),i=oe(e.workspace_context_mode),o=e.shared_host_safe===!0?"true":"false",r=de(e);return`${ae(e)}:${t}:${s}:${n}:${i}:${o}:${r}`},le=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,ue=e=>{let t=0,s=0,n=0;for(const i of e){if(i.status==="passed"){t+=1;continue}if(i.status==="failed"||i.status==="refused"){s+=1;continue}n+=1}return{passed:t,failed:s,skipped:n}},ce=(e,t)=>{for(const[s,n]of Object.entries(t))e[s]+=n},k=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
2
+ `)}catch{}},me=async(e,t,s)=>{const n=[];let i=0;for(const o of e){const r=await X(o.id,{run:!1},{...t,path:s});i+=r.tests.length,n.push({item:o,tests:r.tests})}return{itemTests:n,linkedTests:i}},fe=async e=>{const t=U(e.settings.schema),s=M(e.settings,z()),n=Y(e.options.status,t),i=v(e.options.limit,"--limit"),o=v(e.options.offset,"--offset")??0,u=(await G(e.pmRoot,e.settings.item_format,s.type_to_folder,void 0,e.settings.schema)).filter(a=>n?a.status===n:!0).sort((a,l)=>a.id.localeCompare(l.id));return{filteredItems:i===void 0?u.slice(o):u.slice(o,o+i),statusFilter:n,limitFilter:i,offsetFilter:o}},w=e=>{const t=e.filter(T).map(({provenance:s,provenance_invalid:n,updated_by:i,updated_at:o,note:r,timeout_seconds:u,...d})=>d);return t.length===0?"":W(t)},b=(e,t)=>t.length===0?_(e):`${_(e)}:setup[${t}]`,O=e=>{const t=new Map;for(const{tests:s}of e){const n=w(s);for(const i of s){if(T(i))continue;const o=b(i,n);if(!t.has(o)){t.set(o,i.timeout_seconds);continue}t.set(o,le(t.get(o),i.timeout_seconds))}}return t};function pe(e,t){try{F(e.command);return}catch(s){if(!(s instanceof p)||s.code!=="linked_test_command_not_executable")throw s;return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${t}: ${s.message}`}}}const ge=(e,t)=>{const s=[],n=[],i=L(e.tests),o=w(i),r=y();return{plans:i.map(d=>{const a=T(d),l=a?_(d):b(d,o),m=r.blocked(d);if(m)return{test:d,key:l,duplicate:!1,refusal:m};const c=pe(d,e.item.id);if(c)return{test:d,key:l,duplicate:!1,refusal:r.record(d,c)};if(a)return s.push(d),{test:d,key:l,duplicate:!1,refusal:void 0};if(t.seenTestKeys.has(l))return{test:d,key:l,duplicate:!0,refusal:void 0};t.seenTestKeys.add(l),n.push(l);const f=t.effectiveTimeoutByKey.get(l);return s.push(f===void 0?d:{...d,timeout_seconds:f}),{test:d,key:l,duplicate:!1,refusal:void 0}}),testsToRun:s,reservedKeys:n}},_e=(e,t,s)=>{if(e.some(n=>n.phase==="setup"&&n.status!=="passed"))for(const n of t)s.seenTestKeys.delete(n)},ke=async(e,t)=>{const{plans:s,testsToRun:n,reservedKeys:i}=ge(e,t),o=n.length>0?await V(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[];_e(o,i,t);let r=0;const u=y(),d=s.map(({test:c,key:f,duplicate:E,refusal:C})=>{if(C)return u.blocked(c)??C;if(!E){const P=o[r];return r+=1,u.blocked(c)??u.record(c,P)}return u.blocked(c)??{command:c.command,path:c.path,status:"skipped",error:`Duplicate linked test skipped (key=${f}).`}}),a=ue(d),l=$(d),m=await Se(e,a,d,t);return{passed:a.passed,failed:a.failed,skipped:a.skipped,trackingWarnings:m,failureCategories:l,result:{ok:a.failed===0&&!(t.options.failOnSkipped===!0&&a.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:a.passed,failed:a.failed,skipped:a.skipped,run_results:d,failure_categories:l}}},Te=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),he=e=>e?!0:void 0,Se=async(e,t,s,n)=>{if(!n.trackingEnabled)return[];try{const i=Te(t,n.options);await H({pmRoot:n.pmRoot,settings:n.settings,itemId:e.item.id,author:n.trackingAuthor,message:`Track test-all run summary (${n.trackingRunId})`,entry:{run_id:n.trackingRunId,kind:"test-all",status:i?"failed":"passed",started_at:n.runStartedAt,finished_at:S(),recorded_at:S(),attempt:n.trackingAttempt,resumed_from:n.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:he(n.options.failOnSkipped===!0&&t.skipped>0),executions:s.filter(o=>o.command?.trim()).slice(0,32).map(o=>({command:o.command.trim(),requested_pm_context_mode:o.execution_context?.requested_pm_context_mode,pm_context_mode:o.execution_context?.pm_context_mode,workspace_context_mode:o.execution_context?.workspace_context_mode,trust_reason:o.execution_context?.trust.reason}))}})}catch(i){return N(i)?(n.revisionConflicts.push(i),[]):[`test_result_tracking_failed:${e.item.id}:${A(i)}`]}return[]},Re=()=>{const e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},R=e=>{const t=e?.trim();return t&&t.length>0?t:void 0},Ce=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:D(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:O(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:J(e.options.author,e.settings.author_default),trackingRunId:ee(),trackingAttempt:Re(),trackingResumedFrom:R(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),ye=(e,t,s)=>{const n={results:[],passed:0,failed:0,skipped:0,failureCategories:$([]),trackingWarnings:[]},i=e.failOnEmptyTestRun===!0&&t===0;return i&&(n.failed+=1,n.failureCategories.empty_run+=1,n.trackingWarnings.push(`empty_linked_test_selection:items=${s.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:n,failOnEmptyTestRunTriggered:i}},$e=async(e,t,s)=>{for(const[i,o]of e.entries()){k(t.options,`item ${i+1}/${e.length} start id=${o.item.id} linked_tests=${o.tests.length}`);const r=await ke(o,t);ce(s.failureCategories,r.failureCategories),s.passed+=r.passed,s.failed+=r.failed,s.skipped+=r.skipped,s.trackingWarnings.push(...r.trackingWarnings),s.results.push(r.result),k(t.options,`item ${i+1}/${e.length} end id=${o.item.id} status=${r.failed===0?"passed":"failed"} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`)}const[n]=t.revisionConflicts;if(n!==void 0)throw n},ve=(e,t)=>{if(e.checkContext!==!0)return;const s=t.results.flatMap(i=>i.run_results),n=Q(s);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${n.checked_pm_commands};tracker_read_commands=${n.tracker_read_commands};mismatches=${n.mismatches};auto_remediated=${n.auto_remediated}`)},Ae=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),Ie=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),we=async(e,t)=>{const s=B(process.cwd(),t.path);await x(s);const n=await q(s),i=await fe({pmRoot:s,settings:n,options:e}),o=Z(e.timeout),r=S(),u=await me(i.filteredItems,t,s);return k(e,Ie({...i,linkedTests:u.linkedTests})),{pmRoot:s,settings:n,filteredItems:i.filteredItems,itemTests:u.itemTests,linkedTests:u.linkedTests,defaultTimeoutSeconds:o,runStartedAt:r}},be=e=>{const t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,s=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:s}},Ve=async(e,t)=>{const s=await we(e,t),{accumulation:n,failOnEmptyTestRunTriggered:i}=ye(e,s.linkedTests,s.filteredItems),o=Ce({pmRoot:s.pmRoot,settings:s.settings,options:e,itemTests:s.itemTests,defaultTimeoutSeconds:s.defaultTimeoutSeconds,runStartedAt:s.runStartedAt});await $e(s.itemTests,o,n),ve(e,n);const r=be({options:e,accumulation:n,failOnEmptyTestRunTriggered:i});return k(e,`end status=${r.ok?"passed":"failed"} items=${s.filteredItems.length} linked_tests=${s.linkedTests} passed=${n.passed} failed=${n.failed} skipped=${n.skipped}`),Ae({ok:r.ok,filteredItems:s.filteredItems,linkedTests:s.linkedTests,accumulation:n,failOnSkippedTriggered:r.failOnSkippedTriggered,failOnEmptyTestRunTriggered:i})},Xe={buildLinkedTestKey:_,buildEffectiveTimeoutByKey:O,formatTrackingError:A};export{Xe as _testOnlyTestAll,Ve as runTestAll};
3
3
  //# sourceMappingURL=batch.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]="96013340-cb63-5e96-a1b0-b810100ab080")}catch{}})();function pushOptionalValueFlag(args,flag,value){if(typeof value!="string")return;const trimmed=value.trim();trimmed.length!==0&&args.push(flag,trimmed)}function pushOptionalBooleanFlag(args,flag,value){value===!0&&args.push(flag)}function pushRepeatableValueFlag(args,flag,values){if(Array.isArray(values))for(const value of values){if(typeof value!="string")continue;const trimmed=value.trim();trimmed.length!==0&&args.push(flag,trimmed)}}function buildBackgroundTestCommandArgs(id,options){const args=["test",id,"--run","--json","--progress"];return pushRepeatableValueFlag(args,"--add",options.add),pushRepeatableValueFlag(args,"--add-json",options.addJson),pushRepeatableValueFlag(args,"--remove",options.remove),pushRepeatableValueFlag(args,"--remove-index",Array.isArray(options.removeIndex)?options.removeIndex.map(index=>typeof index=="number"?String(index):index):options.removeIndex),pushOptionalValueFlag(args,"--match",options.match),pushOptionalValueFlag(args,"--only-index",typeof options.onlyIndex=="number"?String(options.onlyIndex):options.onlyIndex),pushOptionalBooleanFlag(args,"--only-last",options.onlyLast),pushOptionalBooleanFlag(args,"--full-history",options.fullHistory),pushRepeatableValueFlag(args,"--measure",options.measure),pushOptionalValueFlag(args,"--metric-below",options.metricBelow),pushOptionalValueFlag(args,"--metric-diff",options.metricDiff),pushSharedBackgroundTestCommandArgs(args,options),pushOptionalValueFlag(args,"--author",options.author),pushOptionalValueFlag(args,"--message",options.message),pushOptionalBooleanFlag(args,"--force",options.force),args}function pushSharedBackgroundTestCommandArgs(args,options){pushOptionalValueFlag(args,"--timeout",options.timeout),pushRepeatableValueFlag(args,"--env-set",options.envSet),pushRepeatableValueFlag(args,"--env-clear",options.envClear),pushOptionalBooleanFlag(args,"--shared-host-safe",options.sharedHostSafe),pushOptionalValueFlag(args,"--pm-context",options.pmContext),pushOptionalBooleanFlag(args,"--override-linked-pm-context",options.overrideLinkedPmContext),pushOptionalValueFlag(args,"--workspace-context",options.workspaceContext),pushOptionalBooleanFlag(args,"--override-linked-workspace-context",options.overrideLinkedWorkspaceContext),pushOptionalBooleanFlag(args,"--allow-untrusted-linked-tests",options.allowUntrustedLinkedTests),pushOptionalBooleanFlag(args,"--fail-on-context-mismatch",options.failOnContextMismatch),pushOptionalBooleanFlag(args,"--fail-on-skipped",options.failOnSkipped),pushOptionalBooleanFlag(args,"--fail-on-empty-test-run",options.failOnEmptyTestRun),pushOptionalBooleanFlag(args,"--require-assertions-for-pm",options.requireAssertionsForPm),pushOptionalBooleanFlag(args,"--check-context",options.checkContext),pushOptionalBooleanFlag(args,"--full-output",options.fullOutput),pushOptionalBooleanFlag(args,"--auto-pm-context",options.autoPmContext)}function buildBackgroundTestAllCommandArgs(options){const args=["test-all","--json","--progress"];return pushOptionalValueFlag(args,"--status",options.status),pushOptionalValueFlag(args,"--limit",options.limit),pushOptionalValueFlag(args,"--offset",options.offset),pushSharedBackgroundTestCommandArgs(args,options),args}export{buildBackgroundTestAllCommandArgs,buildBackgroundTestCommandArgs};
1
+ function u(t,e,r){if(typeof r!="string")return;const l=r.trim();l.length!==0&&t.push(e,l)}function n(t,e,r){r===!0&&t.push(e)}function a(t,e,r){if(Array.isArray(r))for(const l of r){if(typeof l!="string")continue;const m=l.trim();m.length!==0&&t.push(e,m)}}function d(t,e){const r=["test",t,"--run","--json","--progress"];return a(r,"--add",e.add),a(r,"--add-json",e.addJson),a(r,"--remove",e.remove),a(r,"--remove-index",Array.isArray(e.removeIndex)?e.removeIndex.map(l=>typeof l=="number"?String(l):l):e.removeIndex),u(r,"--match",e.match),u(r,"--only-index",typeof e.onlyIndex=="number"?String(e.onlyIndex):e.onlyIndex),n(r,"--only-last",e.onlyLast),n(r,"--full-history",e.fullHistory),a(r,"--measure",e.measure),u(r,"--metric-below",e.metricBelow),u(r,"--metric-diff",e.metricDiff),c(r,e),u(r,"--author",e.author),u(r,"--message",e.message),n(r,"--force",e.force),r}function c(t,e){u(t,"--timeout",e.timeout),a(t,"--env-set",e.envSet),a(t,"--env-clear",e.envClear),n(t,"--shared-host-safe",e.sharedHostSafe),u(t,"--pm-context",e.pmContext),n(t,"--override-linked-pm-context",e.overrideLinkedPmContext),u(t,"--workspace-context",e.workspaceContext),n(t,"--override-linked-workspace-context",e.overrideLinkedWorkspaceContext),n(t,"--allow-untrusted-linked-tests",e.allowUntrustedLinkedTests),n(t,"--fail-on-context-mismatch",e.failOnContextMismatch),n(t,"--fail-on-skipped",e.failOnSkipped),n(t,"--fail-on-empty-test-run",e.failOnEmptyTestRun),n(t,"--require-assertions-for-pm",e.requireAssertionsForPm),n(t,"--check-context",e.checkContext),n(t,"--full-output",e.fullOutput),n(t,"--auto-pm-context",e.autoPmContext)}function f(t){const e=["test-all","--json","--progress"];return u(e,"--status",t.status),u(e,"--limit",t.limit),u(e,"--offset",t.offset),c(e,t),e}export{f as buildBackgroundTestAllCommandArgs,d as buildBackgroundTestCommandArgs};
2
2
  //# sourceMappingURL=command-args.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]="b42f8889-4b5a-5391-b8e4-b68084e20a49")}catch{}})();import{execFile}from"node:child_process";import{constants}from"node:fs";import{access,open}from"node:fs/promises";import path from"node:path";import{promisify}from"node:util";import{isFileAbsentError}from"../../core/fs/fs-utils.js";const execFileAsync=promisify(execFile);function leadingExecutable(command){const match=command.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),executable=match?.[1]??match?.[2]??match?.[3];return executable&&!/[$`%&|<>^;]/u.test(executable)?executable:void 0}function shellReportsMissing(executable,code,stderr){return process.platform==="win32"?(code===1||code===9009)&&stderr.split(/\r?\n/u).some(line=>line.trim()===`'${executable}' is not recognized as an internal or external command,`):code!==126&&code!==127?!1:stderr.split(/\r?\n/u).some(line=>code===127&&(line.endsWith(`: ${executable}: not found`)||line.endsWith(`: ${executable}: command not found`))||code===126&&line.includes(`: ${executable}: `)&&line.endsWith(": bad interpreter: No such file or directory"))}async function hasAbsentScriptInterpreter(resolved,cwd){const filename=resolved.trim();if(!filename||/[\r\n]/u.test(filename))return!1;try{const file=await open(path.resolve(cwd,filename),constants.O_RDONLY|constants.O_NONBLOCK);let header;try{const buffer=Buffer.alloc(256),{bytesRead}=await file.read(buffer,0,buffer.length,0);if(header=buffer.toString("utf8",0,bytesRead),bytesRead===buffer.length&&!header.includes(`
2
- `))return!1}finally{await file.close()}const interpreter=header.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!interpreter)return!1;try{return await access(interpreter),!1}catch(error){return isFileAbsentError(error)}}catch{return!1}}async function detectLinkedTestCommandNotFound(command,result,env,cwd){if(/[;&|<>()`$\r\n]/u.test(command))return!1;const executable=leadingExecutable(command);if(!executable||!shellReportsMissing(executable,result.exitCode,result.stderr))return!1;const windows=process.platform==="win32",resolver=windows?path.join(env.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",args=windows?[executable]:["-c",'command -v "$1"',"pm-linked-test-resolution",executable];try{const{stdout}=await execFileAsync(resolver,args,{env,cwd,timeout:1e3,windowsHide:!0});return!windows&&hasAbsentScriptInterpreter(stdout,cwd)}catch(error){const failure=error;if(failure.killed||failure.signal)return!1;const code=failure.code;return code===1||!windows&&code===127}}export{detectLinkedTestCommandNotFound};
1
+ import{execFile as d}from"node:child_process";import{constants as l}from"node:fs";import{access as p,open as h}from"node:fs/promises";import m from"node:path";import{promisify as w}from"node:util";import{isFileAbsentError as y}from"../../core/fs/fs-utils.js";const $=w(d);function g(n){const t=n.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),e=t?.[1]??t?.[2]??t?.[3];return e&&!/[$`%&|<>^;]/u.test(e)?e:void 0}function b(n,t,e){return process.platform==="win32"?(t===1||t===9009)&&e.split(/\r?\n/u).some(r=>r.trim()===`'${n}' is not recognized as an internal or external command,`):t!==126&&t!==127?!1:e.split(/\r?\n/u).some(r=>t===127&&(r.endsWith(`: ${n}: not found`)||r.endsWith(`: ${n}: command not found`))||t===126&&r.includes(`: ${n}: `)&&r.endsWith(": bad interpreter: No such file or directory"))}async function x(n,t){const e=n.trim();if(!e||/[\r\n]/u.test(e))return!1;try{const r=await h(m.resolve(t,e),l.O_RDONLY|l.O_NONBLOCK);let s;try{const o=Buffer.alloc(256),{bytesRead:a}=await r.read(o,0,o.length,0);if(s=o.toString("utf8",0,a),a===o.length&&!s.includes(`
2
+ `))return!1}finally{await r.close()}const i=s.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!i)return!1;try{return await p(i),!1}catch(o){return y(o)}}catch{return!1}}async function W(n,t,e,r){if(/[;&|<>()`$\r\n]/u.test(n))return!1;const s=g(n);if(!s||!b(s,t.exitCode,t.stderr))return!1;const i=process.platform==="win32",o=i?m.join(e.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",a=i?[s]:["-c",'command -v "$1"',"pm-linked-test-resolution",s];try{const{stdout:c}=await $(o,a,{env:e,cwd:r,timeout:1e3,windowsHide:!0});return!i&&x(c,r)}catch(c){const f=c;if(f.killed||f.signal)return!1;const u=f.code;return u===1||!i&&u===127}}export{W as detectLinkedTestCommandNotFound};
3
3
  //# sourceMappingURL=command-resolution.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]="d1a6d08a-65cd-5403-a43d-57c0ea1815a1")}catch{}})();import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{looksLikeStructuredKeyValueEntry}from"../../core/item/parse.js";import{renderPmCommand}from"../command-line.js";function admitLinkedTestRequest(validate){try{return validate()}catch(error){throw!(error instanceof PmCliError)||error.exitCode!==EXIT_CODE.USAGE?error:new PmCliError(`${error.message} No changes were made.`,EXIT_CODE.USAGE,{...error.context,code:error.code==="linked_test_command_not_executable"?error.code:"invalid_argument_value",reason:"test_option_invalid",changed:!1,required:error.context.required??error.message})}}function quotedAssignmentValueEnd(input,start){if(input[start]==="'"){const closing=input.indexOf("'",start+1);return closing<0?void 0:closing+1}for(let offset=start+1;offset<input.length;offset+=1){if(input[offset]==='"')return offset+1;if(input[offset]==="\\"){offset+=1;continue}if(input[offset]==="`"||input.startsWith("$(",offset))return}}function assignmentValueEnd(input,start){let offset=start;for(;offset<input.length;){const character=input[offset];if(/\s/u.test(character)||";&|".includes(character))return offset;if(character==="\\"){offset+=2;continue}if(character==="'"||character==='"'){const end=quotedAssignmentValueEnd(input,offset);if(end===void 0)return;offset=end;continue}if("<>()`".includes(character))return;offset+=1}return offset===input.length?offset:void 0}function skipAssignmentTrivia(input,start){let offset=start;for(;offset<input.length;){if(/\s/u.test(input[offset])){offset+=1;continue}if(input[offset]!=="#")return offset;const newline=input.indexOf(`
2
- `,offset);if(newline<0)return input.length;offset=newline+1}return offset}function assignmentListNextOffset(input,start){let offset=skipAssignmentTrivia(input,start);const separator=input[offset];return separator===void 0||!";&|".includes(separator)?offset:(offset+=1,separator!==";"&&input[offset]===separator&&(offset+=1),skipAssignmentTrivia(input,offset))}function isAssignmentOnlyCommand(command){const input=command.trim();let offset=skipAssignmentTrivia(input,0);if(input.length===0)return!1;for(;offset<input.length;){if(!/[A-Za-z_]/u.test(input[offset]))return!1;let nameEnd=offset+1;for(;nameEnd<input.length&&/[A-Za-z0-9_]/u.test(input[nameEnd]);)nameEnd+=1;if(input[nameEnd]!=="=")return!1;const end=assignmentValueEnd(input,nameEnd+1);if(end===void 0)return!1;offset=assignmentListNextOffset(input,end)}return!0}function assertLinkedTestCommand(command){if(!(command===void 0||!isAssignmentOnlyCommand(command)))throw new PmCliError("Linked-test command contains only variable assignments or comments and has no executable command.",EXIT_CODE.USAGE,{code:"linked_test_command_not_executable",required:'Supply an actual test command with --add "command=<actual command>" or --add-json. Environment assignments may precede that command.',examples:['pm test <id> --add "command=node --version"'],nextSteps:["Remove any already-stored assignment-only entry with --remove-index, then register the actual test command."]})}function assertLinkedTestContext(test){if(assertLinkedTestCommand(test.command),!(test.pm_context_mode!=="none"||test.workspace_context_mode==="isolated"||test.workspace_context_mode==="snapshot"))throw new PmCliError("pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.",EXIT_CODE.USAGE,{code:"linked_test_context_invalid",required:"Set workspace_context_mode to isolated or snapshot when pm_context_mode is none.",examples:[renderPmCommand(["test","<id>","--add-json",JSON.stringify({command:test.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}function linkedTestsHaveSameIdentity(left,right){return left.command===right.command&&left.path===right.path&&left.scope===right.scope&&left.pm_context_mode===right.pm_context_mode&&left.workspace_context_mode===right.workspace_context_mode}const STRUCTURED_LINKED_TEST_KEYS=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note","phase"],STRUCTURED_LINKED_TEST_KEY_SET=new Set(STRUCTURED_LINKED_TEST_KEYS);function looksLikeStructuredLinkedTestEntry(raw){return looksLikeStructuredKeyValueEntry(raw,STRUCTURED_LINKED_TEST_KEYS)}function normalizeStructuredLinkedTestEntry(kv,optionName){const normalizedKv={},unknownKeys=[];for(const[key,value]of Object.entries(kv)){const normalizedKey=key.toLowerCase();if(!STRUCTURED_LINKED_TEST_KEY_SET.has(normalizedKey)){unknownKeys.push(key);continue}if(Object.hasOwn(normalizedKv,normalizedKey))throw new PmCliError(`${optionName} provides key "${key}" more than once after case normalization`,EXIT_CODE.USAGE);normalizedKv[normalizedKey]=value}if(unknownKeys.length>0)throw new PmCliError(`${optionName} does not recognize key${unknownKeys.length>1?"s":""} ${unknownKeys.map(key=>`"${key}"`).join(", ")}. Allowed keys: ${STRUCTURED_LINKED_TEST_KEYS.join(", ")}.`,EXIT_CODE.USAGE);if(normalizedKv.cmd!==void 0){if(normalizedKv.command!==void 0&&normalizedKv.command.trim()!==normalizedKv.cmd.trim())throw new PmCliError(`${optionName} command and cmd must match when both are provided`,EXIT_CODE.USAGE);const{cmd,...rest}=normalizedKv;return{...rest,command:rest.command??cmd}}return normalizedKv}export{STRUCTURED_LINKED_TEST_KEYS,admitLinkedTestRequest,assertLinkedTestCommand,assertLinkedTestContext,linkedTestsHaveSameIdentity,looksLikeStructuredLinkedTestEntry,normalizeStructuredLinkedTestEntry};
1
+ import{EXIT_CODE as s}from"../../core/shared/constants.js";import{PmCliError as d}from"../../core/shared/errors.js";import{looksLikeStructuredKeyValueEntry as u}from"../../core/item/parse.js";import{renderPmCommand as f}from"../command-line.js";function S(n){try{return n()}catch(t){throw!(t instanceof d)||t.exitCode!==s.USAGE?t:new d(`${t.message} No changes were made.`,s.USAGE,{...t.context,code:t.code==="linked_test_command_not_executable"?t.code:"invalid_argument_value",reason:"test_option_invalid",changed:!1,required:t.context.required??t.message})}}function _(n,t){if(n[t]==="'"){const e=n.indexOf("'",t+1);return e<0?void 0:e+1}for(let e=t+1;e<n.length;e+=1){if(n[e]==='"')return e+1;if(n[e]==="\\"){e+=1;continue}if(n[e]==="`"||n.startsWith("$(",e))return}}function l(n,t){let e=t;for(;e<n.length;){const o=n[e];if(/\s/u.test(o)||";&|".includes(o))return e;if(o==="\\"){e+=2;continue}if(o==="'"||o==='"'){const r=_(n,e);if(r===void 0)return;e=r;continue}if("<>()`".includes(o))return;e+=1}return e===n.length?e:void 0}function c(n,t){let e=t;for(;e<n.length;){if(/\s/u.test(n[e])){e+=1;continue}if(n[e]!=="#")return e;const o=n.indexOf(`
2
+ `,e);if(o<0)return n.length;e=o+1}return e}function h(n,t){let e=c(n,t);const o=n[e];return o===void 0||!";&|".includes(o)?e:(e+=1,o!==";"&&n[e]===o&&(e+=1),c(n,e))}function x(n){const t=n.trim();let e=c(t,0);if(t.length===0)return!1;for(;e<t.length;){if(!/[A-Za-z_]/u.test(t[e]))return!1;let o=e+1;for(;o<t.length&&/[A-Za-z0-9_]/u.test(t[o]);)o+=1;if(t[o]!=="=")return!1;const r=l(t,o+1);if(r===void 0)return!1;e=h(t,r)}return!0}function w(n){if(!(n===void 0||!x(n)))throw new d("Linked-test command contains only variable assignments or comments and has no executable command.",s.USAGE,{code:"linked_test_command_not_executable",required:'Supply an actual test command with --add "command=<actual command>" or --add-json. Environment assignments may precede that command.',examples:['pm test <id> --add "command=node --version"'],nextSteps:["Remove any already-stored assignment-only entry with --remove-index, then register the actual test command."]})}function v(n){if(w(n.command),!(n.pm_context_mode!=="none"||n.workspace_context_mode==="isolated"||n.workspace_context_mode==="snapshot"))throw new d("pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.",s.USAGE,{code:"linked_test_context_invalid",required:"Set workspace_context_mode to isolated or snapshot when pm_context_mode is none.",examples:[f(["test","<id>","--add-json",JSON.stringify({command:n.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}function T(n,t){return n.command===t.command&&n.path===t.path&&n.scope===t.scope&&n.pm_context_mode===t.pm_context_mode&&n.workspace_context_mode===t.workspace_context_mode}const m=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note","phase"],p=new Set(m);function A(n){return u(n,m)}function L(n,t){const e={},o=[];for(const[r,a]of Object.entries(n)){const i=r.toLowerCase();if(!p.has(i)){o.push(r);continue}if(Object.hasOwn(e,i))throw new d(`${t} provides key "${r}" more than once after case normalization`,s.USAGE);e[i]=a}if(o.length>0)throw new d(`${t} does not recognize key${o.length>1?"s":""} ${o.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${m.join(", ")}.`,s.USAGE);if(e.cmd!==void 0){if(e.command!==void 0&&e.command.trim()!==e.cmd.trim())throw new d(`${t} command and cmd must match when both are provided`,s.USAGE);const{cmd:r,...a}=e;return{...a,command:a.command??r}}return e}export{m as STRUCTURED_LINKED_TEST_KEYS,S as admitLinkedTestRequest,w as assertLinkedTestCommand,v as assertLinkedTestContext,T as linkedTestsHaveSameIdentity,A as looksLikeStructuredLinkedTestEntry,L as normalizeStructuredLinkedTestEntry};
3
3
  //# sourceMappingURL=entry.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]="626315a0-7ee9-500d-bb7a-9bcd33eae209")}catch{}})();import{renderPmCommand}from"../command-line.js";const EMPTY_LINKED_TEST_RUN_PATTERNS=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],POSITIVE_LINKED_TEST_RUN_PATTERNS=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function detectEmptyLinkedTestRun(stdout,stderr){const combined=`${stdout}
2
- ${stderr}`;for(const pattern of EMPTY_LINKED_TEST_RUN_PATTERNS)if(pattern.regex.test(combined))return{code:pattern.code};return null}function findLinkedTestExecutionReceipt(stdout,stderr){for(const[stream,output]of[["stdout",stdout],["stderr",stderr]]){const matched=POSITIVE_LINKED_TEST_RUN_PATTERNS.find(pattern=>pattern.regex.test(output));if(matched)return{code:matched.receiptCode,stream}}}function resolveLinkedTestRestoreScope(global2,pmRoot){return{trackerPath:global2.path?.trim()||(process.env.PM_PATH?.trim()?pmRoot:void 0),noExtensions:global2.noExtensions}}function renderLinkedTestRestoreCommand(itemId,scope={}){const trackerPath=scope.trackerPath?.trim();return renderPmCommand(["test",itemId,"--list",...scope.noExtensions===!0?["--no-extensions"]:[],...trackerPath?["--pm-path",trackerPath]:[]],scope.platform)}export{detectEmptyLinkedTestRun,findLinkedTestExecutionReceipt,renderLinkedTestRestoreCommand,resolveLinkedTestRestoreScope};
1
+ import{renderPmCommand as d}from"../command-line.js";const i=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],c=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function u(s,e){const t=`${s}
2
+ ${e}`;for(const r of i)if(r.regex.test(t))return{code:r.code};return null}function a(s,e){for(const[t,r]of[["stdout",s],["stderr",e]]){const o=c.find(n=>n.regex.test(r));if(o)return{code:o.receiptCode,stream:t}}}function _(s,e){return{trackerPath:s.path?.trim()||(process.env.PM_PATH?.trim()?e:void 0),noExtensions:s.noExtensions}}function m(s,e={}){const t=e.trackerPath?.trim();return d(["test",s,"--list",...e.noExtensions===!0?["--no-extensions"]:[],...t?["--pm-path",t]:[]],e.platform)}export{u as detectEmptyLinkedTestRun,a as findLinkedTestExecutionReceipt,m as renderLinkedTestRestoreCommand,_ as resolveLinkedTestRestoreScope};
3
3
  //# sourceMappingURL=execution-receipts.js.map