@unbrained/pm-cli 2026.11.22 → 2026.11.23

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 (892) 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-2UQU7HRR.js +9 -0
  105. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  106. package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
  107. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
  109. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  110. package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-AEOHUSUI.js} +101 -101
  111. package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
  112. package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
  113. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  114. package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
  115. package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
  116. package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
  117. package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
  119. package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
  120. package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
  121. package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
  122. package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
  123. package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
  124. package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
  125. package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
  126. package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
  128. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  129. package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
  130. package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
  131. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  132. package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
  133. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  134. package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
  135. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  136. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  137. package/dist/cli-bundle/chunks/{item-revision-4QBMZXKX.js → item-revision-FMD4KWBB.js} +2 -2
  138. package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
  139. package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
  140. package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
  141. package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-L4IBU64P.js} +11 -11
  142. package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
  143. package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
  144. package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
  145. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  146. package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
  147. package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
  148. package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -0
  149. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  150. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  151. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  152. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
  177. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  178. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  179. package/dist/cli-bundle/focused-chunks/{item-revision-2O6MLPEX.js → item-revision-YDACCDVY.js} +2 -2
  180. package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
  181. package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  184. package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +2 -0
  185. package/dist/cli-bundle/main.js +27 -27
  186. package/dist/cli-bundle/sdk-authoring.js +1 -1
  187. package/dist/cli-bundle/sdk-contracts.js +5 -5
  188. package/dist/cli-bundle/sdk-core.js +1 -1
  189. package/dist/cli-bundle/sdk-governance.js +1 -1
  190. package/dist/cli-bundle/sdk-graph.js +1 -1
  191. package/dist/cli-bundle/sdk-merge.js +66 -66
  192. package/dist/cli-bundle/sdk-query.js +1 -1
  193. package/dist/cli-bundle/sdk-runtime.js +1 -1
  194. package/dist/cli-bundle/sdk-testing.js +1 -1
  195. package/dist/cli-bundle/sdk.js +12 -12
  196. package/dist/cli.js +1 -1
  197. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  198. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  199. package/dist/core/checkpoint/mutation-context.js +1 -1
  200. package/dist/core/config/nested-settings.js +1 -1
  201. package/dist/core/config/positional-value.js +1 -1
  202. package/dist/core/diagnostics/remediation.js +1 -1
  203. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  204. package/dist/core/extensions/activation-summary.js +1 -1
  205. package/dist/core/extensions/activation-transaction.js +1 -1
  206. package/dist/core/extensions/capability-usage.js +1 -1
  207. package/dist/core/extensions/command-hook-context.js +1 -1
  208. package/dist/core/extensions/command-metadata-contract.js +1 -1
  209. package/dist/core/extensions/command-visibility-tier.js +1 -1
  210. package/dist/core/extensions/contribution-inventory.js +1 -1
  211. package/dist/core/extensions/exporter-output-contract.js +1 -1
  212. package/dist/core/extensions/extension-candidate.js +1 -1
  213. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  214. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  215. package/dist/core/extensions/extension-policy.js +1 -1
  216. package/dist/core/extensions/extension-registries.js +1 -1
  217. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  218. package/dist/core/extensions/extension-types.js +1 -1
  219. package/dist/core/extensions/flag-definition-validation.js +1 -1
  220. package/dist/core/extensions/flag-value-types.js +1 -1
  221. package/dist/core/extensions/index.js +1 -1
  222. package/dist/core/extensions/item-field-types.js +1 -1
  223. package/dist/core/extensions/item-fields.js +1 -1
  224. package/dist/core/extensions/loader.js +1 -1
  225. package/dist/core/extensions/manifest-parser.js +1 -1
  226. package/dist/core/extensions/manifest-schema.js +1 -1
  227. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  228. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  229. package/dist/core/extensions/mutation-actor.js +1 -1
  230. package/dist/core/extensions/preflight-ownership.js +1 -1
  231. package/dist/core/extensions/read-output-contract.js +1 -1
  232. package/dist/core/extensions/registration-contracts.js +1 -1
  233. package/dist/core/extensions/registration-validation.js +1 -1
  234. package/dist/core/extensions/registration-values.js +1 -1
  235. package/dist/core/extensions/reserved-host-flags.js +1 -1
  236. package/dist/core/extensions/runtime-registrations.js +1 -1
  237. package/dist/core/extensions/service-ownership.js +1 -1
  238. package/dist/core/extensions/version-compat.js +1 -1
  239. package/dist/core/extensions/version-diagnostics.js +1 -1
  240. package/dist/core/fs/atomic-create.js +1 -1
  241. package/dist/core/fs/file-glob.js +1 -1
  242. package/dist/core/fs/fs-utils.js +2 -2
  243. package/dist/core/fs/host-environment-errors.js +1 -1
  244. package/dist/core/fs/index.js +1 -1
  245. package/dist/core/fs/path-utils.js +1 -1
  246. package/dist/core/governance/content-fields.js +1 -1
  247. package/dist/core/governance/issue-codes.js +1 -1
  248. package/dist/core/governance/metadata-coverage.js +1 -1
  249. package/dist/core/history/bridge.js +1 -1
  250. package/dist/core/history/digest.js +1 -1
  251. package/dist/core/history/drift-cache.js +3 -3
  252. package/dist/core/history/drift-scan.js +1 -1
  253. package/dist/core/history/event-classification.js +1 -1
  254. package/dist/core/history/event-index.js +11 -11
  255. package/dist/core/history/history-compact-bulk.js +1 -1
  256. package/dist/core/history/history-diff.js +1 -1
  257. package/dist/core/history/history-rewrite.js +1 -1
  258. package/dist/core/history/history-storage-stats.js +1 -1
  259. package/dist/core/history/history-stream-policy.js +1 -1
  260. package/dist/core/history/history.js +2 -2
  261. package/dist/core/history/identity.js +1 -1
  262. package/dist/core/history/index.js +1 -1
  263. package/dist/core/history/operation-contract.js +1 -1
  264. package/dist/core/history/projection.js +1 -1
  265. package/dist/core/history/read.js +1 -1
  266. package/dist/core/history/replay.js +2 -2
  267. package/dist/core/history/stream-summary.js +2 -2
  268. package/dist/core/history/tombstone.js +1 -1
  269. package/dist/core/history/version-address.js +1 -1
  270. package/dist/core/history/workspace-history.js +2 -2
  271. package/dist/core/io/body-file.js +1 -1
  272. package/dist/core/io/bulk-ids-input.js +2 -2
  273. package/dist/core/item/actionability.js +1 -1
  274. package/dist/core/item/deferred-fields.js +1 -1
  275. package/dist/core/item/dependency-reference.js +1 -1
  276. package/dist/core/item/id.js +1 -1
  277. package/dist/core/item/index.js +1 -1
  278. package/dist/core/item/item-format-version.js +1 -1
  279. package/dist/core/item/item-format.js +7 -7
  280. package/dist/core/item/item-record.js +1 -1
  281. package/dist/core/item/item-type-definition.js +1 -1
  282. package/dist/core/item/literal-mutation-input.js +1 -1
  283. package/dist/core/item/parent-reference-policy.js +1 -1
  284. package/dist/core/item/parse.js +8 -8
  285. package/dist/core/item/plan-lifecycle.js +1 -1
  286. package/dist/core/item/priority.js +1 -1
  287. package/dist/core/item/sprint-release-format.js +1 -1
  288. package/dist/core/item/status-filter.js +1 -1
  289. package/dist/core/item/status.js +1 -1
  290. package/dist/core/item/toon-decode.js +1 -1
  291. package/dist/core/item/type-registry.js +1 -1
  292. package/dist/core/item/type-synonyms.js +1 -1
  293. package/dist/core/lock/index.js +1 -1
  294. package/dist/core/lock/lock-confinement.js +1 -1
  295. package/dist/core/lock/lock-gc.js +1 -1
  296. package/dist/core/lock/lock-owner.js +1 -1
  297. package/dist/core/lock/lock.js +4 -4
  298. package/dist/core/output/linked-test-projection.js +5 -5
  299. package/dist/core/output/mutation-projection.js +1 -1
  300. package/dist/core/output/output-control.js +1 -1
  301. package/dist/core/output/output.js +19 -19
  302. package/dist/core/output/query-summary.js +1 -1
  303. package/dist/core/output/tabular.js +3 -3
  304. package/dist/core/packages/manifest.js +1 -1
  305. package/dist/core/packages/root.js +1 -1
  306. package/dist/core/policy/workflow-policy-schema.js +1 -1
  307. package/dist/core/policy/workflow-policy-store.js +1 -1
  308. package/dist/core/policy/workflow-policy.js +1 -1
  309. package/dist/core/profile/profile-describe.js +1 -1
  310. package/dist/core/profile/profile-lint.d.ts +1 -1
  311. package/dist/core/profile/profile-lint.js +1 -1
  312. package/dist/core/profile/profile-plan.js +1 -1
  313. package/dist/core/profile/profile-presets.js +4 -4
  314. package/dist/core/reproducibility/context.js +1 -1
  315. package/dist/core/schema/fields-file.js +2 -2
  316. package/dist/core/schema/item-types-file.js +2 -2
  317. package/dist/core/schema/runtime-field-filters.js +1 -1
  318. package/dist/core/schema/runtime-field-values.js +1 -1
  319. package/dist/core/schema/runtime-schema.js +2 -2
  320. package/dist/core/schema/status-defs-file.js +2 -2
  321. package/dist/core/schema/status-token.js +1 -1
  322. package/dist/core/schema/type-inference.js +1 -1
  323. package/dist/core/schema/type-presets.js +1 -1
  324. package/dist/core/schema/type-workflows.js +1 -1
  325. package/dist/core/search/background-refresh.js +2 -2
  326. package/dist/core/search/bm25.js +1 -1
  327. package/dist/core/search/cache.js +2 -2
  328. package/dist/core/search/corpus.js +1 -1
  329. package/dist/core/search/embedding-batches.js +1 -1
  330. package/dist/core/search/eval-thresholds.js +1 -1
  331. package/dist/core/search/eval.js +1 -1
  332. package/dist/core/search/http-client.js +1 -1
  333. package/dist/core/search/providers.js +1 -1
  334. package/dist/core/search/relevance.js +1 -1
  335. package/dist/core/search/semantic-defaults.js +1 -1
  336. package/dist/core/search/staleness.js +1 -1
  337. package/dist/core/search/vector-stores.js +2 -2
  338. package/dist/core/search/vectorization-metadata.js +1 -1
  339. package/dist/core/sentry/helpers.js +1 -1
  340. package/dist/core/sentry/instrument.js +1 -1
  341. package/dist/core/sentry/sensitive-assignments.js +1 -1
  342. package/dist/core/session/session-state.js +1 -1
  343. package/dist/core/shared/agent-session-context.js +1 -1
  344. package/dist/core/shared/author.js +5 -5
  345. package/dist/core/shared/command-line.js +1 -1
  346. package/dist/core/shared/command-types.js +0 -1
  347. package/dist/core/shared/conflict-markers.js +1 -1
  348. package/dist/core/shared/constants.js +1 -1
  349. package/dist/core/shared/error-details.js +1 -1
  350. package/dist/core/shared/errors.js +1 -1
  351. package/dist/core/shared/html-entity-decode.js +1 -1
  352. package/dist/core/shared/index.js +1 -1
  353. package/dist/core/shared/item-metadata-contract.js +1 -1
  354. package/dist/core/shared/lazy-module.js +1 -1
  355. package/dist/core/shared/levenshtein.js +1 -1
  356. package/dist/core/shared/memo.js +1 -1
  357. package/dist/core/shared/numeric-parsers.js +1 -1
  358. package/dist/core/shared/option-alias-visibility.js +1 -1
  359. package/dist/core/shared/output-unicode.js +1 -1
  360. package/dist/core/shared/primitives.js +1 -1
  361. package/dist/core/shared/process-tree.js +2 -2
  362. package/dist/core/shared/secret-rules.js +5 -5
  363. package/dist/core/shared/serial-queue.js +1 -1
  364. package/dist/core/shared/serialization.js +1 -1
  365. package/dist/core/shared/split-comma-list.js +1 -1
  366. package/dist/core/shared/text-normalization.js +1 -1
  367. package/dist/core/shared/time.js +2 -2
  368. package/dist/core/shared/url-credentials.js +1 -1
  369. package/dist/core/store/index.js +1 -1
  370. package/dist/core/store/item-format-migration.js +1 -1
  371. package/dist/core/store/item-metadata-cache.js +1 -1
  372. package/dist/core/store/item-metadata-query-index.js +11 -11
  373. package/dist/core/store/item-metadata-read-work.js +1 -1
  374. package/dist/core/store/item-mutation-precondition.js +1 -1
  375. package/dist/core/store/item-store.js +1 -1
  376. package/dist/core/store/paths.js +1 -1
  377. package/dist/core/store/settings-concurrency.js +1 -1
  378. package/dist/core/store/settings-read-cache.js +1 -1
  379. package/dist/core/store/settings-sections.js +2 -2
  380. package/dist/core/store/settings-validator.js +1 -1
  381. package/dist/core/store/settings.d.ts +3 -1
  382. package/dist/core/store/settings.js +6 -6
  383. package/dist/core/store/sqlite-runtime.js +1 -1
  384. package/dist/core/store/tracker-preflight.js +1 -1
  385. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  386. package/dist/core/telemetry/consent.js +3 -3
  387. package/dist/core/telemetry/observability.js +1 -1
  388. package/dist/core/telemetry/policy.js +1 -1
  389. package/dist/core/telemetry/read-sampling.js +2 -2
  390. package/dist/core/telemetry/runtime.js +9 -9
  391. package/dist/core/test/background-runs.js +4 -4
  392. package/dist/core/test/item-test-run-tracking.js +1 -1
  393. package/dist/core/test/run-selectors.js +1 -1
  394. package/dist/core/validate/estimate-defaults.js +1 -1
  395. package/dist/core/validate/fix-planning.js +1 -1
  396. package/dist/core/validate/linked-artifact-reference.js +1 -1
  397. package/dist/core/validate/missing-by-type.js +1 -1
  398. package/dist/core/validate/missing-link-owners.js +1 -1
  399. package/dist/core/validate/stale-file-classification.js +1 -1
  400. package/dist/mcp/http-server.js +5 -5
  401. package/dist/mcp/legacy-adapter.js +1 -1
  402. package/dist/mcp/runtime-capabilities.js +1 -1
  403. package/dist/mcp/server.js +4 -4
  404. package/dist/mcp/tool-definitions.js +1 -1
  405. package/dist/sdk/actionability.js +1 -1
  406. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  407. package/dist/sdk/agent/command-recovery.js +1 -1
  408. package/dist/sdk/agent/command-suggestions.js +1 -1
  409. package/dist/sdk/agent/create-option-policy.js +1 -1
  410. package/dist/sdk/agent/identity-config.js +1 -1
  411. package/dist/sdk/agent/item-addressing.js +1 -1
  412. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  413. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  414. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  415. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  416. package/dist/sdk/agent-capability-contracts.js +3 -3
  417. package/dist/sdk/agent-session-context.js +1 -1
  418. package/dist/sdk/annotations.js +1 -1
  419. package/dist/sdk/author-attribution.js +1 -1
  420. package/dist/sdk/cli-bootstrap.js +1 -1
  421. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  422. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  423. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  424. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  425. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  426. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  427. package/dist/sdk/cli-contracts/completeness.js +1 -1
  428. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  429. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  430. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  431. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  432. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  433. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  434. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  435. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  436. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  437. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  438. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  439. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  440. package/dist/sdk/cli-contracts.js +1 -1
  441. package/dist/sdk/cli-program.js +1 -1
  442. package/dist/sdk/command-line.js +1 -1
  443. package/dist/sdk/comments.js +1 -1
  444. package/dist/sdk/compile-cache.js +1 -1
  445. package/dist/sdk/completion/bash.js +2 -2
  446. package/dist/sdk/completion/fish.js +72 -72
  447. package/dist/sdk/completion/shared.js +1 -1
  448. package/dist/sdk/completion/zsh.js +75 -75
  449. package/dist/sdk/completion.js +1 -1
  450. package/dist/sdk/config.js +1 -1
  451. package/dist/sdk/context/recency.js +1 -1
  452. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  453. package/dist/sdk/context/usage-egress.js +1 -1
  454. package/dist/sdk/context/usage-ledger.js +6 -6
  455. package/dist/sdk/context-intent-contracts.js +1 -1
  456. package/dist/sdk/context-intent-runtime.js +1 -1
  457. package/dist/sdk/context-packing.js +1 -1
  458. package/dist/sdk/context-relevance.js +1 -1
  459. package/dist/sdk/context-signal-store.js +2 -2
  460. package/dist/sdk/context-usage.js +1 -1
  461. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  462. package/dist/sdk/dependencies.js +1 -1
  463. package/dist/sdk/dependency-flag-validation.js +1 -1
  464. package/dist/sdk/dependency-provenance.js +1 -1
  465. package/dist/sdk/docs.js +1 -1
  466. package/dist/sdk/duplicates.js +1 -1
  467. package/dist/sdk/environment/host-environment-errors.js +1 -1
  468. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  469. package/dist/sdk/environment/source-context.js +1 -1
  470. package/dist/sdk/environment/tracker-preflight.js +1 -1
  471. package/dist/sdk/error-code-catalog.js +1 -1
  472. package/dist/sdk/error-runtime.js +1 -1
  473. package/dist/sdk/errors.js +1 -1
  474. package/dist/sdk/eval.js +1 -1
  475. package/dist/sdk/extension/author-manifest.js +1 -1
  476. package/dist/sdk/extension/bundled-catalog.js +1 -1
  477. package/dist/sdk/extension/command-options.js +1 -1
  478. package/dist/sdk/extension/concurrency.js +1 -1
  479. package/dist/sdk/extension/copy-scope.js +1 -1
  480. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  481. package/dist/sdk/extension/describe.js +3 -3
  482. package/dist/sdk/extension/doctor.js +1 -1
  483. package/dist/sdk/extension/install-plan.js +1 -1
  484. package/dist/sdk/extension/install-receipts.js +1 -1
  485. package/dist/sdk/extension/install-runtime.js +3 -3
  486. package/dist/sdk/extension/install-snapshot.js +1 -1
  487. package/dist/sdk/extension/install-sources.js +5 -5
  488. package/dist/sdk/extension/managed-state.js +2 -2
  489. package/dist/sdk/extension/managed-update-status.js +1 -1
  490. package/dist/sdk/extension/migrations.js +2 -2
  491. package/dist/sdk/extension/native-command-options.js +1 -1
  492. package/dist/sdk/extension/output-ownership.js +1 -1
  493. package/dist/sdk/extension/runtime-summary.js +1 -1
  494. package/dist/sdk/extension/scaffold.js +11 -11
  495. package/dist/sdk/extension/shared.js +1 -1
  496. package/dist/sdk/extension/source-resolution.js +1 -1
  497. package/dist/sdk/extension/static-inventory.js +1 -1
  498. package/dist/sdk/extension/update-check.js +1 -1
  499. package/dist/sdk/extension-command-context.js +2 -2
  500. package/dist/sdk/extension-contracts.js +1 -1
  501. package/dist/sdk/extension.js +1 -1
  502. package/dist/sdk/files.js +1 -1
  503. package/dist/sdk/flag-invocation-contracts.js +1 -1
  504. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  505. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  506. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  507. package/dist/sdk/generated-error-code-catalog.js +1 -1
  508. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  509. package/dist/sdk/governance/assurance-action.js +1 -1
  510. package/dist/sdk/governance/assurance-limits.js +1 -1
  511. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  512. package/dist/sdk/governance/assurance-presets.js +1 -1
  513. package/dist/sdk/governance/assurance-runtime.js +1 -1
  514. package/dist/sdk/governance/assurance.js +4 -4
  515. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  516. package/dist/sdk/governance/closure-timestamps.js +1 -1
  517. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  518. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  519. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  520. package/dist/sdk/governance/defect-recurrence.js +2 -2
  521. package/dist/sdk/governance/extension-host-version.js +1 -1
  522. package/dist/sdk/governance/gc.js +1 -1
  523. package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
  524. package/dist/sdk/governance/health/projection.js +1 -1
  525. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  526. package/dist/sdk/governance/health.js +2 -2
  527. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  528. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  529. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  530. package/dist/sdk/governance/linked-file-report.js +1 -1
  531. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  532. package/dist/sdk/governance/provenance-health.js +4 -4
  533. package/dist/sdk/governance/reindex.js +5 -5
  534. package/dist/sdk/governance/stale-work.js +1 -1
  535. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  536. package/dist/sdk/governance/storage-integrity.js +1 -1
  537. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  538. package/dist/sdk/governance/upgrade.js +2 -2
  539. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  540. package/dist/sdk/governance/validate-history-drift.js +1 -1
  541. package/dist/sdk/governance/validate-item-reader.js +1 -1
  542. package/dist/sdk/governance/validate-normalization.js +1 -1
  543. package/dist/sdk/governance/validate.js +1 -1
  544. package/dist/sdk/governance/workflow-completeness.js +1 -1
  545. package/dist/sdk/governance/workflow-policy.js +3 -3
  546. package/dist/sdk/governance/workspace-position.js +2 -2
  547. package/dist/sdk/graph/analytics.js +1 -1
  548. package/dist/sdk/graph/assembly.js +1 -1
  549. package/dist/sdk/graph/cache.js +1 -1
  550. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  551. package/dist/sdk/graph/centrality.js +1 -1
  552. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  553. package/dist/sdk/graph/durable-cache.js +1 -1
  554. package/dist/sdk/graph/governance-contracts.js +1 -1
  555. package/dist/sdk/graph/governance.js +1 -1
  556. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  557. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  558. package/dist/sdk/graph/mutation-advisory.js +1 -1
  559. package/dist/sdk/graph/query-contracts.js +1 -1
  560. package/dist/sdk/graph/remediation.js +1 -1
  561. package/dist/sdk/graph/run.js +1 -1
  562. package/dist/sdk/graph/scheduling.js +1 -1
  563. package/dist/sdk/graph/traversal.js +1 -1
  564. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  565. package/dist/sdk/guide-topics.js +1 -1
  566. package/dist/sdk/guide.js +7 -7
  567. package/dist/sdk/history/append-only-repair.js +4 -4
  568. package/dist/sdk/history/attestation-command.js +2 -2
  569. package/dist/sdk/history/attestation-contract.js +1 -1
  570. package/dist/sdk/history/attestation-scan.js +1 -1
  571. package/dist/sdk/history/attestation.js +1 -1
  572. package/dist/sdk/history/maintenance.js +1 -1
  573. package/dist/sdk/history/reanchor-refusal.js +1 -1
  574. package/dist/sdk/history/reseed.js +1 -1
  575. package/dist/sdk/history/salvage.js +5 -5
  576. package/dist/sdk/history/subject.js +1 -1
  577. package/dist/sdk/history-analytics.js +1 -1
  578. package/dist/sdk/history-compact.js +1 -1
  579. package/dist/sdk/history-mcp.js +1 -1
  580. package/dist/sdk/history-provenance.js +1 -1
  581. package/dist/sdk/history-read.js +1 -1
  582. package/dist/sdk/history-redact.js +1 -1
  583. package/dist/sdk/history-repair.js +1 -1
  584. package/dist/sdk/improvement-ledger-validation.js +1 -1
  585. package/dist/sdk/improvement-ledger.js +2 -2
  586. package/dist/sdk/init-agent-guidance.js +10 -10
  587. package/dist/sdk/init.js +14 -14
  588. package/dist/sdk/invocation-author.js +1 -1
  589. package/dist/sdk/item-children.js +1 -1
  590. package/dist/sdk/item-metadata-index.js +1 -1
  591. package/dist/sdk/item-schedule.js +1 -1
  592. package/dist/sdk/item-transaction.js +1 -1
  593. package/dist/sdk/learnings.js +1 -1
  594. package/dist/sdk/lifecycle/append.js +3 -3
  595. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  596. package/dist/sdk/lifecycle/claim.js +1 -1
  597. package/dist/sdk/lifecycle/cli-input.js +1 -1
  598. package/dist/sdk/lifecycle/close-many.js +1 -1
  599. package/dist/sdk/lifecycle/close.js +1 -1
  600. package/dist/sdk/lifecycle/copy.js +1 -1
  601. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  602. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  603. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  604. package/dist/sdk/lifecycle/create.js +1 -1
  605. package/dist/sdk/lifecycle/delete.js +1 -1
  606. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  607. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  608. package/dist/sdk/lifecycle/focus.js +1 -1
  609. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  610. package/dist/sdk/lifecycle/item-revision.js +1 -1
  611. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  612. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  613. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  614. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  615. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  616. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  617. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  618. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  619. package/dist/sdk/lifecycle/plan.js +1 -1
  620. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  621. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  622. package/dist/sdk/lifecycle/reopen.js +1 -1
  623. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  624. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  625. package/dist/sdk/lifecycle/restore.js +1 -1
  626. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  627. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  628. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  629. package/dist/sdk/lifecycle/task-composition.js +1 -1
  630. package/dist/sdk/lifecycle/update-many.js +1 -1
  631. package/dist/sdk/lifecycle/update.js +2 -2
  632. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  633. package/dist/sdk/lifecycle-completion.js +1 -1
  634. package/dist/sdk/lifecycle-policy.js +1 -1
  635. package/dist/sdk/linked-artifacts.js +2 -2
  636. package/dist/sdk/mcp/apps.js +5 -5
  637. package/dist/sdk/mcp/authorization.js +1 -1
  638. package/dist/sdk/mcp/discovery.js +1 -1
  639. package/dist/sdk/mcp/executable.js +4 -4
  640. package/dist/sdk/mcp/interactions.js +1 -1
  641. package/dist/sdk/mcp/protocol.js +1 -1
  642. package/dist/sdk/mcp/skills.js +3 -3
  643. package/dist/sdk/mcp/subscriptions.js +1 -1
  644. package/dist/sdk/mcp/tasks.js +2 -2
  645. package/dist/sdk/mcp/transport.js +1 -1
  646. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  647. package/dist/sdk/merge/driver.js +7 -7
  648. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  649. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  650. package/dist/sdk/merge/index.js +1 -1
  651. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  652. package/dist/sdk/merge/install.js +6 -6
  653. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  654. package/dist/sdk/merge/receipt-operation.js +1 -1
  655. package/dist/sdk/merge/receipt-schema.js +1 -1
  656. package/dist/sdk/merge/receipts.js +4 -4
  657. package/dist/sdk/merge/reconcile.js +1 -1
  658. package/dist/sdk/merge/settlement-hook.js +4 -4
  659. package/dist/sdk/merge/stage.js +1 -1
  660. package/dist/sdk/merge/three-way.js +9 -9
  661. package/dist/sdk/merge/worktree-config.js +2 -2
  662. package/dist/sdk/merge.js +1 -1
  663. package/dist/sdk/mutation-events.js +1 -1
  664. package/dist/sdk/mutation-guard.js +1 -1
  665. package/dist/sdk/notes.js +1 -1
  666. package/dist/sdk/output/fit-envelope.js +1 -1
  667. package/dist/sdk/output/list-envelope.js +1 -1
  668. package/dist/sdk/output/table-rows.js +1 -1
  669. package/dist/sdk/output-contracts.js +1 -1
  670. package/dist/sdk/output-projection.js +1 -1
  671. package/dist/sdk/output-token-accounting.js +1 -1
  672. package/dist/sdk/output.js +2 -2
  673. package/dist/sdk/ownership-source.js +1 -1
  674. package/dist/sdk/package-import-adapters.js +1 -1
  675. package/dist/sdk/package-migrations.js +1 -1
  676. package/dist/sdk/package-runtime-options.js +1 -1
  677. package/dist/sdk/pagination.js +1 -1
  678. package/dist/sdk/profile.js +5 -5
  679. package/dist/sdk/provenance.js +1 -1
  680. package/dist/sdk/public-surface.json +1 -1
  681. package/dist/sdk/query/activity.js +1 -1
  682. package/dist/sdk/query/aggregate.js +1 -1
  683. package/dist/sdk/query/calendar.js +4 -4
  684. package/dist/sdk/query/complete-list.js +1 -1
  685. package/dist/sdk/query/context.js +2 -2
  686. package/dist/sdk/query/declared-blockers.js +1 -1
  687. package/dist/sdk/query/duplicate-candidates.js +1 -1
  688. package/dist/sdk/query/get-facet-roots.js +1 -1
  689. package/dist/sdk/query/get.js +1 -1
  690. package/dist/sdk/query/history.js +1 -1
  691. package/dist/sdk/query/item-filter-options.js +0 -1
  692. package/dist/sdk/query/light-metadata.js +1 -1
  693. package/dist/sdk/query/list-filter-shared.js +1 -1
  694. package/dist/sdk/query/list.js +1 -1
  695. package/dist/sdk/query/multi-value-filters.js +1 -1
  696. package/dist/sdk/query/next-ranking-policy.js +1 -1
  697. package/dist/sdk/query/next-ready-budget.js +1 -1
  698. package/dist/sdk/query/next.js +2 -2
  699. package/dist/sdk/query/parsers.js +1 -1
  700. package/dist/sdk/query/projection-contracts.js +1 -1
  701. package/dist/sdk/query/search/corpus.js +2 -2
  702. package/dist/sdk/query/search/filters.js +1 -1
  703. package/dist/sdk/query/search/input.js +1 -1
  704. package/dist/sdk/query/search/lexical.js +1 -1
  705. package/dist/sdk/query/search/response.js +1 -1
  706. package/dist/sdk/query/search/semantic.js +3 -3
  707. package/dist/sdk/query/search/types.js +0 -1
  708. package/dist/sdk/query/search-contracts.js +1 -1
  709. package/dist/sdk/query/search-pagination.js +1 -1
  710. package/dist/sdk/query/search-rendering.js +1 -1
  711. package/dist/sdk/query/search.js +1 -1
  712. package/dist/sdk/query/window-pagination.js +1 -1
  713. package/dist/sdk/query/workspace-contracts.js +1 -1
  714. package/dist/sdk/read-output/continuation.js +1 -1
  715. package/dist/sdk/read-output/extension.js +1 -1
  716. package/dist/sdk/read-output/options.js +1 -1
  717. package/dist/sdk/read-output/positional-rows.js +1 -1
  718. package/dist/sdk/read-output/provenance.js +1 -1
  719. package/dist/sdk/read-output/session-result.js +0 -1
  720. package/dist/sdk/read-output/surfaces.js +1 -1
  721. package/dist/sdk/read-output/tail-retention.js +1 -1
  722. package/dist/sdk/read-output-budget.js +1 -1
  723. package/dist/sdk/read-output-contracts.js +1 -1
  724. package/dist/sdk/read-output-rows.js +1 -1
  725. package/dist/sdk/read-output-session.js +1 -1
  726. package/dist/sdk/relationship-analytics.js +1 -1
  727. package/dist/sdk/relationship-context.js +1 -1
  728. package/dist/sdk/relationship-history.js +6 -6
  729. package/dist/sdk/relationship-kinds/contract.js +1 -1
  730. package/dist/sdk/relationships.js +1 -1
  731. package/dist/sdk/reproducibility/process.js +1 -1
  732. package/dist/sdk/runtime/actions.js +1 -1
  733. package/dist/sdk/runtime/context.js +1 -1
  734. package/dist/sdk/runtime/mutation-admission.js +1 -1
  735. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  736. package/dist/sdk/runtime/schema-preview.js +1 -1
  737. package/dist/sdk/runtime/schema.js +1 -1
  738. package/dist/sdk/runtime-action-aliases.js +1 -1
  739. package/dist/sdk/runtime-extended-actions.js +1 -1
  740. package/dist/sdk/runtime-input.d.ts +2 -0
  741. package/dist/sdk/runtime-input.js +1 -1
  742. package/dist/sdk/runtime-primitives.js +1 -1
  743. package/dist/sdk/runtime-public-contracts.js +0 -1
  744. package/dist/sdk/runtime-stats-options.js +1 -1
  745. package/dist/sdk/runtime.d.ts +5 -3
  746. package/dist/sdk/runtime.js +1 -1
  747. package/dist/sdk/scheduling-shortcuts.js +1 -1
  748. package/dist/sdk/schema/field-option-collisions.js +2 -0
  749. package/dist/sdk/schema-migration.js +4 -4
  750. package/dist/sdk/schema.js +7 -7
  751. package/dist/sdk/search-refresh-worker.js +1 -1
  752. package/dist/sdk/similarity-scoring.js +1 -1
  753. package/dist/sdk/similarity.js +1 -1
  754. package/dist/sdk/start-task-status.js +1 -1
  755. package/dist/sdk/stats.js +1 -1
  756. package/dist/sdk/structured-mutations.js +1 -1
  757. package/dist/sdk/telemetry-flush.js +1 -1
  758. package/dist/sdk/telemetry.js +4 -4
  759. package/dist/sdk/templates.js +3 -3
  760. package/dist/sdk/test/batch.js +2 -2
  761. package/dist/sdk/test/command-args.js +1 -1
  762. package/dist/sdk/test/command-resolution.js +2 -2
  763. package/dist/sdk/test/entry.js +2 -2
  764. package/dist/sdk/test/execution-receipts.js +2 -2
  765. package/dist/sdk/test/execution.js +5 -5
  766. package/dist/sdk/test/json-path.js +1 -1
  767. package/dist/sdk/test/linked-command-detection.js +1 -1
  768. package/dist/sdk/test/measurements.js +1 -1
  769. package/dist/sdk/test/parsers.js +1 -1
  770. package/dist/sdk/test/prerequisites.js +1 -1
  771. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  772. package/dist/sdk/test/run-phases.js +1 -1
  773. package/dist/sdk/test/runs.js +1 -1
  774. package/dist/sdk/test/trust.js +2 -2
  775. package/dist/sdk/test/update.js +1 -1
  776. package/dist/sdk/test/workspace-snapshot.js +1 -1
  777. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  778. package/dist/sdk/traceability/source-traceability.js +2 -2
  779. package/dist/sdk/tracker-root-discovery.js +1 -1
  780. package/dist/sdk/transactions/item-finalization.js +1 -1
  781. package/dist/sdk/workspace-contracts-cache.js +1 -1
  782. package/dist/sdk/workspace-contracts.js +1 -1
  783. package/dist/sdk/workspace-memory.js +2 -2
  784. package/dist/sdk/workspace-snapshot.js +5 -5
  785. package/dist/sdk/workspace-transaction-gc.js +1 -1
  786. package/dist/sdk/workspace-transaction.js +2 -2
  787. package/dist/sdk/workspace.js +6 -6
  788. package/dist/types/index.js +1 -1
  789. package/dist/types.js +1 -1
  790. package/docs/COMMANDS.md +1 -1
  791. package/docs/EXTENSIONS.md +1 -1
  792. package/docs/SDK.md +74 -4
  793. package/marketplace.json +1 -1
  794. package/package.json +2 -1
  795. package/packages/pm-beads/package.json +1 -1
  796. package/packages/pm-calendar/package.json +1 -1
  797. package/packages/pm-command-kit/package.json +1 -1
  798. package/packages/pm-digital-twin/package.json +1 -1
  799. package/packages/pm-governance-audit/package.json +1 -1
  800. package/packages/pm-guide-shell/package.json +1 -1
  801. package/packages/pm-kanban/package.json +1 -1
  802. package/packages/pm-lifecycle-hooks/package.json +1 -1
  803. package/packages/pm-linked-test-adapters/package.json +1 -1
  804. package/packages/pm-search-advanced/package.json +1 -1
  805. package/packages/pm-templates/package.json +1 -1
  806. package/packages/pm-todos/package.json +1 -1
  807. package/packages/pm-vcs/package.json +1 -1
  808. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  809. package/plugins/pm-claude/package.json +1 -1
  810. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  811. package/plugins/pm-codex/package.json +1 -1
  812. package/plugins/pm-codex/plugin.json +1 -1
  813. package/runtime-dependencies.json +1 -1
  814. package/scripts/finalize-build.mjs +63 -24
  815. package/scripts/prepare-build-cache.mjs +28 -1
  816. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
  817. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
  818. package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
  819. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
  820. package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
  821. package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
  822. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
  823. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  824. package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
  825. package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
  826. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
  827. package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
  828. package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
  829. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
  830. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  831. package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
  832. package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
  833. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  834. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  835. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
  836. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  837. package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
  838. package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
  839. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
  840. package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
  841. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
  842. package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
  843. package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
  844. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  845. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  846. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  847. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  848. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
  849. package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
  850. package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
  851. package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
  852. package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
  853. package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
  854. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  855. package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
  856. package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
  857. package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
  858. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  859. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  860. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
  861. package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
  862. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
  863. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
  864. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
  865. package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
  866. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  867. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  868. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  869. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  870. package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
  871. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  872. package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
  873. package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
  874. package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
  875. package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
  876. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
  877. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
  878. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  879. package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
  880. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
  881. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
  882. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
  883. package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
  884. package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
  885. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
  886. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  888. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  892. package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
@@ -1,10 +1,10 @@
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]="6ca73b84-5485-515a-a836-7fcce9851fb6")}catch{}})();import crypto from"node:crypto";import{spawn}from"node:child_process";import{mkdirSync,rmSync,statSync}from"node:fs";import{mkdir,readdir,rm,stat}from"node:fs/promises";import{request as httpRequest}from"node:http";import{request as httpsRequest}from"node:https";import os from"node:os";import path from"node:path";import{acquireLock}from"../lock/lock.js";import{isActiveCommandUnextended,runWithIsolatedExtensionRuntime}from"../extensions/index.js";import{resolveAutomaticReadSampleRate}from"./read-sampling.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES,isTelemetryTestEnvironment,redactTelemetryEndpoint,redactUrlsInText,resolveTelemetryEndpointOverride,resolveTelemetryEnvironmentPolicy,resolveTelemetrySourceAttribution,telemetryRuntimeFileName}from"./policy.js";import{redactUrlCredentialsInText,redactUrlCredentialsInToken}from"../shared/url-credentials.js";import{resolvePmPackageRootFromModule}from"../packages/root.js";import{isFileMissingError,appendLineAtomic,readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{resolveTelemetryErrorCategory}from"../shared/constants.js";import{nowIso}from"../shared/time.js";import{detectAgentIdentity,readAuthorEnvironment}from"../shared/author.js";import{resolveGlobalPmRoot}from"../store/paths.js";import{isConfigurationOnlySettingsRead,isSettingsReadFallback,readSettings,runWithConfigurationOnlySettings,writeSettings}from"../store/settings.js";import{clearSettingsReadCache}from"../store/settings-read-cache.js";import{deriveTelemetryCommandResolution,deriveTelemetryCommandTaxonomy,inferTelemetryErrorCode}from"./observability.js";const TELEMETRY_QUEUE_RELATIVE_PATH=path.join("runtime","telemetry","events.jsonl"),TELEMETRY_STATE_RELATIVE_PATH=path.join("runtime","telemetry","state.json"),TELEMETRY_OTEL_SPANS_RELATIVE_PATH=path.join("runtime","telemetry","otel-spans.jsonl"),TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE=8,TELEMETRY_OTEL_SPANS_MAX_PENDING=500,TELEMETRY_SCHEMA_VERSION=1,TELEMETRY_CLIENT_SCHEMA_VERSION=1,TELEMETRY_FLUSH_BATCH_SIZE=100,TELEMETRY_MAX_RETRY_DELAY_MS=36e5,TELEMETRY_RETRY_BASE_DELAY_MS=3e4,TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS=2e4,TELEMETRY_HTTP_TIMEOUT_MIN_MS=1e3,TELEMETRY_HTTP_TIMEOUT_MAX_MS=25e3,TELEMETRY_FOREGROUND_LOCK_WAIT_MS=250,MILLISECONDS_PER_DAY=864e5,TELEMETRY_MAX_EVENT_BYTES=65536,TELEMETRY_SANITIZE_MAX_DEPTH=6,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS=20,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS=15,TELEMETRY_RESULT_PREVIEW_MAX_BYTES=8192,TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS=[25,50,100,200],TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS=3600*1e3,TELEMETRY_OVERRIDE_QUEUE_MAX_IDLE_MS=1440*60*1e3,TELEMETRY_FLUSH_LOCK_STALE_MS=6e4,TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS=6e4,OTEL_TRACES_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",OTEL_BASE_ENDPOINT_ENV="OTEL_EXPORTER_OTLP_ENDPOINT",OTEL_SERVICE_NAME_ENV="OTEL_SERVICE_NAME",PM_TELEMETRY_OTEL_DISABLED_ENV="PM_TELEMETRY_OTEL_DISABLED",PM_TELEMETRY_OTEL_DISABLED_VALUES=new Set(["1","true","yes","on"]),PM_TELEMETRY_INLINE_FLUSH_ENV="PM_TELEMETRY_INLINE_FLUSH",PM_TELEMETRY_FLUSH_CHILD_ENV="PM_TELEMETRY_FLUSH_CHILD",PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV="PM_TELEMETRY_HTTP_TIMEOUT_MS",NATIVE_FETCH=globalThis.fetch;import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as PM_TELEMETRY_SOURCE_CONTEXT_VALUES2}from"./policy.js";let sourceContextWarningEmitted=!1,_lastFlushPromise=Promise.resolve(),_queueMutationPromise=Promise.resolve();const deferredReadStarts=new WeakMap;async function waitForPendingFlush(){await _lastFlushPromise,await _queueMutationPromise}const BOOLEAN_TRUE_VALUES=new Set(["1","true","yes","on"]),TELEMETRY_HARNESSES=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]),PROCESS_SESSION_ID=crypto.randomUUID(),SENSITIVE_KEYWORDS=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],REDACTION_INPUT_KEYS=new Set(["literal","literals","regex","regexes","replacement","replacements","setjson","set_json","update"]),SENSITIVE_INLINE_KEY_PATTERN="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",INLINE_SENSITIVE_ASSIGNMENT_PATTERN=new RegExp(`\\b(${SENSITIVE_INLINE_KEY_PATTERN})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),INLINE_SENSITIVE_FLAG_PATTERN=new RegExp(`(--${SENSITIVE_INLINE_KEY_PATTERN})(=|\\s+)([^\\s,;]+)`,"giu"),ABSOLUTE_PATH_TOKEN_PATTERN=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,BEARER_TOKEN_PATTERN=/bearer\s+[a-z0-9._=-]+/giu,PRIVATE_IP_PATTERN=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function queuePath(globalPmRoot,override=resolveTelemetryEndpointOverride().endpoint){return path.join(path.dirname(path.join(globalPmRoot,TELEMETRY_QUEUE_RELATIVE_PATH)),telemetryRuntimeFileName("events.jsonl",override))}function otelSpansQueuePath(globalPmRoot){return path.join(globalPmRoot,TELEMETRY_OTEL_SPANS_RELATIVE_PATH)}function telemetryRuntimeDirectory(globalPmRoot){return path.dirname(queuePath(globalPmRoot,null))}function runtimeStatePath(globalPmRoot,override=resolveTelemetryEndpointOverride().endpoint){return path.join(path.dirname(path.join(globalPmRoot,TELEMETRY_STATE_RELATIVE_PATH)),telemetryRuntimeFileName("state.json",override))}function flushLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.lock")}function flushSpawnLockPath(globalPmRoot){return path.join(globalPmRoot,"runtime","telemetry","flush.spawn.lock")}function telemetryFlushRunnerPath(){return path.join(resolvePmPackageRootFromModule(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function shouldFlushInline(){return parseBooleanTrueLike(process.env[PM_TELEMETRY_INLINE_FLUSH_ENV])||parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])?!0:isTelemetryTestEnvironment()}async function readRuntimeState(globalPmRoot,override=resolveTelemetryEndpointOverride().endpoint){const raw=await readFileIfExists(runtimeStatePath(globalPmRoot,override));if(!raw||raw.trim().length===0)return{};try{const parsed=JSON.parse(raw);return typeof parsed!="object"||parsed===null||Array.isArray(parsed)?{}:parsed}catch{return{}}}async function writeRuntimeState(globalPmRoot,patch,override=resolveTelemetryEndpointOverride().endpoint){try{await withQueueMutation(async()=>{const next={...await readRuntimeState(globalPmRoot,override),...patch},normalized=Object.fromEntries(Object.entries(next).filter(([,value])=>value!==void 0).sort((left,right)=>left[0].localeCompare(right[0])));await writeFileAtomic(runtimeStatePath(globalPmRoot,override),`${JSON.stringify(normalized,null,2)}
2
- `,{createParentDirectories:!parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])})},globalPmRoot)}catch{}}function isSensitiveKey(key){const normalized=key.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),tokens=normalized.split("_").filter(token=>token.length>0);return REDACTION_INPUT_KEYS.has(normalized)||SENSITIVE_KEYWORDS.some(keyword=>normalized===keyword||normalized.endsWith(`_${keyword}`)||tokens.includes(keyword))}function redactInlineSensitiveAssignments(input){return input.replaceAll(INLINE_SENSITIVE_ASSIGNMENT_PATTERN,(_match,key,delimiter)=>`${key}${delimiter}[redacted]`).replaceAll(INLINE_SENSITIVE_FLAG_PATTERN,(_match,flag,delimiter)=>`${flag}${delimiter}[redacted]`)}function redactAbsolutePathTokens(input){return input.replaceAll(ABSOLUTE_PATH_TOKEN_PATTERN,(_match,prefix)=>`${prefix}[redacted_path]`)}function isAsciiLetterOrDigitCode(code){const isUpper=code>=65&&code<=90,isLower=code>=97&&code<=122,isDigit=code>=48&&code<=57;return isUpper||isLower||isDigit}function isEmailLocalCharacter(character){if(!character)return!1;const code=character.charCodeAt(0);return isAsciiLetterOrDigitCode(code)?!0:character==="."||character==="_"||character==="%"||character==="+"||character==="-"}function isEmailDomainCharacter(character){if(!character)return!1;const code=character.charCodeAt(0);return isAsciiLetterOrDigitCode(code)?!0:character==="."||character==="-"}function looksLikeEmailToken(token){const atIndex=token.indexOf("@");if(atIndex<=0||atIndex!==token.lastIndexOf("@")||atIndex===token.length-1)return!1;const localPart=token.slice(0,atIndex),domainPart=token.slice(atIndex+1),lastDot=domainPart.lastIndexOf(".");if(lastDot<=0||lastDot===domainPart.length-1||domainPart.length-(lastDot+1)<2)return!1;for(const character of localPart)if(!isEmailLocalCharacter(character))return!1;for(const character of domainPart)if(!isEmailDomainCharacter(character))return!1;return!0}function redactEmailTokens(input){let redacted="",cursor=0;for(;cursor<input.length;){const atIndex=input.indexOf("@",cursor);if(atIndex<0){redacted+=input.slice(cursor);break}let start=atIndex-1;for(;start>=cursor&&isEmailLocalCharacter(input[start]);)start-=1;start+=1;let end=atIndex+1;for(;end<input.length&&isEmailDomainCharacter(input[end]);)end+=1;const candidate=input.slice(start,end);if(looksLikeEmailToken(candidate)){redacted+=input.slice(cursor,start),redacted+="[redacted_email]",cursor=end;continue}redacted+=input.slice(cursor,atIndex+1),cursor=atIndex+1}return redacted}function sanitizeCommonSensitiveTokens(input){return redactEmailTokens(redactUrlCredentialsInText(input)).replaceAll(BEARER_TOKEN_PATTERN,"bearer [redacted_token]").replaceAll(PRIVATE_IP_PATTERN,"[redacted_ip]")}function sanitizeStringRedacted(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input),withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens),withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets),trimmed=withoutAbsolutePaths.trim();return trimmed.startsWith("/")&&trimmed.length>1?"[redacted_path]":withoutAbsolutePaths.length>512?`${withoutAbsolutePaths.slice(0,509)}...`:withoutAbsolutePaths}function sanitizeStringMax(input){const withoutCommonSensitiveTokens=sanitizeCommonSensitiveTokens(input),withoutInlineSecrets=redactInlineSensitiveAssignments(withoutCommonSensitiveTokens),withoutAbsolutePaths=redactAbsolutePathTokens(withoutInlineSecrets),trimmed=withoutAbsolutePaths.trim();return trimmed.startsWith("/")&&trimmed.length>1?"[redacted_path]":withoutAbsolutePaths.length>2048?`${withoutAbsolutePaths.slice(0,2045)}...`:withoutAbsolutePaths}function sanitizeString(input,captureLevel="redacted"){return captureLevel==="max"?sanitizeStringMax(input):sanitizeStringRedacted(input)}function sanitizeValue(value,keyHint,captureLevel="redacted",depth=0){if(keyHint&&isSensitiveKey(keyHint))return"[redacted]";if(value==null)return value;if(typeof value=="string")return sanitizeString(value,captureLevel);if(typeof value=="number"||typeof value=="boolean")return value;if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH)return"[depth_truncated]";if(Array.isArray(value))return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>sanitizeValue(entry,void 0,captureLevel,depth+1));if(typeof value=="object"){const record=value,sanitized={};for(const[key,nested]of Object.entries(record))sanitized[key]=sanitizeValue(nested,key,captureLevel,depth+1);return sanitized}return String(value)}function sanitizeCommandArgs(args,captureLevel="redacted"){const sanitized=[];let nextIsSensitiveValue=!1;for(const rawArg of args){const arg=sanitizeString(redactUrlCredentialsInToken(rawArg),captureLevel);if(nextIsSensitiveValue){sanitized.push("[redacted]"),nextIsSensitiveValue=!1;continue}if(arg.startsWith("--")){const withoutPrefix=arg.slice(2),delimiterIndex=withoutPrefix.indexOf("=");if(delimiterIndex>=0){const key=withoutPrefix.slice(0,delimiterIndex),value=withoutPrefix.slice(delimiterIndex+1);isSensitiveKey(key)?sanitized.push(`--${key}=[redacted]`):sanitized.push(`--${key}=${sanitizeString(value,captureLevel)}`);continue}if(isSensitiveKey(withoutPrefix)){sanitized.push(`--${withoutPrefix}`),nextIsSensitiveValue=!0;continue}}sanitized.push(arg)}return sanitized}function normalizeCaptureLevel(value){const normalized=value?.trim().toLowerCase();return normalized==="minimal"||normalized==="redacted"||normalized==="max"?normalized:"redacted"}function parseBooleanTrueLike(value){return BOOLEAN_TRUE_VALUES.has((value??"").trim().toLowerCase())}function resolveTelemetryHttpTimeoutMs(){const rawConfigured=process.env[PM_TELEMETRY_HTTP_TIMEOUT_MS_ENV]?.trim();if(!rawConfigured)return TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS;const configured=Number(rawConfigured);return Number.isFinite(configured)?Math.min(TELEMETRY_HTTP_TIMEOUT_MAX_MS,Math.max(TELEMETRY_HTTP_TIMEOUT_MIN_MS,Math.trunc(configured))):TELEMETRY_HTTP_TIMEOUT_DEFAULT_MS}async function postTelemetryJson(endpoint,headers,body){const url=new URL(endpoint);if(globalThis.fetch!==NATIVE_FETCH){const controller=new AbortController;let timeout;const deadline=new Promise((_resolve,reject)=>{timeout=setTimeout(()=>{controller.abort(),reject(new Error("telemetry_http_timeout"))},resolveTelemetryHttpTimeoutMs())});try{return(await Promise.race([globalThis.fetch(endpoint,{method:"POST",headers,body,signal:controller.signal}),deadline])).status}finally{clearTimeout(timeout)}}const request=url.protocol==="https:"?httpsRequest:url.protocol==="http:"?httpRequest:void 0;if(!request)throw new Error(`telemetry_http_protocol_unsupported_${url.protocol}`);return new Promise((resolve,reject)=>{const timeoutMs=resolveTelemetryHttpTimeoutMs(),requestOptions={method:"POST",headers:{...headers,"content-length":Buffer.byteLength(body)},signal:AbortSignal.timeout(timeoutMs),autoSelectFamilyAttemptTimeout:Math.min(5e3,timeoutMs)},clientRequest=request(url,requestOptions,response=>{response.once("error",reject),response.once("end",()=>resolve(response.statusCode)),response.resume()});clientRequest.once("error",reject),clientRequest.end(body)})}function normalizePmVersion(value){const trimmed=typeof value=="string"?value.trim():"";return trimmed.length>0?trimmed:"0.0.0"}function normalizeTelemetryErrorCode(value){const normalized=value?.trim();return normalized&&normalized.length>0?normalized:void 0}function normalizeTelemetryExitCode(exitCode,ok){return Number.isFinite(exitCode)?Math.max(0,Math.trunc(exitCode)):ok?0:1}function normalizeTelemetryErrorCategory(params){if(!params.ok)return typeof params.errorCategory=="string"&&params.errorCategory.trim().length>0?params.errorCategory:typeof params.errorCode=="string"&&params.errorCode.trim().length>0?resolveTelemetryErrorCategory(params.errorCode):"unknown"}function resolveTelemetrySourceContext(globalOptions){const resolved=resolveTelemetrySourceAttribution(globalOptions);return resolved.source_context_source==="env_override_rejected"&&!sourceContextWarningEmitted&&!globalOptions.quiet&&(sourceContextWarningEmitted=!0,process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${PM_TELEMETRY_SOURCE_CONTEXT_VALUES.join("|")}; ignoring override.
3
- `)),resolved}function hashWithInstallationId(installationId,value){return crypto.createHash("sha256").update(`${installationId}:${value}`).digest("hex")}function buildAuthorContextPayloadFields(captureLevel,installationId){const author=(readAuthorEnvironment()??"").trim(),agent=detectAgentIdentity({env:process.env,argv:process.argv}),hasAgentContext=agent.harness!==void 0||agent.model!==void 0;return captureLevel==="minimal"?{has_author_context:author.length>0,has_agent_context:hasAgentContext}:{agent_harness:agent.harness?TELEMETRY_HARNESSES.has(agent.harness)?agent.harness:"other":"none",ci:parseBooleanTrueLike(process.env.CI),...author.length>0?{author_context_hash:hashWithInstallationId(installationId,author)}:{},...agent.harness?{agent_harness_hash:hashWithInstallationId(installationId,agent.harness)}:{},...agent.model?{agent_model_hash:hashWithInstallationId(installationId,agent.model)}:{},...agent.model_source?{agent_model_source:agent.model_source}:{}}}function normalizeForHash(value,depth=0){if(value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean")return value;if(depth>=TELEMETRY_SANITIZE_MAX_DEPTH)return"[depth_truncated]";if(Array.isArray(value))return value.slice(0,TELEMETRY_SANITIZE_MAX_ARRAY_ITEMS).map(entry=>normalizeForHash(entry,depth+1));if(typeof value=="object"){const record=value,normalized={},sortedKeys=Object.keys(record).sort((left,right)=>left.localeCompare(right));for(const key of sortedKeys)normalized[key]=normalizeForHash(record[key],depth+1);return normalized}return String(value)}function hashTelemetryValue(installationId,value){return hashWithInstallationId(installationId,JSON.stringify(normalizeForHash(value)))}function hashCommandArgs(installationId,args){return{hashes:args.map(arg=>hashWithInstallationId(installationId,arg)),digest:hashWithInstallationId(installationId,args.join("\0"))}}function hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage){const normalizedMessage=sanitizeString(typeof errorMessage=="string"?errorMessage:"","redacted"),normalizedCode=typeof errorCode2=="string"&&errorCode2.length>0?errorCode2:"unknown_error",fingerprintSource=`${command}\0${normalizedCode}\0${normalizedMessage}`;return hashWithInstallationId(installationId,fingerprintSource)}function resolveOtelTracesEndpoint(){if(PM_TELEMETRY_OTEL_DISABLED_VALUES.has((process.env[PM_TELEMETRY_OTEL_DISABLED_ENV]??"").trim().toLowerCase()))return null;const directEndpoint=(process.env[OTEL_TRACES_ENDPOINT_ENV]??"").trim();if(directEndpoint.length>0)try{return new URL(directEndpoint).toString()}catch{return null}const baseEndpoint=(process.env[OTEL_BASE_ENDPOINT_ENV]??"").trim();if(baseEndpoint.length===0)return null;try{const url=new URL(baseEndpoint),normalizedPath=url.pathname.replace(/\/+$/,"");return normalizedPath.endsWith("/v1/traces")||(url.pathname=`${normalizedPath.length===0?"":normalizedPath}/v1/traces`),url.toString()}catch{return null}}function isoToUnixNano(iso){const parsedMs=Date.parse(iso),epochMs=Number.isNaN(parsedMs)?Date.now():parsedMs;return`${BigInt(epochMs)*1000000n}`}function otlpStringAttribute(key,value){return{key,value:{stringValue:value}}}function otlpBoolAttribute(key,value){return{key,value:{boolValue:value}}}function otlpIntAttribute(key,value){return{key,value:{intValue:String(Math.max(0,Math.trunc(value)))}}}function buildOtelSpanRequest(activeCommand,outcome,finishedAtIso,durationMs,sampleRate=1){const endpoint=activeCommand.otel_traces_endpoint;if(typeof endpoint!="string"||endpoint.trim().length===0||[activeCommand.otel_trace_id,activeCommand.otel_span_id].some(id=>typeof id!="string"||id.length===0))return null;const serviceNameCandidate=sanitizeString((process.env[OTEL_SERVICE_NAME_ENV]??"").trim()),serviceName=serviceNameCandidate.length>0?serviceNameCandidate:"pm-cli",normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok),normalizedErrorCode=normalizeTelemetryErrorCode(outcome.error_code),normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category}),attributes=[otlpStringAttribute("pm.command",sanitizeString(activeCommand.command)),otlpStringAttribute("pm.version",activeCommand.pm_version),otlpStringAttribute("pm.source_context",activeCommand.source_context),otlpStringAttribute("pm.source_context_source",activeCommand.source_context_source),otlpStringAttribute("pm.installation_id",activeCommand.installation_id),otlpStringAttribute("pm.session_id",PROCESS_SESSION_ID),otlpStringAttribute("pm.pm_root_hash",activeCommand.pm_root_hash),otlpStringAttribute("pm.cwd_hash",activeCommand.cwd_hash),otlpBoolAttribute("pm.ok",outcome.ok),otlpIntAttribute("pm.exit_code",normalizedExitCode),otlpIntAttribute("pm.duration_ms",durationMs),otlpStringAttribute("pm.sample_rate",String(sampleRate))];typeof normalizedErrorCode=="string"&&attributes.push(otlpStringAttribute("pm.error_code",normalizedErrorCode)),typeof normalizedErrorCategory=="string"&&attributes.push(otlpStringAttribute("pm.error_category",normalizedErrorCategory)),typeof outcome.error=="string"&&outcome.error.trim().length>0&&attributes.push(otlpStringAttribute("pm.error",sanitizeString(outcome.error)));const payload={resourceSpans:[{resource:{attributes:[otlpStringAttribute("service.name",serviceName)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:activeCommand.otel_trace_id,spanId:activeCommand.otel_span_id,name:`pm.command.${sanitizeString(activeCommand.command)}`,kind:1,startTimeUnixNano:isoToUnixNano(activeCommand.started_at),endTimeUnixNano:isoToUnixNano(finishedAtIso),attributes,status:{code:outcome.ok?1:2,message:outcome.ok?"":sanitizeString(typeof outcome.error=="string"?outcome.error:"command_failed")}}]}]}]};return{endpoint,payload}}function summarizeResult(result,captureLevel="redacted"){if(result==null)return{type:"nullish"};if(typeof result=="string")return{type:"string",value:sanitizeString(result,captureLevel)};if(typeof result=="number"||typeof result=="boolean")return{type:typeof result,value:result};if(Array.isArray(result))return{type:"array",length:result.length,sample:result.slice(0,5).map(entry=>sanitizeValue(entry,void 0,captureLevel))};if(typeof result=="object"){const record=result,keys=Object.keys(record).filter(key=>key!=="tests").sort((left,right)=>left.localeCompare(right)),sanitized={};let previewBytes=0;for(const key of keys.slice(0,25)){const sanitizedValue=sanitizeValue(record[key],key,captureLevel);if(sanitizedValue===void 0)continue;const entrySize=JSON.stringify(sanitizedValue).length;if(previewBytes+entrySize>TELEMETRY_RESULT_PREVIEW_MAX_BYTES){sanitized[key]="[preview_truncated]";break}previewBytes+=entrySize,sanitized[key]=sanitizedValue}return{type:"object",key_count:keys.length,keys_preview:keys.slice(0,50),preview:sanitized}}return{type:typeof result,value:String(result)}}function buildCommandStartPayload(params){const{captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId}=params,commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command),hashedArgs=hashCommandArgs(installationId,context.args),commandInvocationDigest=hashWithInstallationId(installationId,`${context.command}\0${context.args.join("\0")}`),commandOptionsDigest=hashTelemetryValue(installationId,context.options),globalOptionsDigest=hashTelemetryValue(installationId,context.global),authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options_digest:commandOptionsDigest,global_options_digest:globalOptionsDigest,...authorContextFields}:{pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,...authorContextFields,command_args:sanitizeCommandArgs(context.args,captureLevel),command_args_hashes:hashedArgs.hashes,command_args_digest:hashedArgs.digest,command_invocation_digest:commandInvocationDigest,command_options:sanitizeValue(context.options,void 0,captureLevel),command_options_digest:commandOptionsDigest,global_options:sanitizeValue(context.global,void 0,captureLevel),global_options_digest:globalOptionsDigest,pm_root_hash:pmRootHash,cwd_hash:cwdHash,capture_level:captureLevel,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function buildCommandFinishPayload(params){const{captureLevel,pmVersion,sourceContext,outcome,durationMs,startedAt,command,installationId,commandTaxonomy,exitCode,errorCode:errorCode2,errorCategory,commandResolution,resolutionStage}=params,errorFingerprint=outcome.ok===!1?hashTelemetryErrorFingerprint(installationId,command,errorCode2,outcome.error):void 0,authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,"redacted"):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,...authorContextFields}:{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,ok:outcome.ok,exit_code:exitCode,error_code:errorCode2,error_category:errorCategory,error:outcome.error?sanitizeString(outcome.error,captureLevel):void 0,error_fingerprint:errorFingerprint,duration_ms:durationMs,started_at:startedAt,result_summary:summarizeResult(outcome.result,captureLevel)}}function buildCommandErrorPayload(params){const{captureLevel,pmVersion,sourceContext,command,commandTaxonomy,commandResolution,resolutionStage,args,options,pmRootHash,cwdHash,installationId,errorCode:errorCode2,errorMessage,errorCategory,exitCode}=params,attemptedArgHashes=hashCommandArgs(installationId,args),attemptedCommandDigest=hashWithInstallationId(installationId,command),attemptedOptionsDigest=hashTelemetryValue(installationId,options),errorFingerprint=hashTelemetryErrorFingerprint(installationId,command,errorCode2,errorMessage),authorContextFields=buildAuthorContextPayloadFields(captureLevel,installationId);return captureLevel==="minimal"?{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,attempted_command_digest:attemptedCommandDigest,attempted_args_digest:attemptedArgHashes.digest,attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,"redacted"),error_fingerprint:errorFingerprint,...authorContextFields}:{capture_level:captureLevel,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,command_taxonomy:commandTaxonomy,command_resolution:commandResolution,resolution_stage:resolutionStage,...authorContextFields,attempted_command:sanitizeString(command,captureLevel),attempted_command_digest:attemptedCommandDigest,attempted_args:sanitizeCommandArgs(args,captureLevel),attempted_args_hashes:attemptedArgHashes.hashes,attempted_args_digest:attemptedArgHashes.digest,attempted_options:sanitizeValue(options,void 0,captureLevel),attempted_options_digest:attemptedOptionsDigest,error_code:errorCode2,error_category:errorCategory,exit_code:exitCode,error:sanitizeString(errorMessage,captureLevel),error_fingerprint:errorFingerprint,pm_root_hash:pmRootHash,cwd_hash:cwdHash,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:hashWithInstallationId(installationId,os.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function ensureInstallationId(globalPmRoot){const settings=await readSettings(globalPmRoot);if(!settings.telemetry.enabled||resolveTelemetryEnvironmentPolicy().telemetry_disabled)return null;if(settings.telemetry.installation_id.trim().length===0){if(isConfigurationOnlySettingsRead(globalPmRoot)||isSettingsReadFallback(settings))return null;settings.telemetry.installation_id=crypto.randomUUID(),await writeSettings(globalPmRoot,settings,"telemetry:install_id")}return{installationId:settings.telemetry.installation_id,endpoint:settings.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(settings.telemetry.retention_days)),captureLevel:normalizeCaptureLevel(settings.telemetry.capture_level)}}async function appendTelemetryEvent(globalPmRoot,event){let serialized=JSON.stringify({client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event,attempts:0});if(serialized.length>TELEMETRY_MAX_EVENT_BYTES){const trimmed={...event,payload:{...event.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:serialized.length}}};serialized=JSON.stringify({client_schema_version:TELEMETRY_CLIENT_SCHEMA_VERSION,event:trimmed,attempts:0})}await appendLineAtomic(queuePath(globalPmRoot),serialized)}async function enqueueTelemetryEvent(globalPmRoot,event){await withQueueMutation(()=>appendTelemetryEvent(globalPmRoot,event),globalPmRoot)}function parseQueueLines(raw){const entries=[];for(const line of raw.split(`
4
- `)){const trimmed=line.trim();if(trimmed.length!==0)try{const parsed=JSON.parse(trimmed);parsed&&typeof parsed=="object"&&parsed.event&&typeof parsed.event=="object"&&typeof parsed.attempts=="number"&&(parsed.client_schema_version===void 0||typeof parsed.client_schema_version=="number"&&Number.isFinite(parsed.client_schema_version))&&entries.push(parsed)}catch{}}return entries}function nextRetryIso(attempts){const delay=Math.min(TELEMETRY_RETRY_BASE_DELAY_MS*2**Math.max(attempts-1,0),TELEMETRY_MAX_RETRY_DELAY_MS);return new Date(Date.now()+delay).toISOString()}function isDueForRetryAt(nextAttemptAfter){if(typeof nextAttemptAfter!="string"||nextAttemptAfter.trim().length===0)return!0;const dueAtMs=Date.parse(nextAttemptAfter);return Number.isNaN(dueAtMs)?!0:dueAtMs<=Date.now()}function isDueForRetry(entry){return isDueForRetryAt(entry.next_attempt_after)}function retentionCutoffMs(retentionDays){const normalizedDays=Number.isFinite(retentionDays)?Math.max(1,Math.trunc(retentionDays)):1;return Date.now()-normalizedDays*MILLISECONDS_PER_DAY}function isExpiredQueueEntry(entry,cutoffMs){const occurredAt=entry.event?.occurred_at;if(typeof occurredAt!="string"||occurredAt.trim().length===0)return!1;const occurredAtMs=Date.parse(occurredAt);return Number.isNaN(occurredAtMs)?!1:occurredAtMs<cutoffMs}function pruneExpiredQueueEntries(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays),retained=[];let prunedCount=0;for(const entry of entries){if(JSON.stringify(entry).length>TELEMETRY_MAX_EVENT_BYTES||isExpiredQueueEntry(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}return{entries:retained,prunedCount}}async function rewriteQueue(globalPmRoot,entries,override=resolveTelemetryEndpointOverride().endpoint){const serialized=entries.map(entry=>JSON.stringify(entry)).join(`
5
- `),contents=serialized.length>0?`${serialized}
6
- `:"";for(let attempt=0;;attempt+=1)try{await writeFileAtomic(queuePath(globalPmRoot,override),contents,{createParentDirectories:!parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])});return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error))throw error;await sleep(retryDelay)}}function isRetryableQueueRewriteError(error){if(typeof error!="object"||error===null||!("code"in error))return!1;const code=error.code;return code==="EACCES"||code==="EBUSY"||code==="EPERM"}function sleep(milliseconds){return new Promise(resolve=>{setTimeout(resolve,milliseconds)})}async function appendPendingOtelSpan(globalPmRoot,request){const pending={id:crypto.randomUUID(),endpoint:request.endpoint,payload:request.payload,enqueued_at:nowIso(),attempts:0},serialized=JSON.stringify(pending);serialized.length>TELEMETRY_MAX_EVENT_BYTES||await appendLineAtomic(otelSpansQueuePath(globalPmRoot),serialized)}async function enqueuePendingOtelSpan(globalPmRoot,request){await withQueueMutation(()=>appendPendingOtelSpan(globalPmRoot,request),globalPmRoot)}function backfillPendingOtelSpanId(entry){const material=JSON.stringify([entry.endpoint,entry.enqueued_at,entry.payload]);return crypto.createHash("sha256").update(material).digest("hex").slice(0,32)}function parsePendingOtelSpanLines(raw){const entries=[];for(const line of raw.split(`
7
- `)){const trimmed=line.trim();if(trimmed.length!==0)try{const parsed=JSON.parse(trimmed);parsed&&typeof parsed=="object"&&typeof parsed.endpoint=="string"&&parsed.endpoint.trim().length>0&&"payload"in parsed&&typeof parsed.attempts=="number"&&Number.isFinite(parsed.attempts)&&((typeof parsed.id!="string"||parsed.id.length===0)&&(parsed.id=backfillPendingOtelSpanId(parsed)),entries.push(parsed))}catch{}}return entries}function isExpiredPendingOtelSpan(entry,cutoffMs){if(typeof entry.enqueued_at!="string"||entry.enqueued_at.trim().length===0)return!1;const enqueuedAtMs=Date.parse(entry.enqueued_at);return Number.isNaN(enqueuedAtMs)?!1:enqueuedAtMs<cutoffMs}function prunePendingOtelSpans(entries,retentionDays){const cutoffMs=retentionCutoffMs(retentionDays),retained=[];let prunedCount=0;for(const entry of entries){if(JSON.stringify(entry).length>TELEMETRY_MAX_EVENT_BYTES||isExpiredPendingOtelSpan(entry,cutoffMs)||entry.attempts>=TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS){prunedCount+=1;continue}retained.push(entry)}if(retained.length>TELEMETRY_OTEL_SPANS_MAX_PENDING){const overflow=retained.length-TELEMETRY_OTEL_SPANS_MAX_PENDING;return prunedCount+=overflow,{entries:retained.slice(overflow),prunedCount}}return{entries:retained,prunedCount}}async function rewritePendingOtelSpans(globalPmRoot,entries){const serialized=entries.map(entry=>JSON.stringify(entry)).join(`
8
- `),contents=serialized.length>0?`${serialized}
9
- `:"";for(let attempt=0;;attempt+=1)try{await writeFileAtomic(otelSpansQueuePath(globalPmRoot),contents,{createParentDirectories:!parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])});return}catch(error){const retryDelay=TELEMETRY_QUEUE_REWRITE_RETRY_DELAYS_MS[attempt];if(retryDelay===void 0||!isRetryableQueueRewriteError(error))throw error;await sleep(retryDelay)}}async function reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates){return withQueueMutation(async()=>{const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot)),current=raw===null?[]:parsePendingOtelSpanLines(raw),reconciled=[];for(const entry of current){if(succeededIds.has(entry.id))continue;const failure=failedUpdates.get(entry.id);reconciled.push(failure?{...entry,attempts:failure.attempts,next_attempt_after:failure.next_attempt_after}:entry)}const{entries:retained}=prunePendingOtelSpans(reconciled,retentionDays);return await rewritePendingOtelSpans(globalPmRoot,retained),retained.length},globalPmRoot)}async function flushPendingOtelSpans(globalPmRoot,retentionDays){const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));if(raw===null||raw.trim().length===0){await writeRuntimeState(globalPmRoot,{pending_otel_spans:0},null);return}const entries=parsePendingOtelSpanLines(raw),{entries:retained,prunedCount}=prunePendingOtelSpans(entries,retentionDays),due=retained.filter(entry=>isDueForRetryAt(entry.next_attempt_after)).slice(0,TELEMETRY_OTEL_SPANS_FLUSH_BATCH_SIZE);if(due.length===0){const remaining2=prunedCount>0?await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,new Set,new Map):retained.length;await writeRuntimeState(globalPmRoot,{pending_otel_spans:remaining2},null);return}const attemptTime=nowIso(),succeededIds=new Set,failedUpdates=new Map;let succeededCount=0,lastError;await Promise.all(due.map(async span=>{try{const status=await postTelemetryJson(span.endpoint,{"content-type":"application/json"},JSON.stringify(span.payload));if(status<200||status>=300)throw new Error(`local_otel_export_http_${status}`);succeededIds.add(span.id),succeededCount+=1}catch(error){lastError=error instanceof Error?sanitizeString(redactUrlsInText(error.message),"redacted"):"local_otel_export_failed";const nextAttempts=span.attempts+1;failedUpdates.set(span.id,{attempts:nextAttempts,next_attempt_after:nextRetryIso(nextAttempts)})}}));const remaining=await reconcilePendingOtelSpansAfterFlush(globalPmRoot,retentionDays,succeededIds,failedUpdates),statePatch={pending_otel_spans:remaining,last_otel_attempt_at:attemptTime};succeededCount>0&&(statePatch.last_otel_success_at=attemptTime),lastError!==void 0?(statePatch.last_otel_failure_at=attemptTime,statePatch.last_otel_failure_error=lastError):remaining===0&&(statePatch.last_otel_failure_at=void 0,statePatch.last_otel_failure_error=void 0),await writeRuntimeState(globalPmRoot,statePatch,null)}async function flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays){try{await flushQueue(globalPmRoot,endpoint,retentionDays)}catch{}try{await flushPendingOtelSpans(globalPmRoot,retentionDays)}catch{}}async function cleanupTelemetryQueueTempOrphans(globalPmRoot,maxAgeMs=TELEMETRY_QUEUE_TMP_ORPHAN_MAX_AGE_MS,activeOverride=resolveTelemetryEndpointOverride().endpoint){try{const dirPath=telemetryRuntimeDirectory(globalPmRoot),entries=await readdir(dirPath,{withFileTypes:!0}),now=Date.now(),active=new Set([telemetryRuntimeFileName("events.jsonl",activeOverride),telemetryRuntimeFileName("state.json",activeOverride)]),cutoffFor=name=>{if(!active.has(name))return/^\.events(?:\.[a-f0-9]{16})?\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(name)?now-Math.max(0,maxAgeMs):/^(?:events\.[a-f0-9]{16}\.jsonl|state\.[a-f0-9]{16}\.json)$/.test(name)?now-TELEMETRY_OVERRIDE_QUEUE_MAX_IDLE_MS:void 0};await Promise.all(entries.map(async entry=>{const cutoffMs=entry.isFile()?cutoffFor(entry.name):void 0;if(cutoffMs===void 0)return;const candidate=path.join(dirPath,entry.name);(await stat(candidate)).mtimeMs<cutoffMs&&await rm(candidate,{force:!0})}))}catch{}}async function withQueueMutation(operation,globalPmRoot=resolveGlobalPmRoot(process.cwd()),waitMs=5e3){const run=_queueMutationPromise.catch(()=>{}).then(()=>runWithIsolatedExtensionRuntime(async()=>{const release=await acquireLock(globalPmRoot,"telemetry-queue",60,"telemetry",!1,!1,waitMs,{createParentDirectories:!parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])});try{return clearSettingsReadCache(globalPmRoot),await operation()}finally{await release()}}));return _queueMutationPromise=run.catch(()=>{}),run}async function readCurrentQueueEntries(globalPmRoot,override=resolveTelemetryEndpointOverride().endpoint){const raw=await readFileIfExists(queuePath(globalPmRoot,override));return raw===null||raw.trim().length===0?[]:parseQueueLines(raw)}async function removeFlushedEntriesFromCurrentQueue(globalPmRoot,flushedIds,retentionDays,override=resolveTelemetryEndpointOverride().endpoint){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot,override),{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays),remaining=retainedEntries.filter(entry=>!flushedIds.has(entry.event.event_id));return await rewriteQueue(globalPmRoot,remaining,override),remaining},globalPmRoot)}async function markFailedEntriesInCurrentQueue(globalPmRoot,failedIds,attemptTime,retentionDays,override=resolveTelemetryEndpointOverride().endpoint){return withQueueMutation(async()=>{const currentEntries=await readCurrentQueueEntries(globalPmRoot,override),{entries:retainedEntries}=pruneExpiredQueueEntries(currentEntries,retentionDays),retried=retainedEntries.map(entry=>{if(!failedIds.has(entry.event.event_id))return entry;const attempts=entry.attempts+1;return{...entry,attempts,last_attempt_at:attemptTime,next_attempt_after:nextRetryIso(attempts)}});return await rewriteQueue(globalPmRoot,retried,override),retried},globalPmRoot)}function recordedStateEndpoint(endpoint,override){return override===null?endpoint:redactTelemetryEndpoint(endpoint)}async function flushQueue(globalPmRoot,endpoint,retentionDays){const override=resolveTelemetryEndpointOverride().endpoint;await cleanupTelemetryQueueTempOrphans(globalPmRoot,void 0,override);const normalizedEndpoint=(override??endpoint).trim(),stateEndpoint=recordedStateEndpoint(normalizedEndpoint,override),writeState=patch=>writeRuntimeState(globalPmRoot,patch,override);if(normalizedEndpoint.length===0)return;const raw=await readFileIfExists(queuePath(globalPmRoot,override));if(raw===null||raw.trim().length===0){await writeState({endpoint:stateEndpoint,queue_entries:0});return}const queueEntries=parseQueueLines(raw);if(queueEntries.length===0){await writeState({endpoint:stateEndpoint,queue_entries:0});return}const{entries:retainedEntries,prunedCount}=pruneExpiredQueueEntries(queueEntries,retentionDays);if(retainedEntries.length===0){const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays,override);await writeState({endpoint:stateEndpoint,queue_entries:remaining.length});return}const dueEntries=retainedEntries.filter(entry=>isDueForRetry(entry)).slice(0,TELEMETRY_FLUSH_BATCH_SIZE);if(dueEntries.length===0){const remaining=prunedCount>0?await removeFlushedEntriesFromCurrentQueue(globalPmRoot,new Set,retentionDays,override):retainedEntries;await writeState({endpoint:stateEndpoint,queue_entries:remaining.length});return}const dueIds=new Set(dueEntries.map(entry=>entry.event.event_id)),attemptTime=nowIso(),requestHeaders={"content-type":"application/json"},ingestKey=process.env.PM_TELEMETRY_INGEST_KEY?.trim();ingestKey&&(requestHeaders["x-pm-telemetry-key"]=ingestKey);try{const status=await postTelemetryJson(normalizedEndpoint,requestHeaders,JSON.stringify({schema_version:TELEMETRY_SCHEMA_VERSION,events:dueEntries.map(entry=>entry.event)}));if(status<200||status>=300)throw new Error(`telemetry_flush_http_${status}`)}catch(error){const retried=await markFailedEntriesInCurrentQueue(globalPmRoot,dueIds,attemptTime,retentionDays,override),errorMessage=error instanceof Error?sanitizeString(redactUrlsInText(error.message),"redacted"):"telemetry_flush_failed";await writeState({endpoint:stateEndpoint,queue_entries:retried.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage});return}try{const remaining=await removeFlushedEntriesFromCurrentQueue(globalPmRoot,dueIds,retentionDays,override);await writeState({endpoint:stateEndpoint,queue_entries:remaining.length,last_attempted_flush_at:attemptTime,last_successful_flush_at:attemptTime,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(error){const errorMessage=error instanceof Error?sanitizeString(redactUrlsInText(error.message),"redacted"):"telemetry_flush_failed",currentEntries=await readCurrentQueueEntries(globalPmRoot,override).catch(()=>retainedEntries);await writeState({endpoint:stateEndpoint,queue_entries:currentEntries.length,last_attempted_flush_at:attemptTime,last_failed_flush_at:attemptTime,last_failed_flush_error:errorMessage})}}async function acquireTelemetryFlushLock(globalPmRoot){const lockPath=flushLockPath(globalPmRoot);parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV])||await mkdir(path.dirname(lockPath),{recursive:!0});try{return await mkdir(lockPath),!0}catch(error){if(typeof error!="object"||error===null||!("code"in error)||error.code!=="EEXIST")throw error}try{const lockStats=await stat(lockPath);return Date.now()-lockStats.mtimeMs<TELEMETRY_FLUSH_LOCK_STALE_MS?!1:(await rm(lockPath,{recursive:!0,force:!0}),await mkdir(lockPath),!0)}catch{return!1}}function isFreshDirectoryLock(lockPath,staleMs){try{return Date.now()-statSync(lockPath).mtimeMs<staleMs}catch{return!1}}function removeDirectoryLockBestEffort(lockPath){try{rmSync(lockPath,{recursive:!0,force:!0})}catch{}}function errorCode(error){if(typeof error!="object"||error===null||!("code"in error))return;const code=error.code;return typeof code=="string"?code:void 0}function createDirectoryLock(lockPath){try{return mkdirSync(lockPath),!0}catch(error){if(errorCode(error)==="EEXIST"||!isFileMissingError(error))return!1}try{return mkdirSync(path.dirname(lockPath),{recursive:!0}),mkdirSync(lockPath),!0}catch{return!1}}function acquireTelemetryFlushSpawnGate(globalPmRoot){if(isFreshDirectoryLock(flushLockPath(globalPmRoot),TELEMETRY_FLUSH_LOCK_STALE_MS))return!1;const lockPath=flushSpawnLockPath(globalPmRoot);try{if(Date.now()-statSync(lockPath).mtimeMs<TELEMETRY_FLUSH_SPAWN_LOCK_STALE_MS)return!1;removeDirectoryLockBestEffort(lockPath)}catch(error){if(!isFileMissingError(error))return!1}return createDirectoryLock(lockPath)}function releaseTelemetryFlushSpawnGate(globalPmRoot){removeDirectoryLockBestEffort(flushSpawnLockPath(globalPmRoot))}const _testOnly={queuePath,cleanupTelemetryQueueTempOrphans,acquireTelemetryFlushSpawnGate,acquireTelemetryFlushLock,buildAuthorContextPayloadFields,buildCommandErrorPayload,buildCommandFinishPayload,buildCommandStartPayload,buildOtelSpanRequest,createDirectoryLock,enqueuePendingOtelSpan,enqueueTelemetryEvent,errorCode,flushPendingOtelSpans,flushQueue,flushQueueWithProcessLock,flushTelemetryArtifacts,hashTelemetryErrorFingerprint,hashTelemetryValue,isEmailDomainCharacter,isEmailLocalCharacter,isExpiredPendingOtelSpan,isExpiredQueueEntry,isFreshDirectoryLock,isDueForRetry,isDueForRetryAt,isRetryableQueueRewriteError,looksLikeEmailToken,otelSpansQueuePath,parseBooleanTrueLike,postTelemetryJson,parsePendingOtelSpanLines,prunePendingOtelSpans,reconcilePendingOtelSpansAfterFlush,retentionCutoffMs,resolveOtelTracesEndpoint,resolveTelemetryHttpTimeoutMs,rewritePendingOtelSpans,normalizeForHash,normalizeCaptureLevel,normalizePmVersion,normalizeTelemetryErrorCategory,normalizeTelemetryErrorCode,normalizeTelemetryExitCode,parseQueueLines,pruneExpiredQueueEntries,readRuntimeState,readCurrentQueueEntries,releaseTelemetryFlushSpawnGate,removeFlushedEntriesFromCurrentQueue,removeDirectoryLockBestEffort,resolveTelemetrySourceContext,rewriteQueue,sanitizeCommandArgs,sanitizeStringMax,sanitizeStringRedacted,sanitizeValue,scheduleTelemetryFlush,shouldFlushInline,sleep,summarizeResult,telemetryFlushRunnerPath,withQueueMutation,flushLockPath,flushSpawnLockPath,runtimeStatePath,writeRuntimeState};async function flushQueueWithProcessLock(globalPmRoot,endpoint,retentionDays){const acquired=await acquireTelemetryFlushLock(globalPmRoot);if(releaseTelemetryFlushSpawnGate(globalPmRoot),!acquired)return!1;try{await flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays)}finally{try{await rm(flushLockPath(globalPmRoot),{recursive:!0,force:!0})}catch{}}return!0}async function dueTelemetryArtifactIds(globalPmRoot,retentionDays){const ids=new Set;try{const{entries}=pruneExpiredQueueEntries(await readCurrentQueueEntries(globalPmRoot),retentionDays);for(const entry of entries.filter(isDueForRetry))ids.add(`event:${entry.event.event_id}`)}catch{}try{const raw=await readFileIfExists(otelSpansQueuePath(globalPmRoot));if(raw!==null)for(const entry of prunePendingOtelSpans(parsePendingOtelSpanLines(raw),retentionDays).entries)isDueForRetryAt(entry.next_attempt_after)&&ids.add(`span:${entry.id}`)}catch{}return ids}function scheduleTelemetryFlush(globalPmRoot,endpoint,retentionDays){if(!isConfigurationOnlySettingsRead(globalPmRoot)){if(shouldFlushInline())return _lastFlushPromise=_lastFlushPromise.then(()=>flushTelemetryArtifacts(globalPmRoot,endpoint,retentionDays)),_lastFlushPromise;try{if(!acquireTelemetryFlushSpawnGate(globalPmRoot))return;const child=spawn(process.execPath,[telemetryFlushRunnerPath()],{detached:!0,stdio:"ignore",cwd:os.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:globalPmRoot,[PM_TELEMETRY_FLUSH_CHILD_ENV]:"1"}});child.on("error",()=>{releaseTelemetryFlushSpawnGate(globalPmRoot)}),child.unref()}catch{releaseTelemetryFlushSpawnGate(globalPmRoot)}}}async function flushTelemetryQueueNow(globalPmRoot=resolveGlobalPmRoot(process.cwd())){if(!resolveTelemetryEnvironmentPolicy().telemetry_disabled)try{await runWithConfigurationOnlySettings(globalPmRoot,async()=>{const detached=parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV]);let continueDraining=!0;for(;continueDraining;){if(!(await readSettings(globalPmRoot)).telemetry.enabled)return;const installation=await withQueueMutation(()=>ensureInstallationId(globalPmRoot),globalPmRoot);if(!installation)return;const before=detached?await dueTelemetryArtifactIds(globalPmRoot,installation.retentionDays):new Set;if(!await flushQueueWithProcessLock(globalPmRoot,installation.endpoint,installation.retentionDays)||!detached)return;const after=await dueTelemetryArtifactIds(globalPmRoot,installation.retentionDays);continueDraining=after.size>0&&(after.size!==before.size||[...after].some(id=>!before.has(id)))}},()=>parseBooleanTrueLike(process.env[PM_TELEMETRY_FLUSH_CHILD_ENV]))}catch{}}async function startTelemetryCommand(context){if(resolveTelemetryEnvironmentPolicy().telemetry_disabled||context.command==="telemetry"&&context.args.some(token=>token.trim().toLowerCase()==="clear"))return null;try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());if(!(await readSettings(globalPmRoot)).telemetry.enabled)return null;const coreReadOwned=context.global.noExtensions===!0||isActiveCommandUnextended(context.command),activeCommand=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,endpoint,retentionDays,captureLevel}=installation,pmVersion=normalizePmVersion(context.pm_version),sourceContext=resolveTelemetrySourceContext(context.global),pmRootHash=hashWithInstallationId(installationId,context.pm_root),cwdHash=hashWithInstallationId(installationId,process.cwd()),otelTracesEndpoint=resolveOtelTracesEndpoint(),occurredAt=nowIso(),event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_start",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:context.command,payload:buildCommandStartPayload({captureLevel,context,pmVersion,sourceContext,pmRootHash,cwdHash,installationId})},sampleRate=await resolveAutomaticReadSampleRate(globalPmRoot,context.command,coreReadOwned);sampleRate===1&&await appendTelemetryEvent(globalPmRoot,event);const commandTaxonomy=deriveTelemetryCommandTaxonomy(context.command),active={...sampleRate<1?{sample_rate:sampleRate}:{},started_at:occurredAt,started_at_ms:Date.now(),command:context.command,command_taxonomy:commandTaxonomy,pm_version:pmVersion,source_context:sourceContext.source_context,source_context_source:sourceContext.source_context_source,installation_id:installationId,pm_root_hash:pmRootHash,cwd_hash:cwdHash,endpoint,retention_days:retentionDays,global_pm_root:globalPmRoot,capture_level:captureLevel,otel_traces_endpoint:otelTracesEndpoint??void 0,otel_trace_id:otelTracesEndpoint?crypto.randomBytes(16).toString("hex"):void 0,otel_span_id:otelTracesEndpoint?crypto.randomBytes(8).toString("hex"):void 0};return sampleRate<1&&deferredReadStarts.set(active,event),active},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);return activeCommand&&activeCommand.sample_rate===void 0&&scheduleTelemetryFlush(globalPmRoot,activeCommand.endpoint,activeCommand.retention_days),activeCommand}catch{return null}}async function finishTelemetryCommand(activeCommand,outcome){if(!(!activeCommand||resolveTelemetryEnvironmentPolicy().telemetry_disabled))try{if(!await withQueueMutation(async()=>{const settings=await readSettings(activeCommand.global_pm_root);if(resolveTelemetryEnvironmentPolicy().telemetry_disabled||!settings.telemetry.enabled||settings.telemetry.installation_id!==activeCommand.installation_id)return deferredReadStarts.delete(activeCommand),!1;const deferredStart=deferredReadStarts.get(activeCommand),sampleRate=outcome.ok?activeCommand.sample_rate??1:1;if(deferredStart){if(deferredReadStarts.delete(activeCommand),crypto.randomBytes(6).readUIntBE(0,6)/281474976710656>=sampleRate)return!1;deferredStart.payload.sample_rate=sampleRate,await appendTelemetryEvent(activeCommand.global_pm_root,deferredStart)}const finishedAt=nowIso(),durationMs=Math.max(0,Date.now()-activeCommand.started_at_ms),normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:outcome.ok,errorCode:outcome.error_code,errorMessage:outcome.error,exitCode:outcome.exit_code})),normalizedErrorCategory=normalizeTelemetryErrorCategory({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:outcome.error_category}),normalizedExitCode=normalizeTelemetryExitCode(outcome.exit_code,outcome.ok),commandResolution=outcome.command_resolution??deriveTelemetryCommandResolution({ok:outcome.ok,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory}),resolutionStage=outcome.resolution_stage??"execute",event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_finish",occurred_at:finishedAt,installation_id:activeCommand.installation_id,session_id:PROCESS_SESSION_ID,command:activeCommand.command,payload:{...deferredStart?{sample_rate:sampleRate}:{},...buildCommandFinishPayload({captureLevel:activeCommand.capture_level,pmVersion:activeCommand.pm_version,sourceContext:{source_context:activeCommand.source_context,source_context_source:activeCommand.source_context_source},outcome,durationMs,startedAt:activeCommand.started_at,command:activeCommand.command,installationId:activeCommand.installation_id,commandTaxonomy:activeCommand.command_taxonomy,exitCode:normalizedExitCode,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,commandResolution,resolutionStage})}};await appendTelemetryEvent(activeCommand.global_pm_root,event);const otelRequest=buildOtelSpanRequest(activeCommand,{...outcome,exit_code:normalizedExitCode,error_code:normalizedErrorCode,error_category:normalizedErrorCategory},finishedAt,durationMs,sampleRate);return otelRequest&&await appendPendingOtelSpan(activeCommand.global_pm_root,otelRequest),!0},activeCommand.global_pm_root,TELEMETRY_FOREGROUND_LOCK_WAIT_MS))return;await scheduleTelemetryFlush(activeCommand.global_pm_root,activeCommand.endpoint,activeCommand.retention_days)}catch{}}async function emitTelemetryErrorEvent(context){if(!resolveTelemetryEnvironmentPolicy().telemetry_disabled)try{const globalPmRoot=resolveGlobalPmRoot(process.cwd());if(!(await readSettings(globalPmRoot)).telemetry.enabled)return;const captured=await withQueueMutation(async()=>{const installation=await ensureInstallationId(globalPmRoot);if(!installation)return null;const{installationId,captureLevel}=installation,pmVersion=normalizePmVersion(context.pm_version),sourceContext=resolveTelemetrySourceContext(context.global),pmRootHash=hashWithInstallationId(installationId,context.pm_root),cwdHash=hashWithInstallationId(installationId,process.cwd()),occurredAt=nowIso(),normalizedErrorCode=normalizeTelemetryErrorCode(inferTelemetryErrorCode({ok:!1,errorCode:context.error_code,errorMessage:context.error_message,exitCode:context.exit_code})),normalizedErrorCategory=context.error_category??resolveTelemetryErrorCategory(normalizedErrorCode),normalizedExitCode=normalizeTelemetryExitCode(context.exit_code,!1),normalizedCommand=context.command.trim().length>0?context.command:"<unknown>",commandTaxonomy=deriveTelemetryCommandTaxonomy(normalizedCommand),commandResolution=context.command_resolution??deriveTelemetryCommandResolution({ok:!1,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory}),resolutionStage=context.resolution_stage??"unknown",event={schema_version:TELEMETRY_SCHEMA_VERSION,event_id:crypto.randomUUID(),event_type:"command_error",occurred_at:occurredAt,installation_id:installationId,session_id:PROCESS_SESSION_ID,command:sanitizeString(normalizedCommand,"redacted"),payload:buildCommandErrorPayload({captureLevel,pmVersion,sourceContext,command:normalizedCommand,commandTaxonomy,commandResolution,resolutionStage,args:context.args,options:context.options,pmRootHash,cwdHash,installationId,errorCode:normalizedErrorCode,errorCategory:normalizedErrorCategory,exitCode:normalizedExitCode,errorMessage:context.error_message})};return await appendTelemetryEvent(globalPmRoot,event),installation},globalPmRoot,TELEMETRY_FOREGROUND_LOCK_WAIT_MS);captured&&await scheduleTelemetryFlush(globalPmRoot,captured.endpoint,captured.retentionDays)}catch{}}export{PM_TELEMETRY_SOURCE_CONTEXT_VALUES2 as PM_TELEMETRY_SOURCE_CONTEXT_VALUES,TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,TELEMETRY_SCHEMA_VERSION,_testOnly,emitTelemetryErrorEvent,finishTelemetryCommand,flushTelemetryQueueNow,startTelemetryCommand,waitForPendingFlush,withQueueMutation as withTelemetryQueueMutation};
1
+ import M from"node:crypto";import{spawn as zt}from"node:child_process";import{mkdirSync as se,rmSync as Yt,statSync as Ye}from"node:fs";import{mkdir as ie,readdir as bt,rm as ae,stat as be}from"node:fs/promises";import{request as Ft}from"node:http";import{request as jt}from"node:https";import ce from"node:os";import y from"node:path";import{acquireLock as Ht}from"../lock/lock.js";import{isActiveCommandUnextended as Vt,runWithIsolatedExtensionRuntime as qt}from"../extensions/index.js";import{resolveAutomaticReadSampleRate as $t}from"./read-sampling.js";import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as Bt,isTelemetryTestEnvironment as Qt,redactTelemetryEndpoint as Jt,redactUrlsInText as ue,resolveTelemetryEndpointOverride as L,resolveTelemetryEnvironmentPolicy as C,resolveTelemetrySourceAttribution as Xt,telemetryRuntimeFileName as F}from"./policy.js";import{redactUrlCredentialsInText as Wt,redactUrlCredentialsInToken as Gt}from"../shared/url-credentials.js";import{resolvePmPackageRootFromModule as Kt}from"../packages/root.js";import{isFileMissingError as Fe,appendLineAtomic as je,readFileIfExists as R,writeFileAtomic as de}from"../fs/fs-utils.js";import{resolveTelemetryErrorCategory as He}from"../shared/constants.js";import{nowIso as v}from"../shared/time.js";import{detectAgentIdentity as Zt,readAuthorEnvironment as en}from"../shared/author.js";import{resolveGlobalPmRoot as j}from"../store/paths.js";import{isConfigurationOnlySettingsRead as Ve,isSettingsReadFallback as tn,readSettings as P,runWithConfigurationOnlySettings as nn,writeSettings as rn}from"../store/settings.js";import{clearSettingsReadCache as on}from"../store/settings-read-cache.js";import{deriveTelemetryCommandResolution as qe,deriveTelemetryCommandTaxonomy as le,inferTelemetryErrorCode as $e}from"./observability.js";const sn=y.join("runtime","telemetry","events.jsonl"),an=y.join("runtime","telemetry","state.json"),cn=y.join("runtime","telemetry","otel-spans.jsonl"),un=8,Be=500,H=1,Qe=1,dn=100,ln=36e5,_n=3e4,Je=2e4,mn=1e3,fn=25e3,_e=250,pn=864e5,V=65536,Xe=6,We=20,Ge=15,hn=8192,Ke=[25,50,100,200],En=3600*1e3,yn=1440*60*1e3,Ze=6e4,gn=6e4,Tn="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",wn="OTEL_EXPORTER_OTLP_ENDPOINT",Sn="OTEL_SERVICE_NAME",Mn="PM_TELEMETRY_OTEL_DISABLED",xn=new Set(["1","true","yes","on"]),An="PM_TELEMETRY_INLINE_FLUSH",I="PM_TELEMETRY_FLUSH_CHILD",Ln="PM_TELEMETRY_HTTP_TIMEOUT_MS",In=globalThis.fetch;import{PM_TELEMETRY_SOURCE_CONTEXT_VALUES as wr}from"./policy.js";let et=!1,q=Promise.resolve(),me=Promise.resolve();const $=new WeakMap;async function mr(){await q,await me}const Nn=new Set(["1","true","yes","on"]),On=new Set(["claude-code","codex","pi","opencode","cursor","aider","gemini-cli","ci"]),B=M.randomUUID(),Cn=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],Rn=new Set(["literal","literals","regex","regexes","replacement","replacements","setjson","set_json","update"]),tt="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",vn=new RegExp(`\\b(${tt})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),kn=new RegExp(`(--${tt})(=|\\s+)([^\\s,;]+)`,"giu"),Dn=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,Pn=/bearer\s+[a-z0-9._=-]+/giu,Un=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function k(e,t=L().endpoint){return y.join(y.dirname(y.join(e,sn)),F("events.jsonl",t))}function D(e){return y.join(e,cn)}function zn(e){return y.dirname(k(e,null))}function fe(e,t=L().endpoint){return y.join(y.dirname(y.join(e,an)),F("state.json",t))}function Q(e){return y.join(e,"runtime","telemetry","flush.lock")}function pe(e){return y.join(e,"runtime","telemetry","flush.spawn.lock")}function nt(){return y.join(Kt(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function rt(){return x(process.env[An])||x(process.env[I])?!0:Qt()}async function ot(e,t=L().endpoint){const r=await R(fe(e,t));if(!r||r.trim().length===0)return{};try{const n=JSON.parse(r);return typeof n!="object"||n===null||Array.isArray(n)?{}:n}catch{return{}}}async function U(e,t,r=L().endpoint){try{await S(async()=>{const o={...await ot(e,r),...t},s=Object.fromEntries(Object.entries(o).filter(([,i])=>i!==void 0).sort((i,a)=>i[0].localeCompare(a[0])));await de(fe(e,r),`${JSON.stringify(s,null,2)}
2
+ `,{createParentDirectories:!x(process.env[I])})},e)}catch{}}function he(e){const t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),r=t.split("_").filter(n=>n.length>0);return Rn.has(t)||Cn.some(n=>t===n||t.endsWith(`_${n}`)||r.includes(n))}function st(e){return e.replaceAll(vn,(r,n,o)=>`${n}${o}[redacted]`).replaceAll(kn,(r,n,o)=>`${n}${o}[redacted]`)}function it(e){return e.replaceAll(Dn,(t,r)=>`${r}[redacted_path]`)}function at(e){const t=e>=65&&e<=90,r=e>=97&&e<=122,n=e>=48&&e<=57;return t||r||n}function Ee(e){if(!e)return!1;const t=e.charCodeAt(0);return at(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function ye(e){if(!e)return!1;const t=e.charCodeAt(0);return at(t)?!0:e==="."||e==="-"}function ct(e){const t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@")||t===e.length-1)return!1;const r=e.slice(0,t),n=e.slice(t+1),o=n.lastIndexOf(".");if(o<=0||o===n.length-1||n.length-(o+1)<2)return!1;for(const s of r)if(!Ee(s))return!1;for(const s of n)if(!ye(s))return!1;return!0}function Yn(e){let t="",r=0;for(;r<e.length;){const n=e.indexOf("@",r);if(n<0){t+=e.slice(r);break}let o=n-1;for(;o>=r&&Ee(e[o]);)o-=1;o+=1;let s=n+1;for(;s<e.length&&ye(e[s]);)s+=1;const i=e.slice(o,s);if(ct(i)){t+=e.slice(r,o),t+="[redacted_email]",r=s;continue}t+=e.slice(r,n+1),r=n+1}return t}function ut(e){return Yn(Wt(e)).replaceAll(Pn,"bearer [redacted_token]").replaceAll(Un,"[redacted_ip]")}function dt(e){const t=ut(e),r=st(t),n=it(r),o=n.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":n.length>512?`${n.slice(0,509)}...`:n}function lt(e){const t=ut(e),r=st(t),n=it(r),o=n.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":n.length>2048?`${n.slice(0,2045)}...`:n}function E(e,t="redacted"){return t==="max"?lt(e):dt(e)}function N(e,t,r="redacted",n=0){if(t&&he(t))return"[redacted]";if(e==null)return e;if(typeof e=="string")return E(e,r);if(typeof e=="number"||typeof e=="boolean")return e;if(n>=Xe)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,We).map(o=>N(o,void 0,r,n+1));if(typeof e=="object"){const o=e,s={};for(const[i,a]of Object.entries(o))s[i]=N(a,i,r,n+1);return s}return String(e)}function ge(e,t="redacted"){const r=[];let n=!1;for(const o of e){const s=E(Gt(o),t);if(n){r.push("[redacted]"),n=!1;continue}if(s.startsWith("--")){const i=s.slice(2),a=i.indexOf("=");if(a>=0){const c=i.slice(0,a),u=i.slice(a+1);he(c)?r.push(`--${c}=[redacted]`):r.push(`--${c}=${E(u,t)}`);continue}if(he(i)){r.push(`--${i}`),n=!0;continue}}r.push(s)}return r}function _t(e){const t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function x(e){return Nn.has((e??"").trim().toLowerCase())}function Te(){const e=process.env[Ln]?.trim();if(!e)return Je;const t=Number(e);return Number.isFinite(t)?Math.min(fn,Math.max(mn,Math.trunc(t))):Je}async function we(e,t,r){const n=new URL(e);if(globalThis.fetch!==In){const s=new AbortController;let i;const a=new Promise((c,u)=>{i=setTimeout(()=>{s.abort(),u(new Error("telemetry_http_timeout"))},Te())});try{return(await Promise.race([globalThis.fetch(e,{method:"POST",headers:t,body:r,signal:s.signal}),a])).status}finally{clearTimeout(i)}}const o=n.protocol==="https:"?jt:n.protocol==="http:"?Ft:void 0;if(!o)throw new Error(`telemetry_http_protocol_unsupported_${n.protocol}`);return new Promise((s,i)=>{const a=Te(),c={method:"POST",headers:{...t,"content-length":Buffer.byteLength(r)},signal:AbortSignal.timeout(a),autoSelectFamilyAttemptTimeout:Math.min(5e3,a)},u=o(n,c,_=>{_.once("error",i),_.once("end",()=>s(_.statusCode)),_.resume()});u.once("error",i),u.end(r)})}function Se(e){const t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function J(e){const t=e?.trim();return t&&t.length>0?t:void 0}function X(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Me(e){if(!e.ok)return typeof e.errorCategory=="string"&&e.errorCategory.trim().length>0?e.errorCategory:typeof e.errorCode=="string"&&e.errorCode.trim().length>0?He(e.errorCode):"unknown"}function xe(e){const t=Xt(e);return t.source_context_source==="env_override_rejected"&&!et&&!e.quiet&&(et=!0,process.stderr.write(`[pm] warning: PM_TELEMETRY_SOURCE_CONTEXT is not one of ${Bt.join("|")}; ignoring override.
3
+ `)),t}function T(e,t){return M.createHash("sha256").update(`${e}:${t}`).digest("hex")}function W(e,t){const r=(en()??"").trim(),n=Zt({env:process.env,argv:process.argv}),o=n.harness!==void 0||n.model!==void 0;return e==="minimal"?{has_author_context:r.length>0,has_agent_context:o}:{agent_harness:n.harness?On.has(n.harness)?n.harness:"other":"none",ci:x(process.env.CI),...r.length>0?{author_context_hash:T(t,r)}:{},...n.harness?{agent_harness_hash:T(t,n.harness)}:{},...n.model?{agent_model_hash:T(t,n.model)}:{},...n.model_source?{agent_model_source:n.model_source}:{}}}function G(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=Xe)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,We).map(r=>G(r,t+1));if(typeof e=="object"){const r=e,n={},o=Object.keys(r).sort((s,i)=>s.localeCompare(i));for(const s of o)n[s]=G(r[s],t+1);return n}return String(e)}function K(e,t){return T(e,JSON.stringify(G(t)))}function mt(e,t){return{hashes:t.map(r=>T(e,r)),digest:T(e,t.join("\0"))}}function Ae(e,t,r,n){const o=E(typeof n=="string"?n:"","redacted"),s=typeof r=="string"&&r.length>0?r:"unknown_error",i=`${t}\0${s}\0${o}`;return T(e,i)}function ft(){if(xn.has((process.env[Mn]??"").trim().toLowerCase()))return null;const e=(process.env[Tn]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}const t=(process.env[wn]??"").trim();if(t.length===0)return null;try{const r=new URL(t),n=r.pathname.replace(/\/+$/,"");return n.endsWith("/v1/traces")||(r.pathname=`${n.length===0?"":n}/v1/traces`),r.toString()}catch{return null}}function pt(e){const t=Date.parse(e),r=Number.isNaN(t)?Date.now():t;return`${BigInt(r)*1000000n}`}function w(e,t){return{key:e,value:{stringValue:t}}}function bn(e,t){return{key:e,value:{boolValue:t}}}function ht(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function Et(e,t,r,n,o=1){const s=e.otel_traces_endpoint;if(typeof s!="string"||s.trim().length===0||[e.otel_trace_id,e.otel_span_id].some(d=>typeof d!="string"||d.length===0))return null;const i=E((process.env[Sn]??"").trim()),a=i.length>0?i:"pm-cli",c=X(t.exit_code,t.ok),u=J(t.error_code),_=Me({ok:t.ok,errorCode:u,errorCategory:t.error_category}),m=[w("pm.command",E(e.command)),w("pm.version",e.pm_version),w("pm.source_context",e.source_context),w("pm.source_context_source",e.source_context_source),w("pm.installation_id",e.installation_id),w("pm.session_id",B),w("pm.pm_root_hash",e.pm_root_hash),w("pm.cwd_hash",e.cwd_hash),bn("pm.ok",t.ok),ht("pm.exit_code",c),ht("pm.duration_ms",n),w("pm.sample_rate",String(o))];typeof u=="string"&&m.push(w("pm.error_code",u)),typeof _=="string"&&m.push(w("pm.error_category",_)),typeof t.error=="string"&&t.error.trim().length>0&&m.push(w("pm.error",E(t.error)));const f={resourceSpans:[{resource:{attributes:[w("service.name",a)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:e.otel_trace_id,spanId:e.otel_span_id,name:`pm.command.${E(e.command)}`,kind:1,startTimeUnixNano:pt(e.started_at),endTimeUnixNano:pt(r),attributes:m,status:{code:t.ok?1:2,message:t.ok?"":E(typeof t.error=="string"?t.error:"command_failed")}}]}]}]};return{endpoint:s,payload:f}}function yt(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:E(e,t)};if(typeof e=="number"||typeof e=="boolean")return{type:typeof e,value:e};if(Array.isArray(e))return{type:"array",length:e.length,sample:e.slice(0,5).map(r=>N(r,void 0,t))};if(typeof e=="object"){const r=e,n=Object.keys(r).filter(i=>i!=="tests").sort((i,a)=>i.localeCompare(a)),o={};let s=0;for(const i of n.slice(0,25)){const a=N(r[i],i,t);if(a===void 0)continue;const c=JSON.stringify(a).length;if(s+c>hn){o[i]="[preview_truncated]";break}s+=c,o[i]=a}return{type:"object",key_count:n.length,keys_preview:n.slice(0,50),preview:o}}return{type:typeof e,value:String(e)}}function gt(e){const{captureLevel:t,context:r,pmVersion:n,sourceContext:o,pmRootHash:s,cwdHash:i,installationId:a}=e,c=le(r.command),u=mt(a,r.args),_=T(a,`${r.command}\0${r.args.join("\0")}`),m=K(a,r.options),f=K(a,r.global),d=W(t,a);return t==="minimal"?{capture_level:t,pm_version:n,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,command_args_digest:u.digest,command_invocation_digest:_,command_options_digest:m,global_options_digest:f,...d}:{pm_version:n,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,...d,command_args:ge(r.args,t),command_args_hashes:u.hashes,command_args_digest:u.digest,command_invocation_digest:_,command_options:N(r.options,void 0,t),command_options_digest:m,global_options:N(r.global,void 0,t),global_options_digest:f,pm_root_hash:s,cwd_hash:i,capture_level:t,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:T(a,ce.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function Tt(e){const{captureLevel:t,pmVersion:r,sourceContext:n,outcome:o,durationMs:s,startedAt:i,command:a,installationId:c,commandTaxonomy:u,exitCode:_,errorCode:m,errorCategory:f,commandResolution:d,resolutionStage:p}=e,h=o.ok===!1?Ae(c,a,m,o.error):void 0,l=W(t,c);return t==="minimal"?{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:u,command_resolution:d,resolution_stage:p,ok:o.ok,exit_code:_,error_code:m,error_category:f,error:o.error?E(o.error,"redacted"):void 0,error_fingerprint:h,duration_ms:s,...l}:{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:u,command_resolution:d,resolution_stage:p,...l,ok:o.ok,exit_code:_,error_code:m,error_category:f,error:o.error?E(o.error,t):void 0,error_fingerprint:h,duration_ms:s,started_at:i,result_summary:yt(o.result,t)}}function wt(e){const{captureLevel:t,pmVersion:r,sourceContext:n,command:o,commandTaxonomy:s,commandResolution:i,resolutionStage:a,args:c,options:u,pmRootHash:_,cwdHash:m,installationId:f,errorCode:d,errorMessage:p,errorCategory:h,exitCode:l}=e,g=mt(f,c),A=T(f,o),O=K(f,u),Ue=Ae(f,o,d,p),ze=W(t,f);return t==="minimal"?{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:s,command_resolution:i,resolution_stage:a,attempted_command_digest:A,attempted_args_digest:g.digest,attempted_options_digest:O,error_code:d,error_category:h,exit_code:l,error:E(p,"redacted"),error_fingerprint:Ue,...ze}:{capture_level:t,pm_version:r,source_context:n.source_context,source_context_source:n.source_context_source,command_taxonomy:s,command_resolution:i,resolution_stage:a,...ze,attempted_command:E(o,t),attempted_command_digest:A,attempted_args:ge(c,t),attempted_args_hashes:g.hashes,attempted_args_digest:g.digest,attempted_options:N(u,void 0,t),attempted_options_digest:O,error_code:d,error_category:h,exit_code:l,error:E(p,t),error_fingerprint:Ue,pm_root_hash:_,cwd_hash:m,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:T(f,ce.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function Le(e){const t=await P(e);if(!t.telemetry.enabled||C().telemetry_disabled)return null;if(t.telemetry.installation_id.trim().length===0){if(Ve(e)||tn(t))return null;t.telemetry.installation_id=M.randomUUID(),await rn(e,t,"telemetry:install_id")}return{installationId:t.telemetry.installation_id,endpoint:t.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(t.telemetry.retention_days)),captureLevel:_t(t.telemetry.capture_level)}}async function z(e,t){let n=JSON.stringify({client_schema_version:Qe,event:t,attempts:0});if(n.length>V){const o={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:n.length}}};n=JSON.stringify({client_schema_version:Qe,event:o,attempts:0})}await je(k(e),n)}async function Fn(e,t){await S(()=>z(e,t),e)}function Ie(e){const t=[];for(const r of e.split(`
4
+ `)){const n=r.trim();if(n.length!==0)try{const o=JSON.parse(n);o&&typeof o=="object"&&o.event&&typeof o.event=="object"&&typeof o.attempts=="number"&&(o.client_schema_version===void 0||typeof o.client_schema_version=="number"&&Number.isFinite(o.client_schema_version))&&t.push(o)}catch{}}return t}function St(e){const t=Math.min(_n*2**Math.max(e-1,0),ln);return new Date(Date.now()+t).toISOString()}function Z(e){if(typeof e!="string"||e.trim().length===0)return!0;const t=Date.parse(e);return Number.isNaN(t)?!0:t<=Date.now()}function Ne(e){return Z(e.next_attempt_after)}function Oe(e){const t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*pn}function Mt(e,t){const r=e.event?.occurred_at;if(typeof r!="string"||r.trim().length===0)return!1;const n=Date.parse(r);return Number.isNaN(n)?!1:n<t}function Y(e,t){const r=Oe(t),n=[];let o=0;for(const s of e){if(JSON.stringify(s).length>V||Mt(s,r)||s.attempts>=Ge){o+=1;continue}n.push(s)}return{entries:n,prunedCount:o}}async function Ce(e,t,r=L().endpoint){const n=t.map(s=>JSON.stringify(s)).join(`
5
+ `),o=n.length>0?`${n}
6
+ `:"";for(let s=0;;s+=1)try{await de(k(e,r),o,{createParentDirectories:!x(process.env[I])});return}catch(i){const a=Ke[s];if(a===void 0||!Re(i))throw i;await ve(a)}}function Re(e){if(typeof e!="object"||e===null||!("code"in e))return!1;const t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function ve(e){return new Promise(t=>{setTimeout(t,e)})}async function xt(e,t){const r={id:M.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:v(),attempts:0},n=JSON.stringify(r);n.length>V||await je(D(e),n)}async function jn(e,t){await S(()=>xt(e,t),e)}function Hn(e){const t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return M.createHash("sha256").update(t).digest("hex").slice(0,32)}function ee(e){const t=[];for(const r of e.split(`
7
+ `)){const n=r.trim();if(n.length!==0)try{const o=JSON.parse(n);o&&typeof o=="object"&&typeof o.endpoint=="string"&&o.endpoint.trim().length>0&&"payload"in o&&typeof o.attempts=="number"&&Number.isFinite(o.attempts)&&((typeof o.id!="string"||o.id.length===0)&&(o.id=Hn(o)),t.push(o))}catch{}}return t}function At(e,t){if(typeof e.enqueued_at!="string"||e.enqueued_at.trim().length===0)return!1;const r=Date.parse(e.enqueued_at);return Number.isNaN(r)?!1:r<t}function te(e,t){const r=Oe(t),n=[];let o=0;for(const s of e){if(JSON.stringify(s).length>V||At(s,r)||s.attempts>=Ge){o+=1;continue}n.push(s)}if(n.length>Be){const s=n.length-Be;return o+=s,{entries:n.slice(s),prunedCount:o}}return{entries:n,prunedCount:o}}async function Lt(e,t){const r=t.map(o=>JSON.stringify(o)).join(`
8
+ `),n=r.length>0?`${r}
9
+ `:"";for(let o=0;;o+=1)try{await de(D(e),n,{createParentDirectories:!x(process.env[I])});return}catch(s){const i=Ke[o];if(i===void 0||!Re(s))throw s;await ve(i)}}async function ke(e,t,r,n){return S(async()=>{const o=await R(D(e)),s=o===null?[]:ee(o),i=[];for(const c of s){if(r.has(c.id))continue;const u=n.get(c.id);i.push(u?{...c,attempts:u.attempts,next_attempt_after:u.next_attempt_after}:c)}const{entries:a}=te(i,t);return await Lt(e,a),a.length},e)}async function It(e,t){const r=await R(D(e));if(r===null||r.trim().length===0){await U(e,{pending_otel_spans:0},null);return}const n=ee(r),{entries:o,prunedCount:s}=te(n,t),i=o.filter(p=>Z(p.next_attempt_after)).slice(0,un);if(i.length===0){const p=s>0?await ke(e,t,new Set,new Map):o.length;await U(e,{pending_otel_spans:p},null);return}const a=v(),c=new Set,u=new Map;let _=0,m;await Promise.all(i.map(async p=>{try{const h=await we(p.endpoint,{"content-type":"application/json"},JSON.stringify(p.payload));if(h<200||h>=300)throw new Error(`local_otel_export_http_${h}`);c.add(p.id),_+=1}catch(h){m=h instanceof Error?E(ue(h.message),"redacted"):"local_otel_export_failed";const l=p.attempts+1;u.set(p.id,{attempts:l,next_attempt_after:St(l)})}}));const f=await ke(e,t,c,u),d={pending_otel_spans:f,last_otel_attempt_at:a};_>0&&(d.last_otel_success_at=a),m!==void 0?(d.last_otel_failure_at=a,d.last_otel_failure_error=m):f===0&&(d.last_otel_failure_at=void 0,d.last_otel_failure_error=void 0),await U(e,d,null)}async function De(e,t,r){try{await Ot(e,t,r)}catch{}try{await It(e,r)}catch{}}async function Nt(e,t=En,r=L().endpoint){try{const n=zn(e),o=await bt(n,{withFileTypes:!0}),s=Date.now(),i=new Set([F("events.jsonl",r),F("state.json",r)]),a=c=>{if(!i.has(c))return/^\.events(?:\.[a-f0-9]{16})?\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(c)?s-Math.max(0,t):/^(?:events\.[a-f0-9]{16}\.jsonl|state\.[a-f0-9]{16}\.json)$/.test(c)?s-yn:void 0};await Promise.all(o.map(async c=>{const u=c.isFile()?a(c.name):void 0;if(u===void 0)return;const _=y.join(n,c.name);(await be(_)).mtimeMs<u&&await ae(_,{force:!0})}))}catch{}}async function S(e,t=j(process.cwd()),r=5e3){const n=me.catch(()=>{}).then(()=>qt(async()=>{const o=await Ht(t,"telemetry-queue",60,"telemetry",!1,!1,r,{createParentDirectories:!x(process.env[I])});try{return on(t),await e()}finally{await o()}}));return me=n.catch(()=>{}),n}async function b(e,t=L().endpoint){const r=await R(k(e,t));return r===null||r.trim().length===0?[]:Ie(r)}async function ne(e,t,r,n=L().endpoint){return S(async()=>{const o=await b(e,n),{entries:s}=Y(o,r),i=s.filter(a=>!t.has(a.event.event_id));return await Ce(e,i,n),i},e)}async function Vn(e,t,r,n,o=L().endpoint){return S(async()=>{const s=await b(e,o),{entries:i}=Y(s,n),a=i.map(c=>{if(!t.has(c.event.event_id))return c;const u=c.attempts+1;return{...c,attempts:u,last_attempt_at:r,next_attempt_after:St(u)}});return await Ce(e,a,o),a},e)}function qn(e,t){return t===null?e:Jt(e)}async function Ot(e,t,r){const n=L().endpoint;await Nt(e,void 0,n);const o=(n??t).trim(),s=qn(o,n),i=l=>U(e,l,n);if(o.length===0)return;const a=await R(k(e,n));if(a===null||a.trim().length===0){await i({endpoint:s,queue_entries:0});return}const c=Ie(a);if(c.length===0){await i({endpoint:s,queue_entries:0});return}const{entries:u,prunedCount:_}=Y(c,r);if(u.length===0){const l=await ne(e,new Set,r,n);await i({endpoint:s,queue_entries:l.length});return}const m=u.filter(l=>Ne(l)).slice(0,dn);if(m.length===0){const l=_>0?await ne(e,new Set,r,n):u;await i({endpoint:s,queue_entries:l.length});return}const f=new Set(m.map(l=>l.event.event_id)),d=v(),p={"content-type":"application/json"},h=process.env.PM_TELEMETRY_INGEST_KEY?.trim();h&&(p["x-pm-telemetry-key"]=h);try{const l=await we(o,p,JSON.stringify({schema_version:H,events:m.map(g=>g.event)}));if(l<200||l>=300)throw new Error(`telemetry_flush_http_${l}`)}catch(l){const g=await Vn(e,f,d,r,n),A=l instanceof Error?E(ue(l.message),"redacted"):"telemetry_flush_failed";await i({endpoint:s,queue_entries:g.length,last_attempted_flush_at:d,last_failed_flush_at:d,last_failed_flush_error:A});return}try{const l=await ne(e,f,r,n);await i({endpoint:s,queue_entries:l.length,last_attempted_flush_at:d,last_successful_flush_at:d,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(l){const g=l instanceof Error?E(ue(l.message),"redacted"):"telemetry_flush_failed",A=await b(e,n).catch(()=>u);await i({endpoint:s,queue_entries:A.length,last_attempted_flush_at:d,last_failed_flush_at:d,last_failed_flush_error:g})}}async function Ct(e){const t=Q(e);x(process.env[I])||await ie(y.dirname(t),{recursive:!0});try{return await ie(t),!0}catch(r){if(typeof r!="object"||r===null||!("code"in r)||r.code!=="EEXIST")throw r}try{const r=await be(t);return Date.now()-r.mtimeMs<Ze?!1:(await ae(t,{recursive:!0,force:!0}),await ie(t),!0)}catch{return!1}}function Rt(e,t){try{return Date.now()-Ye(e).mtimeMs<t}catch{return!1}}function Pe(e){try{Yt(e,{recursive:!0,force:!0})}catch{}}function vt(e){if(typeof e!="object"||e===null||!("code"in e))return;const t=e.code;return typeof t=="string"?t:void 0}function kt(e){try{return se(e),!0}catch(t){if(vt(t)==="EEXIST"||!Fe(t))return!1}try{return se(y.dirname(e),{recursive:!0}),se(e),!0}catch{return!1}}function Dt(e){if(Rt(Q(e),Ze))return!1;const t=pe(e);try{if(Date.now()-Ye(t).mtimeMs<gn)return!1;Pe(t)}catch(r){if(!Fe(r))return!1}return kt(t)}function re(e){Pe(pe(e))}const fr={queuePath:k,cleanupTelemetryQueueTempOrphans:Nt,acquireTelemetryFlushSpawnGate:Dt,acquireTelemetryFlushLock:Ct,buildAuthorContextPayloadFields:W,buildCommandErrorPayload:wt,buildCommandFinishPayload:Tt,buildCommandStartPayload:gt,buildOtelSpanRequest:Et,createDirectoryLock:kt,enqueuePendingOtelSpan:jn,enqueueTelemetryEvent:Fn,errorCode:vt,flushPendingOtelSpans:It,flushQueue:Ot,flushQueueWithProcessLock:Pt,flushTelemetryArtifacts:De,hashTelemetryErrorFingerprint:Ae,hashTelemetryValue:K,isEmailDomainCharacter:ye,isEmailLocalCharacter:Ee,isExpiredPendingOtelSpan:At,isExpiredQueueEntry:Mt,isFreshDirectoryLock:Rt,isDueForRetry:Ne,isDueForRetryAt:Z,isRetryableQueueRewriteError:Re,looksLikeEmailToken:ct,otelSpansQueuePath:D,parseBooleanTrueLike:x,postTelemetryJson:we,parsePendingOtelSpanLines:ee,prunePendingOtelSpans:te,reconcilePendingOtelSpansAfterFlush:ke,retentionCutoffMs:Oe,resolveOtelTracesEndpoint:ft,resolveTelemetryHttpTimeoutMs:Te,rewritePendingOtelSpans:Lt,normalizeForHash:G,normalizeCaptureLevel:_t,normalizePmVersion:Se,normalizeTelemetryErrorCategory:Me,normalizeTelemetryErrorCode:J,normalizeTelemetryExitCode:X,parseQueueLines:Ie,pruneExpiredQueueEntries:Y,readRuntimeState:ot,readCurrentQueueEntries:b,releaseTelemetryFlushSpawnGate:re,removeFlushedEntriesFromCurrentQueue:ne,removeDirectoryLockBestEffort:Pe,resolveTelemetrySourceContext:xe,rewriteQueue:Ce,sanitizeCommandArgs:ge,sanitizeStringMax:lt,sanitizeStringRedacted:dt,sanitizeValue:N,scheduleTelemetryFlush:oe,shouldFlushInline:rt,sleep:ve,summarizeResult:yt,telemetryFlushRunnerPath:nt,withQueueMutation:S,flushLockPath:Q,flushSpawnLockPath:pe,runtimeStatePath:fe,writeRuntimeState:U};async function Pt(e,t,r){const n=await Ct(e);if(re(e),!n)return!1;try{await De(e,t,r)}finally{try{await ae(Q(e),{recursive:!0,force:!0})}catch{}}return!0}async function Ut(e,t){const r=new Set;try{const{entries:n}=Y(await b(e),t);for(const o of n.filter(Ne))r.add(`event:${o.event.event_id}`)}catch{}try{const n=await R(D(e));if(n!==null)for(const o of te(ee(n),t).entries)Z(o.next_attempt_after)&&r.add(`span:${o.id}`)}catch{}return r}function oe(e,t,r){if(!Ve(e)){if(rt())return q=q.then(()=>De(e,t,r)),q;try{if(!Dt(e))return;const o=zt(process.execPath,[nt()],{detached:!0,stdio:"ignore",cwd:ce.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[I]:"1"}});o.on("error",()=>{re(e)}),o.unref()}catch{re(e)}}}async function pr(e=j(process.cwd())){if(!C().telemetry_disabled)try{await nn(e,async()=>{const t=x(process.env[I]);let r=!0;for(;r;){if(!(await P(e)).telemetry.enabled)return;const o=await S(()=>Le(e),e);if(!o)return;const s=t?await Ut(e,o.retentionDays):new Set;if(!await Pt(e,o.endpoint,o.retentionDays)||!t)return;const a=await Ut(e,o.retentionDays);r=a.size>0&&(a.size!==s.size||[...a].some(c=>!s.has(c)))}},()=>x(process.env[I]))}catch{}}async function hr(e){if(C().telemetry_disabled||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{const t=j(process.cwd());if(!(await P(t)).telemetry.enabled)return null;const n=e.global.noExtensions===!0||Vt(e.command),o=await S(async()=>{const s=await Le(t);if(!s)return null;const{installationId:i,endpoint:a,retentionDays:c,captureLevel:u}=s,_=Se(e.pm_version),m=xe(e.global),f=T(i,e.pm_root),d=T(i,process.cwd()),p=ft(),h=v(),l={schema_version:H,event_id:M.randomUUID(),event_type:"command_start",occurred_at:h,installation_id:i,session_id:B,command:e.command,payload:gt({captureLevel:u,context:e,pmVersion:_,sourceContext:m,pmRootHash:f,cwdHash:d,installationId:i})},g=await $t(t,e.command,n);g===1&&await z(t,l);const A=le(e.command),O={...g<1?{sample_rate:g}:{},started_at:h,started_at_ms:Date.now(),command:e.command,command_taxonomy:A,pm_version:_,source_context:m.source_context,source_context_source:m.source_context_source,installation_id:i,pm_root_hash:f,cwd_hash:d,endpoint:a,retention_days:c,global_pm_root:t,capture_level:u,otel_traces_endpoint:p??void 0,otel_trace_id:p?M.randomBytes(16).toString("hex"):void 0,otel_span_id:p?M.randomBytes(8).toString("hex"):void 0};return g<1&&$.set(O,l),O},t,_e);return o&&o.sample_rate===void 0&&oe(t,o.endpoint,o.retention_days),o}catch{return null}}async function Er(e,t){if(!(!e||C().telemetry_disabled))try{if(!await S(async()=>{const n=await P(e.global_pm_root);if(C().telemetry_disabled||!n.telemetry.enabled||n.telemetry.installation_id!==e.installation_id)return $.delete(e),!1;const o=$.get(e),s=t.ok?e.sample_rate??1:1;if(o){if($.delete(e),M.randomBytes(6).readUIntBE(0,6)/281474976710656>=s)return!1;o.payload.sample_rate=s,await z(e.global_pm_root,o)}const i=v(),a=Math.max(0,Date.now()-e.started_at_ms),c=J($e({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),u=Me({ok:t.ok,errorCode:c,errorCategory:t.error_category}),_=X(t.exit_code,t.ok),m=t.command_resolution??qe({ok:t.ok,errorCode:c,errorCategory:u}),f=t.resolution_stage??"execute",d={schema_version:H,event_id:M.randomUUID(),event_type:"command_finish",occurred_at:i,installation_id:e.installation_id,session_id:B,command:e.command,payload:{...o?{sample_rate:s}:{},...Tt({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:a,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:_,errorCode:c,errorCategory:u,commandResolution:m,resolutionStage:f})}};await z(e.global_pm_root,d);const p=Et(e,{...t,exit_code:_,error_code:c,error_category:u},i,a,s);return p&&await xt(e.global_pm_root,p),!0},e.global_pm_root,_e))return;await oe(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function yr(e){if(!C().telemetry_disabled)try{const t=j(process.cwd());if(!(await P(t)).telemetry.enabled)return;const n=await S(async()=>{const o=await Le(t);if(!o)return null;const{installationId:s,captureLevel:i}=o,a=Se(e.pm_version),c=xe(e.global),u=T(s,e.pm_root),_=T(s,process.cwd()),m=v(),f=J($e({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),d=e.error_category??He(f),p=X(e.exit_code,!1),h=e.command.trim().length>0?e.command:"<unknown>",l=le(h),g=e.command_resolution??qe({ok:!1,errorCode:f,errorCategory:d}),A=e.resolution_stage??"unknown",O={schema_version:H,event_id:M.randomUUID(),event_type:"command_error",occurred_at:m,installation_id:s,session_id:B,command:E(h,"redacted"),payload:wt({captureLevel:i,pmVersion:a,sourceContext:c,command:h,commandTaxonomy:l,commandResolution:g,resolutionStage:A,args:e.args,options:e.options,pmRootHash:u,cwdHash:_,installationId:s,errorCode:f,errorCategory:d,exitCode:p,errorMessage:e.error_message})};return await z(t,O),o},t,_e);n&&await oe(t,n.endpoint,n.retentionDays)}catch{}}export{wr as PM_TELEMETRY_SOURCE_CONTEXT_VALUES,Ge as TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,H as TELEMETRY_SCHEMA_VERSION,fr as _testOnly,yr as emitTelemetryErrorEvent,Er as finishTelemetryCommand,pr as flushTelemetryQueueNow,hr as startTelemetryCommand,mr as waitForPendingFlush,S as withTelemetryQueueMutation};
10
10
  //# sourceMappingURL=runtime.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]="7a7096c6-a9c3-5d8e-96e4-ed1b0218234e")}catch{}})();import fs from"node:fs/promises";import{spawn}from"node:child_process";import{createHash,randomBytes}from"node:crypto";import path from"node:path";import{ensureDir,pathExists,readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{PmCliError}from"../shared/errors.js";import{EXIT_CODE}from"../shared/constants.js";import{nowIso}from"../shared/time.js";import{getTestRunRecordPath,getTestRunResultPath,getTestRunStderrPath,getTestRunStdoutPath,getTestRunsPath,getTestRunsRecordsPath,getTestRunsResultsPath,getTestRunsStderrPath,getTestRunsStdoutPath}from"../store/paths.js";const BACKGROUND_RUN_ACTIVE_STATUSES=new Set(["queued","running"]),BACKGROUND_RUN_TERMINAL_STATUSES=new Set(["passed","failed","stopped","canceled"]),DEFAULT_BACKGROUND_RUN_RESOURCE_SNAPSHOT_INTERVAL_MS=3e3,DEFAULT_BACKGROUND_RUN_FORCE_KILL_DELAY_MS=3e3,DEFAULT_BACKGROUND_RUN_HEARTBEAT_STALE_MS=3e4,DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES=100,PROC_STAT_TICKS_PER_SECOND=100;function nowMs(){return Date.now()}function normalizeCommandArgs(args){return args.map(entry=>entry.trim()).filter(entry=>entry.length>0)}function summarizeCommandLabel(args){const joined=args.join(" ").replaceAll(/\s+/g," ").trim();return joined.length<=180?joined:`${joined.slice(0,177)}...`}function buildRunId(){const timePart=Date.now().toString(36),randomPart=randomBytes(3).toString("hex");return`tr-${timePart}-${randomPart}`}function buildBackgroundTestRunFingerprint(kind,commandArgs,pmRoot){const payload={kind,command:normalizeCommandArgs(commandArgs),pm_root:path.resolve(pmRoot)};return createHash("sha256").update(JSON.stringify(payload)).digest("hex")}function isPidRunning(pid){if(!Number.isInteger(pid)||!pid||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(error){return(typeof error=="object"&&error!==null&&"code"in error?error.code:void 0)==="EPERM"}}async function ensureBackgroundRunStorage(pmRoot){await ensureDir(getTestRunsPath(pmRoot)),await ensureDir(getTestRunsRecordsPath(pmRoot)),await ensureDir(getTestRunsStdoutPath(pmRoot)),await ensureDir(getTestRunsStderrPath(pmRoot)),await ensureDir(getTestRunsResultsPath(pmRoot))}async function parseBackgroundRunRecord(raw,recordPath){try{const parsed=JSON.parse(raw);if(!parsed||typeof parsed!="object"||typeof parsed.id!="string")throw new Error("invalid run record payload");return parsed}catch(error){throw new PmCliError(`Failed to parse background test run record at ${recordPath}: ${error instanceof Error?error.message:String(error)}`,EXIT_CODE.GENERIC_FAILURE)}}async function writeBackgroundRunRecord(pmRoot,record){const next={...record,updated_at:nowIso()};await writeFileAtomic(getTestRunRecordPath(pmRoot,record.id),`${JSON.stringify(next,null,2)}
2
- `)}async function readBackgroundTestRunRecord(pmRoot,runId){const recordPath=getTestRunRecordPath(pmRoot,runId),raw=await readFileIfExists(recordPath);return raw?parseBackgroundRunRecord(raw,recordPath):null}async function listBackgroundRunRecordPaths(pmRoot){const recordsRoot=getTestRunsRecordsPath(pmRoot);return await pathExists(recordsRoot)?(await fs.readdir(recordsRoot,{withFileTypes:!0})).filter(entry=>entry.isFile()&&entry.name.endsWith(".json")).map(entry=>path.join(recordsRoot,entry.name)).sort((left,right)=>right.localeCompare(left)):[]}function parseLinuxRssStatus(raw){const match=raw.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(match)return Number.parseInt(match[1],10)*1024}async function readLinuxRssBytes(pid){if(process.platform==="linux")try{const raw=await fs.readFile(`/proc/${pid}/status`,"utf8");return parseLinuxRssStatus(raw)}catch{return}}function parseLinuxCpuStat(raw){const closeParenIndex=raw.lastIndexOf(")");if(closeParenIndex<0)return{};const parts=raw.slice(closeParenIndex+2).trim().split(/\s+/),utimeTicks=Number.parseInt(parts[11],10),stimeTicks=Number.parseInt(parts[12],10);return!Number.isFinite(utimeTicks)||!Number.isFinite(stimeTicks)?{}:{cpu_user_seconds:utimeTicks/PROC_STAT_TICKS_PER_SECOND,cpu_system_seconds:stimeTicks/PROC_STAT_TICKS_PER_SECOND}}async function readLinuxCpuSeconds(pid){if(process.platform!=="linux")return{};try{const raw=await fs.readFile(`/proc/${pid}/stat`,"utf8");return parseLinuxCpuStat(raw)}catch{return{}}}async function buildResourceSnapshot(record){const pid=record.child_pid??record.worker_pid;if(!isPidRunning(pid))return;const rssBytes=await readLinuxRssBytes(pid),cpu=await readLinuxCpuSeconds(pid),startedAtMs=record.started_at?Date.parse(record.started_at):Number.NaN,uptimeSeconds=Number.isFinite(startedAtMs)?Math.max(0,(nowMs()-startedAtMs)/1e3):void 0;return{recorded_at:nowIso(),rss_bytes:rssBytes,cpu_user_seconds:cpu.cpu_user_seconds,cpu_system_seconds:cpu.cpu_system_seconds,uptime_seconds:uptimeSeconds}}function readCount(value){return typeof value=="number"&&Number.isFinite(value)?value:0}function evaluateWorkerResult(kind,payload){if(!payload||typeof payload!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};const record=payload;if(kind==="test-all"){const totals=record.totals??{};return{summary:{items:typeof totals.items=="number"?totals.items:void 0,linked_tests:typeof totals.linked_tests=="number"?totals.linked_tests:void 0,passed:readCount(totals.passed),failed:readCount(totals.failed),skipped:readCount(totals.skipped),fail_on_skipped_triggered:record.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:payload}}const runResults=Array.isArray(record.run_results)?record.run_results:[];let passed=0,failed=0,skipped=0;for(const entry of runResults){if(!entry||typeof entry!="object")continue;const status=entry.status;if(status==="passed"){passed+=1;continue}if(status==="failed"||status==="refused"){failed+=1;continue}skipped+=1}return{summary:{passed,failed,skipped,fail_on_skipped_triggered:record.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:payload}}function parseProgressLine(stderrLine){const line=stderrLine.trim();if(line.length===0)return null;const testAllMatch=line.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(testAllMatch){const itemIndex=Number.parseInt(testAllMatch[1],10),itemTotal=Number.parseInt(testAllMatch[2],10);return{item_index:itemIndex,item_total:itemTotal,item_id:testAllMatch[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:nowIso(),phase:testAllMatch[3]?.toLowerCase()==="end"?"finished":"running"}}const linkedTestMatch=line.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!linkedTestMatch)return null;const index=Number.parseInt(linkedTestMatch[1],10),total=Number.parseInt(linkedTestMatch[2],10),elapsed=linkedTestMatch[4]?Number.parseInt(linkedTestMatch[4],10):void 0,commandMatch=line.match(/\scommand="((?:\\.|[^"\\])*)"/),currentCommand=commandMatch?commandMatch[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:index,linked_test_total:total,current_command:currentCommand,elapsed_ms:Number.isFinite(elapsed)?elapsed:void 0,heartbeat_at:nowIso(),phase:linkedTestMatch[3]?.toLowerCase()==="end"?"finished":"running"}}function splitLines(value){return value.split(/\r?\n/).map(entry=>entry.trimEnd()).filter(entry=>entry.length>0)}function tailLines(value,limit){if(limit<=0)return[];const lines=splitLines(value);return lines.length<=limit?lines:lines.slice(lines.length-limit)}async function resolveBackgroundCliEntry(cwd){const configured=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(configured&&configured.length>0){const resolvedConfigured=path.resolve(cwd,configured);if(await pathExists(resolvedConfigured))return resolvedConfigured}const distEntry=path.resolve(cwd,"dist","cli.js");if(await pathExists(distEntry))return distEntry;const argvEntry=process.argv[1]?.trim();if(argvEntry&&argvEntry.length>0){const resolvedArgvEntry=path.resolve(cwd,argvEntry);if(await pathExists(resolvedArgvEntry))return resolvedArgvEntry}throw new PmCliError("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",EXIT_CODE.GENERIC_FAILURE)}async function refreshRunIfStale(pmRoot,record){if(!BACKGROUND_RUN_ACTIVE_STATUSES.has(record.status)||isPidRunning(record.worker_pid)||record.finished_at)return record;const next={...record,status:"failed",finished_at:nowIso(),error:record.error??"Background test run worker exited before writing terminal status."};return await writeBackgroundRunRecord(pmRoot,next),next}async function startBackgroundTestRun(options){await ensureBackgroundRunStorage(options.pmRoot);const normalizedArgs=normalizeCommandArgs(options.commandArgs);if(normalizedArgs.length===0)throw new PmCliError("Background test run requires command arguments.",EXIT_CODE.USAGE);const fingerprint=buildBackgroundTestRunFingerprint(options.kind,normalizedArgs,options.pmRoot),existingRuns=await listBackgroundTestRuns(options.pmRoot,{});for(const existing of existingRuns){const refreshed=await refreshRunIfStale(options.pmRoot,existing);if(refreshed.fingerprint===fingerprint&&!(!BACKGROUND_RUN_ACTIVE_STATUSES.has(refreshed.status)||!isPidRunning(refreshed.worker_pid)))return{started:!1,run:{...refreshed,duplicate_of:refreshed.id},duplicate_of:refreshed.id}}const runId=buildRunId(),createdAt=nowIso(),stdoutPath=getTestRunStdoutPath(options.pmRoot,runId),stderrPath=getTestRunStderrPath(options.pmRoot,runId),resultPath=getTestRunResultPath(options.pmRoot,runId);await fs.writeFile(stdoutPath,"","utf8"),await fs.writeFile(stderrPath,"","utf8");const record={id:runId,kind:options.kind,status:"queued",created_at:createdAt,updated_at:createdAt,requested_by:options.requestedBy,fingerprint,command_args:normalizedArgs,command_label:summarizeCommandLabel(normalizedArgs),pm_root:options.pmRoot,global_pm_root:options.globalPmRoot,target_id:options.targetId,status_filter:options.statusFilter,attempt:typeof options.attempt=="number"&&Number.isFinite(options.attempt)&&options.attempt>=1?Math.floor(options.attempt):1,resumed_from:options.resumedFrom,resumed_by:options.resumedBy,stdout_path:stdoutPath,stderr_path:stderrPath,result_path:resultPath,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:createdAt}};return await writeBackgroundRunRecord(options.pmRoot,record),{started:!0,run:record}}async function spawnBackgroundTestRunWorker(options){const record=await readBackgroundTestRunRecord(options.pmRoot,options.runId);if(!record)throw new PmCliError(`Background test run ${options.runId} not found`,EXIT_CODE.NOT_FOUND);if(BACKGROUND_RUN_TERMINAL_STATUSES.has(record.status))throw new PmCliError(`Background test run ${record.id} is already terminal (${record.status}).`,EXIT_CODE.CONFLICT);const cliEntry=await resolveBackgroundCliEntry(process.cwd()),args=[];options.noExtensions===!0&&args.push("--no-extensions"),args.push("--path",record.pm_root,"test-runs-worker",record.id);const env={...process.env,PM_PATH:record.pm_root,PM_GLOBAL_PATH:record.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:record.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(record.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:record.resumed_from??"",FORCE_COLOR:"0"},child=spawn(process.execPath,[cliEntry,...args],{cwd:process.cwd(),env,detached:!0,stdio:"ignore",windowsHide:!0});child.unref();const next={...record,status:"queued",worker_pid:child.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:nowIso()}};return await writeBackgroundRunRecord(options.pmRoot,next),next}async function appendFileOrdered(queue,filePath,text){await queue,await fs.appendFile(filePath,text,"utf8")}function resolvePositiveEnvInteger(name,fallback){const parsed=Number.parseInt(process.env[name]??"",10);return Number.isFinite(parsed)&&parsed>0?parsed:fallback}function buildBackgroundWorkerEnv(record){return{...process.env,PM_PATH:record.pm_root,PM_GLOBAL_PATH:record.global_pm_root,FORCE_COLOR:"0"}}function buildBackgroundWorkerChildArgs(record,noExtensions){return noExtensions?["--no-extensions",...record.command_args]:[...record.command_args]}function createBackgroundRunRecordWriteScheduler(pmRoot,record){let writeQueue=Promise.resolve();return{schedule(){writeQueue=writeQueue.then(async()=>{try{await writeBackgroundRunRecord(pmRoot,record)}catch{}})},async flush(){await writeQueue}}}function requestChildSignal(child,signal){try{child.kill(signal)}catch{}}async function requestBackgroundWorkerStop(record,child,state,scheduleRecordWrite){state.stopRequested||(state.stopRequested=!0,record.stop_requested_at=nowIso(),record.progress={...record.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:nowIso()},scheduleRecordWrite(),requestChildSignal(child,"SIGTERM"),setTimeout(()=>requestChildSignal(child,"SIGKILL"),resolvePositiveEnvInteger("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",DEFAULT_BACKGROUND_RUN_FORCE_KILL_DELAY_MS)).unref?.())}function buildItemBackgroundProgress(line,progressPatch,phase){return{phase,message:line,heartbeat_at:nowIso(),item_index:progressPatch.item_index,item_total:progressPatch.item_total,item_id:progressPatch.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function buildLinkedTestBackgroundProgress(line,record,progressPatch,phase){return{phase,message:line,heartbeat_at:nowIso(),item_index:progressPatch.item_index??record.progress?.item_index,item_total:progressPatch.item_total??record.progress?.item_total,item_id:progressPatch.item_id??record.progress?.item_id,linked_test_index:progressPatch.linked_test_index,linked_test_total:progressPatch.linked_test_total,current_command:progressPatch.current_command,elapsed_ms:progressPatch.elapsed_ms}}function applyBackgroundWorkerProgressLine(record,line,stopRequested){const progressPatch=parseProgressLine(line);if(!progressPatch)return!1;const phase=record.progress?.phase==="stopping"?"stopping":"running";return record.progress=progressPatch.item_id?buildItemBackgroundProgress(line,progressPatch,phase):buildLinkedTestBackgroundProgress(line,record,progressPatch,phase),progressPatch.phase==="finished"&&!stopRequested&&(record.progress.phase="running"),!0}function parseBackgroundWorkerStdout(stdoutBuffer){if(stdoutBuffer.trim().length===0)return null;try{return JSON.parse(stdoutBuffer)}catch{return null}}function resolveBackgroundWorkerFinalStatus(exitCode,summary,stopRequested){return stopRequested?"stopped":exitCode===0&&summary.failed===0&&summary.fail_on_skipped_triggered!==!0?"passed":"failed"}function buildFinishedBackgroundProgress(record,stopRequested){return{phase:"finished",message:stopRequested?"Background run stopped.":`Background run finished with status=${record.status}.`,heartbeat_at:nowIso(),item_index:record.progress?.item_index,item_total:record.progress?.item_total,item_id:record.progress?.item_id,linked_test_index:record.progress?.linked_test_index,linked_test_total:record.progress?.linked_test_total,current_command:record.progress?.current_command,elapsed_ms:record.progress?.elapsed_ms}}async function writeBackgroundWorkerResult(record,parsedResult,stdoutBuffer){if(parsedResult!==null){await writeFileAtomic(record.result_path,`${JSON.stringify(parsedResult,null,2)}
3
- `);return}await writeFileAtomic(record.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:tailLines(stdoutBuffer,DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES)},null,2)}
4
- `)}async function runBackgroundTestRunWorker(pmRoot,runId,noExtensions=!1){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const record={...loaded,status:"running",started_at:loaded.started_at??nowIso(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:nowIso()}},cliEntry=await resolveBackgroundCliEntry(process.cwd()),env=buildBackgroundWorkerEnv(record);await writeBackgroundRunRecord(pmRoot,record);const childArgs=buildBackgroundWorkerChildArgs(record,noExtensions),child=spawn(process.execPath,[cliEntry,...childArgs],{cwd:process.cwd(),env,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});record.child_pid=child.pid;const recordWriteScheduler=createBackgroundRunRecordWriteScheduler(pmRoot,record),scheduleRecordWrite=recordWriteScheduler.schedule;let stdoutWriteQueue=Promise.resolve(),stderrWriteQueue=Promise.resolve(),stdoutBuffer="",stderrBuffer="";const stopState={stopRequested:!1},onSignal=()=>{requestBackgroundWorkerStop(record,child,stopState,scheduleRecordWrite)};process.on("SIGTERM",onSignal),process.on("SIGINT",onSignal);const resourceTimer=setInterval(()=>{(async()=>(record.resource=await buildResourceSnapshot(record),record.progress.heartbeat_at=nowIso(),scheduleRecordWrite()))()},resolvePositiveEnvInteger("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",DEFAULT_BACKGROUND_RUN_RESOURCE_SNAPSHOT_INTERVAL_MS));resourceTimer.unref?.(),child.stdout?.on("data",chunk=>{const text=chunk.toString("utf8");stdoutBuffer+=text,stdoutWriteQueue=appendFileOrdered(stdoutWriteQueue,record.stdout_path,text)}),child.stderr?.on("data",chunk=>{const text=chunk.toString("utf8");stderrWriteQueue=appendFileOrdered(stderrWriteQueue,record.stderr_path,text),stderrBuffer+=text;const parts=stderrBuffer.split(/\r?\n/);stderrBuffer=parts.pop();let progressChanged=!1;for(const part of parts){const line=part.trimEnd();line.length>0&&applyBackgroundWorkerProgressLine(record,line,stopState.stopRequested)&&(progressChanged=!0)}progressChanged&&scheduleRecordWrite()});let exitCode=null,signal=null;try{({code:exitCode,signal}=await new Promise(resolve=>{child.on("close",(code,closeSignal)=>{resolve({code,signal:closeSignal})})}))}finally{clearInterval(resourceTimer),process.off("SIGTERM",onSignal),process.off("SIGINT",onSignal)}await stdoutWriteQueue,await stderrWriteQueue;const trailingStderrLine=stderrBuffer.trimEnd();trailingStderrLine.length>0&&applyBackgroundWorkerProgressLine(record,trailingStderrLine,stopState.stopRequested)&&scheduleRecordWrite(),stderrBuffer="";const parsedResult=parseBackgroundWorkerStdout(stdoutBuffer),evaluated=evaluateWorkerResult(record.kind,parsedResult);return record.summary=evaluated.summary,record.exit_code=typeof exitCode=="number"?exitCode:void 0,record.signal=signal??void 0,record.finished_at=nowIso(),record.status=resolveBackgroundWorkerFinalStatus(record.exit_code,evaluated.summary,stopState.stopRequested),record.progress=buildFinishedBackgroundProgress(record,stopState.stopRequested),record.resource=await buildResourceSnapshot(record),await writeBackgroundWorkerResult(record,parsedResult,stdoutBuffer),await writeBackgroundRunRecord(pmRoot,record),await recordWriteScheduler.flush(),record}async function listBackgroundTestRuns(pmRoot,options){const recordPaths=await listBackgroundRunRecordPaths(pmRoot),runs=[];for(const recordPath of recordPaths){const raw=await readFileIfExists(recordPath);if(!raw)continue;const parsed=await parseBackgroundRunRecord(raw,recordPath);runs.push(parsed)}const refreshed=[];for(const run of runs)refreshed.push(await refreshRunIfStale(pmRoot,run));const sorted=(options.status?refreshed.filter(entry=>entry.status===options.status):refreshed).sort((left,right)=>{const byUpdated=Date.parse(right.updated_at)-Date.parse(left.updated_at);return Number.isFinite(byUpdated)&&byUpdated!==0?byUpdated:right.id.localeCompare(left.id)}),limit=typeof options.limit=="number"&&options.limit>=0?options.limit:void 0;return limit===void 0?sorted:sorted.slice(0,limit)}async function getBackgroundTestRunStatus(pmRoot,runId){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const refreshed=await refreshRunIfStale(pmRoot,loaded),workerAlive=isPidRunning(refreshed.worker_pid),childAlive=isPidRunning(refreshed.child_pid);refreshed.status==="running"&&!childAlive&&!refreshed.finished_at&&!workerAlive&&(refreshed.status="failed",refreshed.finished_at=nowIso(),refreshed.error=refreshed.error??"Background run process exited unexpectedly.",await writeBackgroundRunRecord(pmRoot,refreshed)),refreshed.status==="running"&&(refreshed.resource=await buildResourceSnapshot(refreshed),await writeBackgroundRunRecord(pmRoot,refreshed));const heartbeatAt=refreshed.progress?.heartbeat_at,heartbeatAtMs=heartbeatAt?Date.parse(heartbeatAt):Number.NaN,lagMs=Number.isFinite(heartbeatAtMs)?Math.max(0,nowMs()-heartbeatAtMs):void 0,staleMs=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),staleThresholdMs=Number.isFinite(staleMs)&&staleMs>0?staleMs:DEFAULT_BACKGROUND_RUN_HEARTBEAT_STALE_MS,healthState=refreshed.status==="running"?lagMs!==void 0&&lagMs>staleThresholdMs?"stale":"healthy":"inactive";return{run:refreshed,health:{state:healthState,last_heartbeat_at:heartbeatAt,heartbeat_lag_ms:lagMs,worker_alive:workerAlive,child_alive:childAlive}}}function sendBackgroundRunStopSignal(record,force){const signal=force?"SIGKILL":"SIGTERM";if(!isPidRunning(record.worker_pid)||!record.worker_pid)return"none";try{return process.kill(record.worker_pid,signal),signal}catch{return"none"}}function buildStoppingBackgroundProgress(record,signalSent){return{phase:"stopping",message:signalSent==="none"?"Run marked stopped.":`Stop requested via ${signalSent}.`,heartbeat_at:nowIso(),item_index:record.progress?.item_index,item_total:record.progress?.item_total,item_id:record.progress?.item_id,linked_test_index:record.progress?.linked_test_index,linked_test_total:record.progress?.linked_test_total,current_command:record.progress?.current_command,elapsed_ms:record.progress?.elapsed_ms}}async function stopBackgroundTestRun(pmRoot,runId,force=!1){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const refreshed=await refreshRunIfStale(pmRoot,loaded);if(BACKGROUND_RUN_TERMINAL_STATUSES.has(refreshed.status))return{run:refreshed,signal_sent:"none"};const signalSent=sendBackgroundRunStopSignal(refreshed,force);return signalSent==="none"&&(refreshed.status="stopped",refreshed.finished_at=refreshed.finished_at??nowIso()),refreshed.stop_requested_at=nowIso(),refreshed.progress=buildStoppingBackgroundProgress(refreshed,signalSent),await writeBackgroundRunRecord(pmRoot,refreshed),{run:refreshed,signal_sent:signalSent}}async function resumeBackgroundTestRun(pmRoot,runId,requestedBy,noExtensions=!1){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const refreshed=await refreshRunIfStale(pmRoot,loaded);if(!BACKGROUND_RUN_TERMINAL_STATUSES.has(refreshed.status))throw new PmCliError(`Background test run ${runId} is not terminal and cannot be resumed.`,EXIT_CODE.CONFLICT);const started=await startBackgroundTestRun({pmRoot:refreshed.pm_root,globalPmRoot:refreshed.global_pm_root,kind:refreshed.kind,commandArgs:refreshed.command_args,requestedBy,targetId:refreshed.target_id,statusFilter:refreshed.status_filter,resumedFrom:refreshed.id,resumedBy:requestedBy,attempt:refreshed.attempt+1});if(!started.started)return started.run;const spawned=await spawnBackgroundTestRunWorker({pmRoot,runId:started.run.id,noExtensions}),prior={...refreshed,resumed_by:spawned.id};return await writeBackgroundRunRecord(pmRoot,prior),spawned}async function readBackgroundTestRunLogs(pmRoot,runId,stream,tail){const loaded=await readBackgroundTestRunRecord(pmRoot,runId);if(!loaded)throw new PmCliError(`Background test run ${runId} not found`,EXIT_CODE.NOT_FOUND);const resolvedTail=typeof tail=="number"&&Number.isFinite(tail)&&tail>=0?Math.floor(tail):DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES,stdoutRaw=stream==="stdout"||stream==="both"?await readFileIfExists(loaded.stdout_path)??"":"",stderrRaw=stream==="stderr"||stream==="both"?await readFileIfExists(loaded.stderr_path)??"":"";return{run:loaded,stream,tail:resolvedTail,stdout:stream==="stdout"||stream==="both"?tailLines(stdoutRaw,resolvedTail):[],stderr:stream==="stderr"||stream==="both"?tailLines(stderrRaw,resolvedTail):[]}}const _testOnly={buildResourceSnapshot,evaluateWorkerResult,isPidRunning,parseLinuxCpuStat,parseLinuxRssStatus,parseProgressLine,readLinuxCpuSeconds,readLinuxRssBytes,refreshRunIfStale,splitLines,tailLines};export{_testOnly,buildBackgroundTestRunFingerprint,getBackgroundTestRunStatus,listBackgroundTestRuns,readBackgroundTestRunLogs,readBackgroundTestRunRecord,resumeBackgroundTestRun,runBackgroundTestRunWorker,spawnBackgroundTestRunWorker,startBackgroundTestRun,stopBackgroundTestRun};
1
+ import w from"node:fs/promises";import{spawn as j}from"node:child_process";import{createHash as pt,randomBytes as ft}from"node:crypto";import y from"node:path";import{ensureDir as S,pathExists as A,readFileIfExists as x,writeFileAtomic as F}from"../fs/fs-utils.js";import{PmCliError as p}from"../shared/errors.js";import{EXIT_CODE as f}from"../shared/constants.js";import{nowIso as d}from"../shared/time.js";import{getTestRunRecordPath as H,getTestRunResultPath as mt,getTestRunStderrPath as gt,getTestRunStdoutPath as ht,getTestRunsPath as wt,getTestRunsRecordsPath as J,getTestRunsResultsPath as kt,getTestRunsStderrPath as Rt,getTestRunsStdoutPath as Nt}from"../store/paths.js";const Q=new Set(["queued","running"]),U=new Set(["passed","failed","stopped","canceled"]),bt=3e3,Tt=3e3,yt=3e4,V=100,Y=100;function z(){return Date.now()}function X(t){return t.map(e=>e.trim()).filter(e=>e.length>0)}function St(t){const e=t.join(" ").replaceAll(/\s+/g," ").trim();return e.length<=180?e:`${e.slice(0,177)}...`}function Et(){const t=Date.now().toString(36),e=ft(3).toString("hex");return`tr-${t}-${e}`}function Bt(t,e,n){const r={kind:t,command:X(e),pm_root:y.resolve(n)};return pt("sha256").update(JSON.stringify(r)).digest("hex")}function h(t){if(!Number.isInteger(t)||!t||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(typeof e=="object"&&e!==null&&"code"in e?e.code:void 0)==="EPERM"}}async function At(t){await S(wt(t)),await S(J(t)),await S(Nt(t)),await S(Rt(t)),await S(kt(t))}async function Z(t,e){try{const n=JSON.parse(t);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new p(`Failed to parse background test run record at ${e}: ${n instanceof Error?n.message:String(n)}`,f.GENERIC_FAILURE)}}async function m(t,e){const n={...e,updated_at:d()};await F(H(t,e.id),`${JSON.stringify(n,null,2)}
2
+ `)}async function k(t,e){const n=H(t,e),r=await x(n);return r?Z(r,n):null}async function xt(t){const e=J(t);return await A(e)?(await w.readdir(e,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".json")).map(r=>y.join(e,r.name)).sort((r,s)=>s.localeCompare(r)):[]}function tt(t){const e=t.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(e)return Number.parseInt(e[1],10)*1024}async function et(t){if(process.platform==="linux")try{const e=await w.readFile(`/proc/${t}/status`,"utf8");return tt(e)}catch{return}}function nt(t){const e=t.lastIndexOf(")");if(e<0)return{};const r=t.slice(e+2).trim().split(/\s+/),s=Number.parseInt(r[11],10),a=Number.parseInt(r[12],10);return!Number.isFinite(s)||!Number.isFinite(a)?{}:{cpu_user_seconds:s/Y,cpu_system_seconds:a/Y}}async function rt(t){if(process.platform!=="linux")return{};try{const e=await w.readFile(`/proc/${t}/stat`,"utf8");return nt(e)}catch{return{}}}async function O(t){const e=t.child_pid??t.worker_pid;if(!h(e))return;const n=await et(e),r=await rt(e),s=t.started_at?Date.parse(t.started_at):Number.NaN,a=Number.isFinite(s)?Math.max(0,(z()-s)/1e3):void 0;return{recorded_at:d(),rss_bytes:n,cpu_user_seconds:r.cpu_user_seconds,cpu_system_seconds:r.cpu_system_seconds,uptime_seconds:a}}function v(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function st(t,e){if(!e||typeof e!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};const n=e;if(t==="test-all"){const i=n.totals??{};return{summary:{items:typeof i.items=="number"?i.items:void 0,linked_tests:typeof i.linked_tests=="number"?i.linked_tests:void 0,passed:v(i.passed),failed:v(i.failed),skipped:v(i.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:e}}const r=Array.isArray(n.run_results)?n.run_results:[];let s=0,a=0,u=0;for(const i of r){if(!i||typeof i!="object")continue;const o=i.status;if(o==="passed"){s+=1;continue}if(o==="failed"||o==="refused"){a+=1;continue}u+=1}return{summary:{passed:s,failed:a,skipped:u,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:e}}function at(t){const e=t.trim();if(e.length===0)return null;const n=e.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){const c=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:c,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:d(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}const r=e.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!r)return null;const s=Number.parseInt(r[1],10),a=Number.parseInt(r[2],10),u=r[4]?Number.parseInt(r[4],10):void 0,i=e.match(/\scommand="((?:\\.|[^"\\])*)"/),o=i?i[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:s,linked_test_total:a,current_command:o,elapsed_ms:Number.isFinite(u)?u:void 0,heartbeat_at:d(),phase:r[3]?.toLowerCase()==="end"?"finished":"running"}}function it(t){return t.split(/\r?\n/).map(e=>e.trimEnd()).filter(e=>e.length>0)}function I(t,e){if(e<=0)return[];const n=it(t);return n.length<=e?n:n.slice(n.length-e)}async function ot(t){const e=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(e&&e.length>0){const s=y.resolve(t,e);if(await A(s))return s}const n=y.resolve(t,"dist","cli.js");if(await A(n))return n;const r=process.argv[1]?.trim();if(r&&r.length>0){const s=y.resolve(t,r);if(await A(s))return s}throw new p("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",f.GENERIC_FAILURE)}async function R(t,e){if(!Q.has(e.status)||h(e.worker_pid)||e.finished_at)return e;const r={...e,status:"failed",finished_at:d(),error:e.error??"Background test run worker exited before writing terminal status."};return await m(t,r),r}async function Ot(t){await At(t.pmRoot);const e=X(t.commandArgs);if(e.length===0)throw new p("Background test run requires command arguments.",f.USAGE);const n=Bt(t.kind,e,t.pmRoot),r=await qt(t.pmRoot,{});for(const l of r){const _=await R(t.pmRoot,l);if(_.fingerprint===n&&!(!Q.has(_.status)||!h(_.worker_pid)))return{started:!1,run:{..._,duplicate_of:_.id},duplicate_of:_.id}}const s=Et(),a=d(),u=ht(t.pmRoot,s),i=gt(t.pmRoot,s),o=mt(t.pmRoot,s);await w.writeFile(u,"","utf8"),await w.writeFile(i,"","utf8");const c={id:s,kind:t.kind,status:"queued",created_at:a,updated_at:a,requested_by:t.requestedBy,fingerprint:n,command_args:e,command_label:St(e),pm_root:t.pmRoot,global_pm_root:t.globalPmRoot,target_id:t.targetId,status_filter:t.statusFilter,attempt:typeof t.attempt=="number"&&Number.isFinite(t.attempt)&&t.attempt>=1?Math.floor(t.attempt):1,resumed_from:t.resumedFrom,resumed_by:t.resumedBy,stdout_path:u,stderr_path:i,result_path:o,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:a}};return await m(t.pmRoot,c),{started:!0,run:c}}async function It(t){const e=await k(t.pmRoot,t.runId);if(!e)throw new p(`Background test run ${t.runId} not found`,f.NOT_FOUND);if(U.has(e.status))throw new p(`Background test run ${e.id} is already terminal (${e.status}).`,f.CONFLICT);const n=await ot(process.cwd()),r=[];t.noExtensions===!0&&r.push("--no-extensions"),r.push("--path",e.pm_root,"test-runs-worker",e.id);const s={...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:e.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(e.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:e.resumed_from??"",FORCE_COLOR:"0"},a=j(process.execPath,[n,...r],{cwd:process.cwd(),env:s,detached:!0,stdio:"ignore",windowsHide:!0});a.unref();const u={...e,status:"queued",worker_pid:a.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:d()}};return await m(t.pmRoot,u),u}async function ut(t,e,n){await t,await w.appendFile(e,n,"utf8")}function dt(t,e){const n=Number.parseInt(process.env[t]??"",10);return Number.isFinite(n)&&n>0?n:e}function Ct(t){return{...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,FORCE_COLOR:"0"}}function Pt(t,e){return e?["--no-extensions",...t.command_args]:[...t.command_args]}function Lt(t,e){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await m(t,e)}catch{}})},async flush(){await n}}}function ct(t,e){try{t.kill(e)}catch{}}async function Ft(t,e,n,r){if(n.stopRequested)return;n.stopRequested=!0,t.stop_requested_at=d(),t.progress={...t.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:d()},r(),ct(e,"SIGTERM"),setTimeout(()=>ct(e,"SIGKILL"),dt("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",Tt)).unref?.()}function Ut(t,e,n){return{phase:n,message:t,heartbeat_at:d(),item_index:e.item_index,item_total:e.item_total,item_id:e.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function vt(t,e,n,r){return{phase:r,message:t,heartbeat_at:d(),item_index:n.item_index??e.progress?.item_index,item_total:n.item_total??e.progress?.item_total,item_id:n.item_id??e.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function lt(t,e,n){const r=at(e);if(!r)return!1;const s=t.progress?.phase==="stopping"?"stopping":"running";return t.progress=r.item_id?Ut(e,r,s):vt(e,t,r,s),r.phase==="finished"&&!n&&(t.progress.phase="running"),!0}function Mt(t){if(t.trim().length===0)return null;try{return JSON.parse(t)}catch{return null}}function Dt(t,e,n){return n?"stopped":t===0&&e.failed===0&&e.fail_on_skipped_triggered!==!0?"passed":"failed"}function Gt(t,e){return{phase:"finished",message:e?"Background run stopped.":`Background run finished with status=${t.status}.`,heartbeat_at:d(),item_index:t.progress?.item_index,item_total:t.progress?.item_total,item_id:t.progress?.item_id,linked_test_index:t.progress?.linked_test_index,linked_test_total:t.progress?.linked_test_total,current_command:t.progress?.current_command,elapsed_ms:t.progress?.elapsed_ms}}async function $t(t,e,n){if(e!==null){await F(t.result_path,`${JSON.stringify(e,null,2)}
3
+ `);return}await F(t.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:I(n,V)},null,2)}
4
+ `)}async function te(t,e,n=!1){const r=await k(t,e);if(!r)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const s={...r,status:"running",started_at:r.started_at??d(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:d()}},a=await ot(process.cwd()),u=Ct(s);await m(t,s);const i=Pt(s,n),o=j(process.execPath,[a,...i],{cwd:process.cwd(),env:u,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});s.child_pid=o.pid;const c=Lt(t,s),l=c.schedule;let _=Promise.resolve(),C=Promise.resolve(),P="",N="";const b={stopRequested:!1},E=()=>{Ft(s,o,b,l)};process.on("SIGTERM",E),process.on("SIGINT",E);const M=setInterval(()=>{(async()=>(s.resource=await O(s),s.progress.heartbeat_at=d(),l()))()},dt("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",bt));M.unref?.(),o.stdout?.on("data",T=>{const g=T.toString("utf8");P+=g,_=ut(_,s.stdout_path,g)}),o.stderr?.on("data",T=>{const g=T.toString("utf8");C=ut(C,s.stderr_path,g),N+=g;const B=N.split(/\r?\n/);N=B.pop();let K=!1;for(const _t of B){const W=_t.trimEnd();W.length>0&&lt(s,W,b.stopRequested)&&(K=!0)}K&&l()});let L=null,D=null;try{({code:L,signal:D}=await new Promise(T=>{o.on("close",(g,B)=>{T({code:g,signal:B})})}))}finally{clearInterval(M),process.off("SIGTERM",E),process.off("SIGINT",E)}await _,await C;const G=N.trimEnd();G.length>0&&lt(s,G,b.stopRequested)&&l(),N="";const $=Mt(P),q=st(s.kind,$);return s.summary=q.summary,s.exit_code=typeof L=="number"?L:void 0,s.signal=D??void 0,s.finished_at=d(),s.status=Dt(s.exit_code,q.summary,b.stopRequested),s.progress=Gt(s,b.stopRequested),s.resource=await O(s),await $t(s,$,P),await m(t,s),await c.flush(),s}async function qt(t,e){const n=await xt(t),r=[];for(const o of n){const c=await x(o);if(!c)continue;const l=await Z(c,o);r.push(l)}const s=[];for(const o of r)s.push(await R(t,o));const u=(e.status?s.filter(o=>o.status===e.status):s).sort((o,c)=>{const l=Date.parse(c.updated_at)-Date.parse(o.updated_at);return Number.isFinite(l)&&l!==0?l:c.id.localeCompare(o.id)}),i=typeof e.limit=="number"&&e.limit>=0?e.limit:void 0;return i===void 0?u:u.slice(0,i)}async function ee(t,e){const n=await k(t,e);if(!n)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const r=await R(t,n),s=h(r.worker_pid),a=h(r.child_pid);r.status==="running"&&!a&&!r.finished_at&&!s&&(r.status="failed",r.finished_at=d(),r.error=r.error??"Background run process exited unexpectedly.",await m(t,r)),r.status==="running"&&(r.resource=await O(r),await m(t,r));const u=r.progress?.heartbeat_at,i=u?Date.parse(u):Number.NaN,o=Number.isFinite(i)?Math.max(0,z()-i):void 0,c=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(c)&&c>0?c:yt,_=r.status==="running"?o!==void 0&&o>l?"stale":"healthy":"inactive";return{run:r,health:{state:_,last_heartbeat_at:u,heartbeat_lag_ms:o,worker_alive:s,child_alive:a}}}function Kt(t,e){const n=e?"SIGKILL":"SIGTERM";if(!h(t.worker_pid)||!t.worker_pid)return"none";try{return process.kill(t.worker_pid,n),n}catch{return"none"}}function Wt(t,e){return{phase:"stopping",message:e==="none"?"Run marked stopped.":`Stop requested via ${e}.`,heartbeat_at:d(),item_index:t.progress?.item_index,item_total:t.progress?.item_total,item_id:t.progress?.item_id,linked_test_index:t.progress?.linked_test_index,linked_test_total:t.progress?.linked_test_total,current_command:t.progress?.current_command,elapsed_ms:t.progress?.elapsed_ms}}async function ne(t,e,n=!1){const r=await k(t,e);if(!r)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const s=await R(t,r);if(U.has(s.status))return{run:s,signal_sent:"none"};const a=Kt(s,n);return a==="none"&&(s.status="stopped",s.finished_at=s.finished_at??d()),s.stop_requested_at=d(),s.progress=Wt(s,a),await m(t,s),{run:s,signal_sent:a}}async function re(t,e,n,r=!1){const s=await k(t,e);if(!s)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const a=await R(t,s);if(!U.has(a.status))throw new p(`Background test run ${e} is not terminal and cannot be resumed.`,f.CONFLICT);const u=await Ot({pmRoot:a.pm_root,globalPmRoot:a.global_pm_root,kind:a.kind,commandArgs:a.command_args,requestedBy:n,targetId:a.target_id,statusFilter:a.status_filter,resumedFrom:a.id,resumedBy:n,attempt:a.attempt+1});if(!u.started)return u.run;const i=await It({pmRoot:t,runId:u.run.id,noExtensions:r}),o={...a,resumed_by:i.id};return await m(t,o),i}async function se(t,e,n,r){const s=await k(t,e);if(!s)throw new p(`Background test run ${e} not found`,f.NOT_FOUND);const a=typeof r=="number"&&Number.isFinite(r)&&r>=0?Math.floor(r):V,u=n==="stdout"||n==="both"?await x(s.stdout_path)??"":"",i=n==="stderr"||n==="both"?await x(s.stderr_path)??"":"";return{run:s,stream:n,tail:a,stdout:n==="stdout"||n==="both"?I(u,a):[],stderr:n==="stderr"||n==="both"?I(i,a):[]}}const ae={buildResourceSnapshot:O,evaluateWorkerResult:st,isPidRunning:h,parseLinuxCpuStat:nt,parseLinuxRssStatus:tt,parseProgressLine:at,readLinuxCpuSeconds:rt,readLinuxRssBytes:et,refreshRunIfStale:R,splitLines:it,tailLines:I};export{ae as _testOnly,Bt as buildBackgroundTestRunFingerprint,ee as getBackgroundTestRunStatus,qt as listBackgroundTestRuns,se as readBackgroundTestRunLogs,k as readBackgroundTestRunRecord,re as resumeBackgroundTestRun,te as runBackgroundTestRunWorker,It as spawnBackgroundTestRunWorker,Ot as startBackgroundTestRun,ne as stopBackgroundTestRun};
5
5
  //# sourceMappingURL=background-runs.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]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();import{mutateItem}from"../store/item-store.js";import{compareTimestampStrings}from"../shared/time.js";const DEFAULT_TRACKED_TEST_RUN_HISTORY_LIMIT=20;function trackedTestRunHistoryLimit(){const raw=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!raw||raw.trim().length===0)return DEFAULT_TRACKED_TEST_RUN_HISTORY_LIMIT;const parsed=Number.parseInt(raw,10);return!Number.isFinite(parsed)||parsed<=0?DEFAULT_TRACKED_TEST_RUN_HISTORY_LIMIT:parsed}function buildTrackedTestRunHistory(entries){const normalized=[...entries].filter(entry=>entry.run_id.trim().length>0&&entry.started_at.trim().length>0&&entry.finished_at.trim().length>0&&entry.recorded_at.trim().length>0).sort((left,right)=>{const byRecorded=compareTimestampStrings(left.recorded_at,right.recorded_at);if(byRecorded!==0)return byRecorded;const byRunId=left.run_id.localeCompare(right.run_id);return byRunId!==0?byRunId:left.kind.localeCompare(right.kind)}),historyLimit=trackedTestRunHistoryLimit();return normalized.length>historyLimit?normalized.slice(normalized.length-historyLimit):normalized}async function appendTrackedTestRunSummary(options){await mutateItem({pmRoot:options.pmRoot,settings:options.settings,id:options.itemId,op:"test_run_track",author:options.author,message:options.message,force:!1,mutate(document){const current=document.metadata.test_runs??[];return document.metadata.test_runs=buildTrackedTestRunHistory([...current,options.entry]),{changedFields:["test_runs"]}}})}export{appendTrackedTestRunSummary,buildTrackedTestRunHistory};
1
+ import{mutateItem as u}from"../store/item-store.js";import{compareTimestampStrings as o}from"../shared/time.js";const m=20;function d(){const t=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!t||t.trim().length===0)return m;const e=Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?m:e}function c(t){const e=[...t].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,a)=>{const s=o(r.recorded_at,a.recorded_at);if(s!==0)return s;const i=r.run_id.localeCompare(a.run_id);return i!==0?i:r.kind.localeCompare(a.kind)}),n=d();return e.length>n?e.slice(e.length-n):e}async function l(t){await u({pmRoot:t.pmRoot,settings:t.settings,id:t.itemId,op:"test_run_track",author:t.author,message:t.message,force:!1,mutate(e){const n=e.metadata.test_runs??[];return e.metadata.test_runs=c([...n,t.entry]),{changedFields:["test_runs"]}}})}export{l as appendTrackedTestRunSummary,c as buildTrackedTestRunHistory};
2
2
  //# sourceMappingURL=item-test-run-tracking.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]="7140bb24-7202-541a-bc13-6a67bac260a8")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_SELECTOR_ENTRY_LABEL_LENGTH=100;function parseOnlyIndexValue(raw,optionName="--only-index"){const value=typeof raw=="number"?raw:Number(String(raw).trim());if(!Number.isInteger(value)||value<1)throw new PmCliError(`${optionName} requires a 1-based integer index into the linked-test list (got "${raw}"). Use pm test <id> --list to inspect positions.`,EXIT_CODE.USAGE);return value}function summarizeSelectorEntry(entry){const normalized=(entry.command??entry.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return normalized.length<=MAX_SELECTOR_ENTRY_LABEL_LENGTH?normalized:`${normalized.slice(0,MAX_SELECTOR_ENTRY_LABEL_LENGTH-3)}...`}function describeLinkedTestEntries(tests){return tests.map((entry,index)=>`${index+1}. ${summarizeSelectorEntry(entry)}`).join("; ")}function activeSelectorKinds(selector){const kinds=[];return selector.match!==void 0&&kinds.push("match"),selector.onlyIndex!==void 0&&kinds.push("only-index"),selector.onlyLast===!0&&kinds.push("only-last"),kinds}function entryMatchesSubstring(entry,needle){const command=entry.command?.toLowerCase()??"",entryPath=entry.path?.toLowerCase()??"";return command.includes(needle)||entryPath.includes(needle)}function resolveLinkedTestRunSelection(tests,selector){const kinds=activeSelectorKinds(selector);if(kinds.length===0)return{selector:null,requested:null,selected:tests,selected_indexes:tests.map((_,index)=>index+1),selected_count:tests.length,skipped_count:0};if(kinds.length>1)throw new PmCliError(`Combine at most one linked-test selector per run: ${kinds.map(kind2=>`--${kind2}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,EXIT_CODE.USAGE);const kind=kinds[0];if(tests.length===0)throw new PmCliError(`--${kind} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,EXIT_CODE.USAGE);if(kind==="match"){const needle=selector.match.trim().toLowerCase();if(needle.length===0)throw new PmCliError("--match requires a non-empty substring to match against linked-test command/path values",EXIT_CODE.USAGE);const selectedIndexes=[],selected=[];for(let index=0;index<tests.length;index+=1)entryMatchesSubstring(tests[index],needle)&&(selected.push(tests[index]),selectedIndexes.push(index+1));if(selected.length===0)throw new PmCliError(`--match "${selector.match}" matched none of the ${tests.length} linked test(s). Available entries: ${describeLinkedTestEntries(tests)}`,EXIT_CODE.USAGE);return{selector:"match",requested:selector.match,selected,selected_indexes:selectedIndexes,selected_count:selected.length,skipped_count:tests.length-selected.length}}if(kind==="only-index"){const index=parseOnlyIndexValue(selector.onlyIndex);if(index>tests.length)throw new PmCliError(`--only-index ${index} is out of range: this item has ${tests.length} linked test(s). Available entries: ${describeLinkedTestEntries(tests)}`,EXIT_CODE.USAGE);return{selector:"only-index",requested:String(index),selected:[tests[index-1]],selected_indexes:[index],selected_count:1,skipped_count:tests.length-1}}return{selector:"only-last",requested:"last",selected:[tests[tests.length-1]],selected_indexes:[tests.length],selected_count:1,skipped_count:tests.length-1}}export{describeLinkedTestEntries,parseOnlyIndexValue,resolveLinkedTestRunSelection};
1
+ import{EXIT_CODE as o}from"../shared/constants.js";import{PmCliError as l}from"../shared/errors.js";const a=100;function h(e,n="--only-index"){const t=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(t)||t<1)throw new l(`${n} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,o.USAGE);return t}function m(e){const t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=a?t:`${t.slice(0,a-3)}...`}function u(e){return e.map((n,t)=>`${t+1}. ${m(n)}`).join("; ")}function p(e){const n=[];return e.match!==void 0&&n.push("match"),e.onlyIndex!==void 0&&n.push("only-index"),e.onlyLast===!0&&n.push("only-last"),n}function f(e,n){const t=e.command?.toLowerCase()??"",d=e.path?.toLowerCase()??"";return t.includes(n)||d.includes(n)}function _(e,n){const t=p(n);if(t.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((i,s)=>s+1),selected_count:e.length,skipped_count:0};if(t.length>1)throw new l(`Combine at most one linked-test selector per run: ${t.map(i=>`--${i}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,o.USAGE);const d=t[0];if(e.length===0)throw new l(`--${d} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,o.USAGE);if(d==="match"){const i=n.match.trim().toLowerCase();if(i.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",o.USAGE);const s=[],r=[];for(let c=0;c<e.length;c+=1)f(e[c],i)&&(r.push(e[c]),s.push(c+1));if(r.length===0)throw new l(`--match "${n.match}" matched none of the ${e.length} linked test(s). Available entries: ${u(e)}`,o.USAGE);return{selector:"match",requested:n.match,selected:r,selected_indexes:s,selected_count:r.length,skipped_count:e.length-r.length}}if(d==="only-index"){const i=h(n.onlyIndex);if(i>e.length)throw new l(`--only-index ${i} is out of range: this item has ${e.length} linked test(s). Available entries: ${u(e)}`,o.USAGE);return{selector:"only-index",requested:String(i),selected:[e[i-1]],selected_indexes:[i],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}export{u as describeLinkedTestEntries,h as parseOnlyIndexValue,_ as resolveLinkedTestRunSelection};
2
2
  //# sourceMappingURL=run-selectors.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]="de43e8e6-d7ef-53cc-94b0-ccdf1c4f94a3")}catch{}})();const DEFAULT_ESTIMATE_MINUTES_BY_TYPE={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},FALLBACK_ESTIMATE_MINUTES=120;function isHonoredMinutes(value){return typeof value=="number"&&Number.isFinite(value)&&value>0}function toLowercasedLookup(source){const lookup=new Map;for(const[key,value]of Object.entries(source))lookup.set(key.toLowerCase(),value);return lookup}const BUILTIN_LOWERCASED_LOOKUP=toLowercasedLookup(DEFAULT_ESTIMATE_MINUTES_BY_TYPE),OVERRIDE_LOOKUP_CACHE=new WeakMap;function lowercasedOverrideLookup(overrides){const cached=OVERRIDE_LOOKUP_CACHE.get(overrides);if(cached)return cached;const lookup=toLowercasedLookup(overrides);return OVERRIDE_LOOKUP_CACHE.set(overrides,lookup),lookup}function resolveEstimateDefaultMinutes(type,overrides){const key=(type??"").trim().toLowerCase();if(key.length===0)return FALLBACK_ESTIMATE_MINUTES;if(overrides){const overrideValue=lowercasedOverrideLookup(overrides).get(key);if(isHonoredMinutes(overrideValue))return Math.floor(overrideValue)}const builtinValue=BUILTIN_LOWERCASED_LOOKUP.get(key);return isHonoredMinutes(builtinValue)?Math.floor(builtinValue):FALLBACK_ESTIMATE_MINUTES}function normalizeEstimateDefaultOverrides(raw){const normalized={};if(raw===null||typeof raw!="object"||Array.isArray(raw))return normalized;for(const[rawKey,rawValue]of Object.entries(raw)){const key=rawKey.trim();key.length===0||!isHonoredMinutes(rawValue)||(normalized[key]=Math.floor(rawValue))}return normalized}export{DEFAULT_ESTIMATE_MINUTES_BY_TYPE,FALLBACK_ESTIMATE_MINUTES,normalizeEstimateDefaultOverrides,resolveEstimateDefaultMinutes};
1
+ const a={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},s=120;function i(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function u(e){const t=new Map;for(const[o,n]of Object.entries(e))t.set(o.toLowerCase(),n);return t}const f=u(a),c=new WeakMap;function l(e){const t=c.get(e);if(t)return t;const o=u(e);return c.set(e,o),o}function E(e,t){const o=(e??"").trim().toLowerCase();if(o.length===0)return s;if(t){const r=l(t).get(o);if(i(r))return Math.floor(r)}const n=f.get(o);return i(n)?Math.floor(n):s}function p(e){const t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(const[o,n]of Object.entries(e)){const r=o.trim();r.length===0||!i(n)||(t[r]=Math.floor(n))}return t}export{a as DEFAULT_ESTIMATE_MINUTES_BY_TYPE,s as FALLBACK_ESTIMATE_MINUTES,p as normalizeEstimateDefaultOverrides,E as resolveEstimateDefaultMinutes};
2
2
  //# sourceMappingURL=estimate-defaults.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]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{resolveEstimateDefaultMinutes}from"./estimate-defaults.js";const DEFAULT_GRANTED_FIX_SCOPES=["metadata","resolution"],SUPPORTED_FIX_SCOPES=["metadata","resolution","estimates","timestamps","lifecycle"],DEFAULT_RESOLUTION_BACKFILL_VALUE="completed";function quoteForCommand(value){return`"${value.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function toMeaningfulValue(value){const trimmed=value?.trim();return trimmed!==void 0&&trimmed.length>0?trimmed:void 0}function planResolutionBackfillFixes(rows){const fixes=[];for(const row of rows){if(!row.missing_fields.includes("resolution"))continue;const value=toMeaningfulValue(row.close_reason)??DEFAULT_RESOLUTION_BACKFILL_VALUE;fixes.push({item_id:row.id,check:"resolution",field:"resolution",kind:"set_resolution",value,command:`pm update ${row.id} --resolution ${quoteForCommand(value)}`,gate:"resolution"})}return fixes}function planCloseReasonBackfillFixes(rows){const fixes=[];for(const row of rows){const value=toMeaningfulValue(row.resolution);value!==void 0&&fixes.push({item_id:row.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value,command:`pm update ${row.id} --close-reason ${quoteForCommand(value)}`,gate:"metadata"})}return fixes}function planEstimateBackfillFixes(rows,overrides){return rows.map(row=>{const minutes=resolveEstimateDefaultMinutes(row.type,overrides);return{item_id:row.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(minutes),command:`pm update ${row.id} --estimate ${minutes}`,gate:"estimates"}})}function planTerminalParentFixes(rows){return rows.map(row=>row.grandparent_id!==void 0&&row.grandparent_active===!0?{item_id:row.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:row.grandparent_id,command:`pm update ${row.id} --parent ${row.grandparent_id}`,gate:"lifecycle"}:{item_id:row.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${row.id} --unset parent`,gate:"lifecycle"})}function planStaleLinkPruneFixes(rows){const fixes=[];for(const row of rows){if(row.classification!=="deleted")continue;const noun=row.link_kind==="files"?"files":"docs";fixes.push({item_id:row.item_id,check:"files",field:row.link_kind,kind:row.link_kind==="files"?"prune_file_link":"prune_doc_link",path:row.path,command:`pm ${noun} ${row.item_id} --remove ${quoteForCommand(row.path)}`})}return fixes}function resolveGrantedFixScopes(rawScopes){const tokens=(rawScopes??[]).flatMap(raw=>raw.split(",")).map(raw=>raw.trim()).filter(raw=>raw.length>0);if(tokens.length===0){if(rawScopes!==void 0&&rawScopes.length>0)throw new PmCliError(`--fix-scope values must not be empty. Supported values: ${SUPPORTED_FIX_SCOPES.join(", ")}.`,EXIT_CODE.USAGE);return new Set(DEFAULT_GRANTED_FIX_SCOPES)}const granted=new Set;for(const raw of tokens){const normalized=raw.toLowerCase().replaceAll("-","_");if(SUPPORTED_FIX_SCOPES.includes(normalized)){granted.add(normalized);continue}throw new PmCliError(`Unknown --fix-scope value "${raw}". Supported values: ${SUPPORTED_FIX_SCOPES.join(", ")}.`,EXIT_CODE.USAGE)}return granted}function partitionFixesByGrant(fixes,granted){const applicable=[],gated=[];for(const fix of fixes)fix.gate!==void 0&&!granted.has(fix.gate)?gated.push(fix):applicable.push(fix);return{applicable,gated}}function toFixOutputRow(fix){return{item_id:fix.item_id,check:fix.check,field:fix.field,command:fix.command,...fix.gate!==void 0?{gate:fix.gate}:{}}}export{DEFAULT_GRANTED_FIX_SCOPES,SUPPORTED_FIX_SCOPES,partitionFixesByGrant,planCloseReasonBackfillFixes,planEstimateBackfillFixes,planResolutionBackfillFixes,planStaleLinkPruneFixes,planTerminalParentFixes,resolveGrantedFixScopes,toFixOutputRow};
1
+ import{EXIT_CODE as s}from"../shared/constants.js";import{PmCliError as d}from"../shared/errors.js";import{resolveEstimateDefaultMinutes as c}from"./estimate-defaults.js";const u=["metadata","resolution"],a=["metadata","resolution","estimates","timestamps","lifecycle"],m="completed";function r(n){return`"${n.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function l(n){const e=n?.trim();return e!==void 0&&e.length>0?e:void 0}function k(n){const e=[];for(const t of n){if(!t.missing_fields.includes("resolution"))continue;const i=l(t.close_reason)??m;e.push({item_id:t.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${t.id} --resolution ${r(i)}`,gate:"resolution"})}return e}function g(n){const e=[];for(const t of n){const i=l(t.resolution);i!==void 0&&e.push({item_id:t.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${t.id} --close-reason ${r(i)}`,gate:"metadata"})}return e}function h(n,e){return n.map(t=>{const i=c(t.type,e);return{item_id:t.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${t.id} --estimate ${i}`,gate:"estimates"}})}function x(n){return n.map(e=>e.grandparent_id!==void 0&&e.grandparent_active===!0?{item_id:e.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:e.grandparent_id,command:`pm update ${e.id} --parent ${e.grandparent_id}`,gate:"lifecycle"}:{item_id:e.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${e.id} --unset parent`,gate:"lifecycle"})}function $(n){const e=[];for(const t of n){if(t.classification!=="deleted")continue;const i=t.link_kind==="files"?"files":"docs";e.push({item_id:t.item_id,check:"files",field:t.link_kind,kind:t.link_kind==="files"?"prune_file_link":"prune_doc_link",path:t.path,command:`pm ${i} ${t.item_id} --remove ${r(t.path)}`})}return e}function E(n){const e=(n??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(e.length===0){if(n!==void 0&&n.length>0)throw new d(`--fix-scope values must not be empty. Supported values: ${a.join(", ")}.`,s.USAGE);return new Set(u)}const t=new Set;for(const i of e){const o=i.toLowerCase().replaceAll("-","_");if(a.includes(o)){t.add(o);continue}throw new d(`Unknown --fix-scope value "${i}". Supported values: ${a.join(", ")}.`,s.USAGE)}return t}function F(n,e){const t=[],i=[];for(const o of n)o.gate!==void 0&&!e.has(o.gate)?i.push(o):t.push(o);return{applicable:t,gated:i}}function S(n){return{item_id:n.item_id,check:n.check,field:n.field,command:n.command,...n.gate!==void 0?{gate:n.gate}:{}}}export{u as DEFAULT_GRANTED_FIX_SCOPES,a as SUPPORTED_FIX_SCOPES,F as partitionFixesByGrant,g as planCloseReasonBackfillFixes,h as planEstimateBackfillFixes,k as planResolutionBackfillFixes,$ as planStaleLinkPruneFixes,x as planTerminalParentFixes,E as resolveGrantedFixScopes,S as toFixOutputRow};
2
2
  //# sourceMappingURL=fix-planning.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]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();const REMOTE_ARTIFACT_REFERENCE_PATTERN=/^[a-z][a-z0-9+.-]+:\/\//i;function isRemoteLinkedArtifactReference(path){return REMOTE_ARTIFACT_REFERENCE_PATTERN.test(path.trim())}export{isRemoteLinkedArtifactReference};
1
+ const t=/^[a-z][a-z0-9+.-]+:\/\//i;function E(e){return t.test(e.trim())}export{E as isRemoteLinkedArtifactReference};
2
2
  //# sourceMappingURL=linked-artifact-reference.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]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function buildMissingByTypeCounts(occurrences){const countsByType=new Map;for(const occurrence of occurrences){let fieldCounts=countsByType.get(occurrence.item_type);fieldCounts||(fieldCounts=new Map,countsByType.set(occurrence.item_type,fieldCounts)),fieldCounts.set(occurrence.field,(fieldCounts.get(occurrence.field)??0)+1)}const result={};for(const type of[...countsByType.keys()].sort((left,right)=>left.localeCompare(right))){const fieldCounts=countsByType.get(type),fields={};for(const field of[...fieldCounts.keys()].sort((left,right)=>left.localeCompare(right)))fields[field]=fieldCounts.get(field);result[type]=fields}return result}export{buildMissingByTypeCounts};
1
+ function r(f){const o=new Map;for(const t of f){let e=o.get(t.item_type);e||(e=new Map,o.set(t.item_type,e)),e.set(t.field,(e.get(t.field)??0)+1)}const n={};for(const t of[...o.keys()].sort((e,s)=>e.localeCompare(s))){const e=o.get(t),s={};for(const c of[...e.keys()].sort((i,l)=>i.localeCompare(l)))s[c]=e.get(c);n[t]=s}return n}export{r as buildMissingByTypeCounts};
2
2
  //# sourceMappingURL=missing-by-type.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]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function preferClassification(current,next){return current==="malformed"||next==="malformed"?"malformed":current==="moved"||next==="moved"?"moved":"deleted"}function ownerKey(input){return`${input.item_id} ${input.link_kind}`}function buildMissingLinkedPathRows(rows,lookup){const buckets=new Map;for(const row of rows){const bucket=buckets.get(row.path);bucket?(bucket.classification=preferClassification(bucket.classification,row.classification),bucket.owners.set(ownerKey(row),row)):buckets.set(row.path,{classification:row.classification,owners:new Map([[ownerKey(row),row]])})}return[...buckets.entries()].sort(([left],[right])=>left.localeCompare(right)).map(([path,bucket])=>({path,classification:bucket.classification,items:[...bucket.owners.values()].map(owner=>{const metadata=lookup(owner.item_id);return{id:owner.item_id,type:metadata?.type??"Unknown",title:metadata?.title??"",status:metadata?.status??"",field:owner.link_kind}}).sort((leftOwner,rightOwner)=>{const byId=leftOwner.id.localeCompare(rightOwner.id);return byId!==0?byId:leftOwner.field.localeCompare(rightOwner.field)})}))}function escapeTitle(title){return title.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function summarizeMissingLinkedPathRows(rows){const lines=[];for(const row of rows)for(const owner of row.items)lines.push(`${row.path}:${row.classification} owner=${owner.id} status=${owner.status} field=${owner.field} title="${escapeTitle(owner.title)}"`);return lines}export{buildMissingLinkedPathRows,summarizeMissingLinkedPathRows};
1
+ function r(e,s){return e==="malformed"||s==="malformed"?"malformed":e==="moved"||s==="moved"?"moved":"deleted"}function l(e){return`${e.item_id} ${e.link_kind}`}function d(e,s){const o=new Map;for(const i of e){const t=o.get(i.path);t?(t.classification=r(t.classification,i.classification),t.owners.set(l(i),i)):o.set(i.path,{classification:i.classification,owners:new Map([[l(i),i]])})}return[...o.entries()].sort(([i],[t])=>i.localeCompare(t)).map(([i,t])=>({path:i,classification:t.classification,items:[...t.owners.values()].map(n=>{const a=s(n.item_id);return{id:n.item_id,type:a?.type??"Unknown",title:a?.title??"",status:a?.status??"",field:n.link_kind}}).sort((n,a)=>{const c=n.id.localeCompare(a.id);return c!==0?c:n.field.localeCompare(a.field)})}))}function f(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function m(e){const s=[];for(const o of e)for(const i of o.items)s.push(`${o.path}:${o.classification} owner=${i.id} status=${i.status} field=${i.field} title="${f(i.title)}"`);return s}export{d as buildMissingLinkedPathRows,m as summarizeMissingLinkedPathRows};
2
2
  //# sourceMappingURL=missing-link-owners.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]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();const DEFAULT_STALE_PATH_CANDIDATE_LIMIT=3;function basenameOf(relativePath){const lastSlash=Math.max(relativePath.lastIndexOf("/"),relativePath.lastIndexOf("\\"));return lastSlash===-1?relativePath:relativePath.slice(lastSlash+1)}function classifyStaleLinkedPaths(stalePaths,candidateFiles,candidateLimit=3){const limit=Number.isFinite(candidateLimit)&&candidateLimit>=1?Math.floor(candidateLimit):3,candidatesByBasename=new Map;for(const candidate of candidateFiles){const basename=basenameOf(candidate);if(basename.length===0)continue;const bucket=candidatesByBasename.get(basename);bucket?bucket.push(candidate):candidatesByBasename.set(basename,[candidate])}return stalePaths.map(stalePath=>{if(stalePath.includes(",")||stalePath.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:stalePath,classification:"malformed",candidates:[],candidates_truncated:!1};const matches=(candidatesByBasename.get(basenameOf(stalePath))??[]).filter(candidate=>candidate!==stalePath).sort((left,right)=>left.localeCompare(right));return matches.length===0?{path:stalePath,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:stalePath,classification:"moved",candidates:matches.slice(0,limit),candidates_truncated:matches.length>limit}})}function summarizeStaleLinkedPathClassifications(classified){return classified.map(entry=>entry.classification==="moved"?`${entry.path}:moved:${entry.candidates[0]}`:`${entry.path}:${entry.classification}`)}export{DEFAULT_STALE_PATH_CANDIDATE_LIMIT,classifyStaleLinkedPaths,summarizeStaleLinkedPathClassifications};
1
+ const l=3;function d(a){const n=Math.max(a.lastIndexOf("/"),a.lastIndexOf("\\"));return n===-1?a:a.slice(n+1)}function r(a,n,c=3){const o=Number.isFinite(c)&&c>=1?Math.floor(c):3,i=new Map;for(const e of n){const s=d(e);if(s.length===0)continue;const t=i.get(s);t?t.push(e):i.set(s,[e])}return a.map(e=>{if(e.includes(",")||e.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:e,classification:"malformed",candidates:[],candidates_truncated:!1};const s=(i.get(d(e))??[]).filter(t=>t!==e).sort((t,f)=>t.localeCompare(f));return s.length===0?{path:e,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:e,classification:"moved",candidates:s.slice(0,o),candidates_truncated:s.length>o}})}function u(a){return a.map(n=>n.classification==="moved"?`${n.path}:moved:${n.candidates[0]}`:`${n.path}:${n.classification}`)}export{l as DEFAULT_STALE_PATH_CANDIDATE_LIMIT,r as classifyStaleLinkedPaths,u as summarizeStaleLinkedPathClassifications};
2
2
  //# sourceMappingURL=stale-file-classification.js.map