@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,6 +1,6 @@
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]="ff655b5f-e369-5a1c-b2d3-680d27fc94d6")}catch{}})();import{readJsonPathValue,splitJsonPathSegments}from"./json-path.js";import{isItemRevisionConflict}from"../lifecycle/item-revision.js";import{detectEmptyLinkedTestRun,findLinkedTestExecutionReceipt,renderLinkedTestRestoreCommand,resolveLinkedTestRestoreScope}from"./execution-receipts.js";import{seedLinkedTestWorkspaceSnapshot}from"./workspace-snapshot.js";import{detectLinkedTestCommandNotFound}from"./command-resolution.js";import{updateLinkedTest,parseLinkedTestUpdateOptions,assertLinkedTestEditUsage}from"./update.js";import{admitLinkedTestRequest,assertLinkedTestCommand,linkedTestsHaveSameIdentity}from"./entry.js";import{countFailureCategories,createLinkedTestSetupGate,isLinkedTestSetup,orderLinkedTestsSetupFirst,parseLinkedTestPhase,resolveSetupWorkspaceRefusal,withLinkedTestSetupEntries}from"./run-phases.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{spawn}from"node:child_process";import{killProcessTree}from"../../core/shared/process-tree.js";const LINKED_TEST_TREE_KILL={taskkillTimeoutMs:null};import{cp,mkdir,mkdtemp,open,readdir,rm,symlink}from"node:fs/promises";import{tmpdir}from"node:os";import path from"node:path";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{isFileMissingError,pathExists,readFileIfExists}from"../../core/fs/fs-utils.js";import{getWorkspaceHistoryPath,writeWorkspaceJsonWithHistory}from"../../core/history/workspace-history.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{createStdinTokenResolver,parseCsvKv,parseOptionalNumber}from"../../core/item/parse.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{resolveAuthor}from"../../core/shared/author.js";import{PmCliError}from"../../core/shared/errors.js";import{stableValueEquals}from"../../core/shared/serialization.js";import{nowIso}from"../../core/shared/time.js";import{locateItem,mutateItem,readLocatedItem}from"../../core/store/item-store.js";import{getSettingsPath,ITEM_FILE_EXTENSIONS,resolveGlobalPmRoot,resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{appendTrackedTestRunSummary,buildTrackedTestRunHistory}from"../../core/test/item-test-run-tracking.js";import{runInit}from"../init.js";import{looksLikeStructuredLinkedTestEntry,normalizeStructuredLinkedTestEntry}from"./entry.js";import{LINKED_TEST_PM_CONTEXT_MODE_VALUES as PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean as parseLinkedTestBooleanValue,parseLinkedTestContextMode as parseLinkedTestContextModeValue,parseLinkedTestEnvClear as parseLinkedTestEnvClearValue,parseLinkedTestEnvSet as parseLinkedTestEnvSetValue,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode}from"./parsers.js";import{parseOnlyIndexValue,resolveLinkedTestRunSelection}from"../../core/test/run-selectors.js";import{SCOPE_VALUES}from"../../types/index.js";import{diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow}from"./measurements.js";import{withHostEnvironmentBoundary}from"../environment/host-environment-errors.js";import{linkedCollectionMutationFields,projectLinkedCollectionMutation,writtenLinkedEntries}from"../linked-artifacts.js";import{SOURCE_CONTEXT_ACCESS_ENV}from"../environment/source-context.js";import{assertTestMeasurementExecution,assertTestMeasurementRun}from"./prerequisites.js";import{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust}from"./trust.js";const TEST_OUTPUT_MAX_BUFFER_BYTES=20*1024*1024,DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS=3e3,DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS=1e4,DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS=5e3,MAX_LINKED_TEST_COMMAND_LABEL_LENGTH=120,LINKED_TEST_TRACKER_DIRS_TO_SKIP=new Set(["locks","extensions","runtime"]),LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP=new Set(["history","index","search","extensions","locks","runtime"]),LINKED_TEST_INFRA_COLLISION_PATTERNS=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],LINKED_TEST_LOCK_ACQUISITION_PATTERN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,LINKED_TEST_LOCK_CONTENTION_CONTEXT_PATTERN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,PM_TRACKER_READ_SUBCOMMANDS=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function readPositiveIntegerEnv(name,fallback){const raw=process.env[name];if(typeof raw!="string"||raw.trim().length===0)return fallback;const parsed=Number.parseInt(raw,10);return!Number.isFinite(parsed)||parsed<=0?fallback:parsed}function linkedTestTimeoutForceKillDelayMs(){return readPositiveIntegerEnv("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS)}function linkedTestHeartbeatIntervalMs(){return readPositiveIntegerEnv("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS)}function linkedTestPipeCloseGraceMs(){return readPositiveIntegerEnv("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS)}import{countFailureCategories as countFailureCategories2}from"./run-phases.js";function resolveTrackedRunId(kind){const fromEnv=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return fromEnv&&fromEnv.length>0?fromEnv:`${kind}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function summarizeRunResultStatuses(results){let passed=0,failed=0,skipped=0;for(const entry of results){if(entry.status==="passed"){passed+=1;continue}if(entry.status==="failed"||entry.status==="refused"){failed+=1;continue}skipped+=1}return{passed,failed,skipped}}function summarizeContextPreflight(runResults){let checkedPmCommands=0,trackerReadCommands=0,mismatches=0,autoRemediated=0;for(const result of runResults){const context=result.execution_context;!context||context.is_pm_command!==!0||(checkedPmCommands+=1,context.is_pm_tracker_read_command===!0&&(trackerReadCommands+=1),context.mismatch_detected===!0&&(mismatches+=1),context.auto_pm_context_applied===!0&&(autoRemediated+=1))}return{checked_pm_commands:checkedPmCommands,tracker_read_commands:trackerReadCommands,mismatches,auto_remediated:autoRemediated}}function ensureScope(raw){const value=raw??"project";if(!SCOPE_VALUES.includes(value))throw new PmCliError(`Invalid scope "${raw}"`,EXIT_CODE.USAGE);return value}function parsePmContextMode(raw){if(!raw)return"schema";const normalized=raw.trim().toLowerCase();if(PM_CONTEXT_MODE_VALUES.includes(normalized))return normalized;throw new PmCliError(`Invalid --pm-context value "${raw}". Expected one of: ${PM_CONTEXT_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseWorkspaceContextMode(raw){return parseLinkedTestWorkspaceContextMode(raw??"source","--workspace-context")}function resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelMode,overrideLinkedMode){return overrideLinkedMode?runLevelMode:parseLinkedTestWorkspaceContextMode(linkedTest.workspace_context_mode,"linked test")??runLevelMode}function resolveLinkedTestRequestedContextMode(linkedTest,runLevelMode,overrideLinkedPmContext){return overrideLinkedPmContext||typeof linkedTest.pm_context_mode!="string"||linkedTest.pm_context_mode.trim().length===0?runLevelMode:parsePmContextMode(linkedTest.pm_context_mode)}function resolveLinkedTestEffectiveContextMode(requestedMode,isPmTrackerReadCommand){return requestedMode==="auto"?isPmTrackerReadCommand?"tracker":"schema":requestedMode}function hasLinkedTestAssertions(linkedTest){return Object.entries(linkedTest).filter(([key])=>key.startsWith("assert_")).some(([,value])=>value==null?!1:Array.isArray(value)?value.length>0:typeof value=="object"?Object.keys(value).length>0:typeof value=="string"?value.trim().length>0:!0)}function buildPmContextMismatchHint(params){const{executionContext,runLevelPmContextMode,linkedOverridePmContextMode}=params;return!executionContext.is_pm_tracker_read_command||!executionContext.mismatch_detected?"":runLevelPmContextMode==="tracker"&&linkedOverridePmContextMode==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":executionContext.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function mergeEnvSetDirectives(entries,optionName){const merged={};if(!entries)return merged;for(const entry of entries){const parsed=parseLinkedTestEnvSetValue(entry,optionName);if(parsed)for(const[key,value]of Object.entries(parsed))merged[key]=value}return merged}function mergeEnvClearDirectives(entries,optionName){if(!entries)return[];const values=[];for(const entry of entries){const parsed=parseLinkedTestEnvClearValue(entry,optionName);parsed&&values.push(...parsed)}return[...new Set(values)]}import{BUN_GLOBAL_FLAGS_WITH_VALUE,NPM_GLOBAL_FLAGS_WITH_VALUE,PNPM_GLOBAL_FLAGS_WITH_VALUE,SCRIPT_RUN_FLAGS_WITH_VALUE,SCRIPT_RUN_SUBCOMMANDS,YARN_GLOBAL_FLAGS_WITH_VALUE,extractPmInvocationArgsFromSegment,parseLauncherSubcommand,parseNpmExecCommand,parseNpxCommand,parsePnpmDlxCommand,resolvePmSubcommandContext,splitNormalizedCommandSegments,stripLeadingEnvAssignments,SHELL_COMMAND_FLAG_PATTERNS,assertNoRecursiveTestAllCommand,invokesRecursiveTestAllCommand,normalizeCommandForValidation,segmentInvokesRecursiveTestAll}from"./linked-command-detection.js";import{extractReferencedPmItemIdsFromCommand}from"./linked-command-detection.js";function commandInvokesPmCli(command){const normalizedCommand=normalizeCommandForValidation(command);return splitNormalizedCommandSegments(normalizedCommand).some(segment=>extractPmInvocationArgsFromSegment(segment)!==null)}function commandInvokesPmTrackerReadCommand(command){const normalizedCommand=normalizeCommandForValidation(command);return splitNormalizedCommandSegments(normalizedCommand).some(segment=>{const invocationArgs=extractPmInvocationArgsFromSegment(segment);if(!invocationArgs)return!1;const context=resolvePmSubcommandContext(invocationArgs);return context?PM_TRACKER_READ_SUBCOMMANDS.has(context.subcommand):!1})}function resolveDirectRunnerSubcommand(parsed){if(parsed)return SCRIPT_RUN_SUBCOMMANDS.has(parsed.subcommand)?parseLauncherSubcommand(parsed.args,SCRIPT_RUN_FLAGS_WITH_VALUE)?.subcommand:parsed.subcommand}function firstDirectTestRunnerSubcommand(executable,args){if(executable==="npx"||executable==="bunx")return parseNpxCommand(args)?.command;if(executable==="pnpm")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,PNPM_GLOBAL_FLAGS_WITH_VALUE));if(executable==="npm")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,NPM_GLOBAL_FLAGS_WITH_VALUE));if(executable==="yarn")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,YARN_GLOBAL_FLAGS_WITH_VALUE));if(executable==="bun")return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args,BUN_GLOBAL_FLAGS_WITH_VALUE))}function isDirectTestRunnerSubcommand(token){return token?token==="vitest"||token==="test"||token.startsWith("test:"):!1}function commandUsesSandboxRunner(normalizedCommand){return normalizedCommand.includes("node scripts/run-tests.mjs ")||normalizedCommand.endsWith("node scripts/run-tests.mjs")||normalizedCommand.includes("node ./scripts/run-tests.mjs ")||normalizedCommand.endsWith("node ./scripts/run-tests.mjs")}function segmentInvokesDirectTestRunner(normalizedSegment){const rawTokens=normalizedSegment.split(" ").filter(token=>token.length>0),tokens=stripLeadingEnvAssignments(rawTokens);if(tokens.length===0)return!1;const[executable,...args]=tokens,shellCommandFlagPattern=SHELL_COMMAND_FLAG_PATTERNS.get(executable);if(shellCommandFlagPattern){const commandFlagIndex=args.findIndex(argument=>shellCommandFlagPattern.test(argument));return commandFlagIndex>=0&&segmentInvokesDirectTestRunner(args.slice(commandFlagIndex+1).join(" "))}return executable==="vitest"||executable.endsWith("/vitest")||executable.endsWith("/vitest.mjs")?!0:executable==="node"?nodeArgsInvokeDirectTestRunner(args):packageManagerInvokesDirectTestRunner(executable,args)}function nodeArgsInvokeDirectTestRunner(args){return args.includes("--test")||args.some(arg=>arg==="vitest"||arg==="vitest.mjs"||arg.endsWith("/vitest")||arg.endsWith("/vitest.mjs"))}function packageManagerInvokesDirectTestRunner(executable,args){return executable==="npx"||executable==="bunx"?isDirectTestRunnerSubcommand(parseNpxCommand(args)?.command):executable==="pnpm"||executable==="npm"?isDirectTestRunnerSubcommand((executable==="pnpm"?parsePnpmDlxCommand(args):parseNpmExecCommand(args))?.command)||isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args)):(executable==="yarn"||executable==="bun")&&isDirectTestRunnerSubcommand(firstDirectTestRunnerSubcommand(executable,args))}function classifyLinkedTestCommandSafety(command){const normalized=normalizeCommandForValidation(command),segments=splitNormalizedCommandSegments(normalized),directRunner=segments.some(segment=>!commandUsesSandboxRunner(segment)&&segmentInvokesDirectTestRunner(segment)),sandboxRunner=segments.some(commandUsesSandboxRunner);return{accepted:!0,command_kind:directRunner?"direct_runner":sandboxRunner?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:directRunner?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function getRuntimeSafetySkipReason(command){if(invokesRecursiveTestAllCommand(command))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function parseAddEntries(raw){return raw?raw.map(parseAddEntry):[]}function parseAddEntry(entry){const trimmed=entry.trim(),kv=looksLikeStructuredLinkedTestEntry(trimmed)?normalizeStructuredLinkedTestEntry(parseCsvKv(entry,"--add"),"--add"):{command:trimmed},command=trimLinkedTestEntryField(kv.command);if(!command)throw new PmCliError("--add requires command=<value> or a bare command (path=<value> is optional metadata)",EXIT_CODE.USAGE);return assertNoRecursiveTestAllCommand(command),{command,path:trimLinkedTestEntryField(kv.path),scope:ensureScope(kv.scope),timeout_seconds:parseLinkedTestTimeoutSeconds(trimLinkedTestEntryField(kv.timeout_seconds),trimLinkedTestEntryField(kv.timeout)),pm_context_mode:parseLinkedTestContextModeValue(trimLinkedTestEntryField(kv.pm_context_mode),"--add"),workspace_context_mode:parseLinkedTestWorkspaceContextMode(trimLinkedTestEntryField(kv.workspace_context_mode),"--add"),env_set:parseLinkedTestEnvSetValue(trimLinkedTestEntryField(kv.env_set),"--add"),env_clear:parseLinkedTestEnvClearValue(trimLinkedTestEntryField(kv.env_clear),"--add"),shared_host_safe:parseLinkedTestBooleanValue(trimLinkedTestEntryField(kv.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:parseLinkedTestStringList(trimLinkedTestEntryField(kv.assert_stdout_contains)),assert_stdout_regex:parseLinkedTestRegexList(trimLinkedTestEntryField(kv.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:parseLinkedTestStringList(trimLinkedTestEntryField(kv.assert_stderr_contains)),assert_stderr_regex:parseLinkedTestRegexList(trimLinkedTestEntryField(kv.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:parseLinkedTestMinLines(trimLinkedTestEntryField(kv.assert_stdout_min_lines),"--add"),assert_json_field_equals:parseLinkedTestAssertionEqualsMap(trimLinkedTestEntryField(kv.assert_json_field_equals),"--add"),assert_json_field_gte:parseLinkedTestAssertionGteMap(trimLinkedTestEntryField(kv.assert_json_field_gte),"--add"),note:trimLinkedTestEntryField(kv.note),phase:parseLinkedTestPhase(kv.phase,"--add")}}function trimLinkedTestEntryField(value){const trimmed=value?.trim();return trimmed&&trimmed.length>0?trimmed:void 0}function parseLinkedTestTimeoutSeconds(timeoutSecondsRaw,timeoutAliasRaw){if(timeoutSecondsRaw&&timeoutAliasRaw&&timeoutSecondsRaw!==timeoutAliasRaw)throw new PmCliError("--add timeout and timeout_seconds must match when both are provided",EXIT_CODE.USAGE);const timeoutRaw=timeoutSecondsRaw??timeoutAliasRaw;if(timeoutRaw===void 0)return;const timeout=Math.floor(parseOptionalNumber(timeoutRaw,"timeout_seconds"));if(timeout<=0)throw new PmCliError("--add timeout_seconds must be a positive integer",EXIT_CODE.USAGE);return timeout}function parseAddJsonEntries(raw){return raw?raw.flatMap(entry=>{const parsed=parseLinkedTestJsonEntries(entry,"--add-json");for(const linkedTest of parsed){const command=linkedTest.command;if(!command)throw new PmCliError("--add-json requires a non-empty command string",EXIT_CODE.USAGE);assertNoRecursiveTestAllCommand(command)}return parsed}):[]}function parseRemoveEntries(raw){return raw?raw.map(entry=>{const trimmed=entry.trim();if(!trimmed)throw new PmCliError("--remove requires command or path value",EXIT_CODE.USAGE);const identityPrefix=/^(command|path)\s*=/i.exec(trimmed);if(identityPrefix){const value=trimmed.slice(identityPrefix[0].length).trim();if(!value)throw new PmCliError("--remove requires a non-empty command=<value> or path=<value>",EXIT_CODE.USAGE);return{kind:identityPrefix[1].toLowerCase(),value}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(trimmed))throw new PmCliError("--remove structured selectors require command=<value> or path=<value>",EXIT_CODE.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(trimmed)||trimmed.startsWith("```")){const kv=parseCsvKv(trimmed,"--remove"),kind=kv.path!==void 0?"path":"command",value=kv.path??kv.command;if(!value?.trim())throw new PmCliError("--remove requires command=<value> and/or path=<value>",EXIT_CODE.USAGE);return{kind,value:value.trim()}}return{kind:"either",value:trimmed}}):[]}function parseRemoveIndexes(raw){return raw?[...new Set(raw.map(value=>{const parsed=typeof value=="number"?value:Number.parseInt(value,10);if(!Number.isInteger(parsed)||parsed<1||String(parsed)!==String(value).trim())throw new PmCliError("--remove-index must be a positive integer",EXIT_CODE.USAGE);return parsed}))]:[]}function closeLinkedTestStdin(child){try{child.stdin?.end()}catch{}}function summarizeLinkedTestCommand(command){const normalized=command.trim().replaceAll(/\s+/g," ");return normalized.length<=MAX_LINKED_TEST_COMMAND_LABEL_LENGTH?normalized:`${normalized.slice(0,MAX_LINKED_TEST_COMMAND_LABEL_LENGTH-3)}...`}function shouldEmitLinkedTestProgress(mode){return mode==="off"?!1:mode==="always"?!0:process.stderr.isTTY===!0}function emitLinkedTestProgress(message){try{process.stderr.write(`${message}
2
- `)}catch{}}function beginLinkedTestProgress(context,mode){if(!shouldEmitLinkedTestProgress(mode))return null;const commandLabel=summarizeLinkedTestCommand(context.command),startAt=Date.now();emitLinkedTestProgress(`[pm test] linked-test ${context.index}/${context.total} start timeout_ms=${context.timeoutMs} command="${commandLabel}"`);const heartbeat=setInterval(()=>{const elapsedMs=Date.now()-startAt;emitLinkedTestProgress(`[pm test] linked-test ${context.index}/${context.total} running elapsed_ms=${elapsedMs} command="${commandLabel}"`)},linkedTestHeartbeatIntervalMs());return heartbeat.unref?.(),heartbeat}function endLinkedTestProgress(context,executionResult,startedAt,mode){if(!shouldEmitLinkedTestProgress(mode))return;const commandLabel=summarizeLinkedTestCommand(context.command),elapsedMs=Date.now()-startedAt,statusLabel=executionResult.timedOut||executionResult.maxBufferExceeded||executionResult.exitCode!==0?"failed":"passed",reasonTokens=[];executionResult.timedOut&&reasonTokens.push("reason=timeout"),executionResult.maxBufferExceeded&&reasonTokens.push("reason=max_buffer"),executionResult.outputTruncated&&reasonTokens.push("output=truncated"),executionResult.signal&&reasonTokens.push(`signal=${executionResult.signal}`);const exitLabel=executionResult.exitCode===null?"null":String(executionResult.exitCode),reasonSuffix=reasonTokens.length>0?` ${reasonTokens.join(" ")}`:"";emitLinkedTestProgress(`[pm test] linked-test ${context.index}/${context.total} end status=${statusLabel} exit_code=${exitLabel} elapsed_ms=${elapsedMs}${reasonSuffix} command="${commandLabel}"`)}function clearLinkedTestTimers(timers){timers.heartbeat&&clearInterval(timers.heartbeat),timers.timedOutTimer&&(clearTimeout(timers.timedOutTimer),timers.timedOutTimer=null),timers.forceKillTimer&&(clearTimeout(timers.forceKillTimer),timers.forceKillTimer=null)}function createLinkedTestTerminationRequester(child,timers){let terminationRequested=!1;return async()=>{if(terminationRequested)return;terminationRequested=!0;const pid=child.pid,childRoot={alive:()=>child.exitCode===null&&child.signalCode===null,kill:()=>{child.exitCode===null&&child.signalCode===null&&child.kill("SIGKILL")}};if(!pid||pid<=0){try{child.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await killProcessTree(pid,childRoot,LINKED_TEST_TREE_KILL);return}try{process.kill(-pid,"SIGTERM")}catch{try{child.kill("SIGTERM")}catch{}}timers.forceKillTimer=setTimeout(()=>{killProcessTree(pid,childRoot,LINKED_TEST_TREE_KILL)},linkedTestTimeoutForceKillDelayMs()),timers.forceKillTimer.unref?.()}}function waitForLinkedTestChildClose(child){return new Promise(resolve=>{let settled=!1,pipeCloseGraceTimer=null;const settle=(value,destroyPipes=!1)=>{settled||(settled=!0,pipeCloseGraceTimer&&(clearTimeout(pipeCloseGraceTimer),pipeCloseGraceTimer=null),destroyPipes&&(child.stdin?.destroy(),child.stdout?.destroy(),child.stderr?.destroy()),resolve(value))};child.on("exit",(exitCode,exitSignal)=>{settled||(pipeCloseGraceTimer=setTimeout(()=>{settle({code:exitCode,signal:exitSignal},!0)},linkedTestPipeCloseGraceMs()),pipeCloseGraceTimer.unref?.())}),child.on("close",(closeCode,closeSignal)=>{settle({code:closeCode,signal:closeSignal})})})}function createLinkedTestChild(command,env,stdoutFd,stderrFd,cwd){return spawn(command,{cwd,env,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",stdoutFd,stderrFd]})}async function readLinkedTestCapture(capturePath){const handle=await open(capturePath,"r");try{const size=(await handle.stat()).size,retainedBytes=Math.min(size,TEST_OUTPUT_MAX_BUFFER_BYTES),buffer=Buffer.alloc(retainedBytes);return retainedBytes>0&&await handle.read(buffer,0,retainedBytes,0),{text:buffer.toString("utf8"),truncated:size>TEST_OUTPUT_MAX_BUFFER_BYTES}}finally{await handle.close()}}async function runLinkedTestCommand(command,timeoutMs,env,progressContext,progressMode,cwd=process.cwd()){const startedAt=Date.now(),captureRoot=await mkdtemp(path.join(tmpdir(),"pm-linked-test-output-"));try{const stdoutPath=path.join(captureRoot,"stdout.log"),stderrPath=path.join(captureRoot,"stderr.log"),[stdoutHandle,stderrHandle]=await Promise.all([open(stdoutPath,"w"),open(stderrPath,"w")]);let child;try{child=createLinkedTestChild(command,env,stdoutHandle.fd,stderrHandle.fd,cwd)}catch(error){throw await Promise.all([stdoutHandle.close(),stderrHandle.close()]),error}const childClose=waitForLinkedTestChildClose(child);let spawnError;child.on("error",error=>{spawnError=error.message}),await Promise.all([stdoutHandle.close(),stderrHandle.close()]),closeLinkedTestStdin(child);const timers={heartbeat:beginLinkedTestProgress(progressContext,progressMode),forceKillTimer:null,timedOutTimer:null},requestTermination=createLinkedTestTerminationRequester(child,timers);let timedOut=!1;timers.timedOutTimer=setTimeout(()=>{timedOut=!0,requestTermination()},timeoutMs),timers.timedOutTimer.unref?.();const{code,signal}=await childClose;clearLinkedTestTimers(timers);const[stdout,stderr]=await Promise.all([readLinkedTestCapture(stdoutPath),readLinkedTestCapture(stderrPath)]),outputTruncated=stdout.truncated||stderr.truncated,truncationNotice=outputTruncated?`
3
- [pm linked-test output truncated at ${TEST_OUTPUT_MAX_BUFFER_BYTES} bytes per stream; the child process continued to completion]
4
- `:"";!spawnError&&await detectLinkedTestCommandNotFound(command,{exitCode:code,stderr:stderr.text},env,cwd)&&(spawnError="Linked test executable was not found. Install the tool or update the linked command before retrying.");const executionResult={stdout:`${stdout.text}${truncationNotice}`,stderr:stderr.text,exitCode:code,signal,timedOut,maxBufferExceeded:!1,outputTruncated,spawnError};return endLinkedTestProgress(progressContext,executionResult,startedAt,progressMode),executionResult}finally{await rm(captureRoot,{recursive:!0,force:!0})}}function formatLinkedTestExecutionError(result,timeoutMs){const details=[];result.maxBufferExceeded&&details.push(`Linked test output exceeded maxBuffer=${TEST_OUTPUT_MAX_BUFFER_BYTES} bytes. Reduce output volume or split the command.`),result.timedOut&&timeoutMs>0&&details.push(`Linked test timed out after ${timeoutMs}ms.`);const signalMessage=result.signal?`Linked test command terminated by signal ${result.signal}.`:void 0,baseMessage=result.spawnError?.trim()||signalMessage||"Linked test command failed.";return details.length===0?baseMessage:`${baseMessage} ${details.join(" ")}`}function hasInfraCollisionSignal(result){const combined=[result.spawnError??"",result.stderr,result.stdout].join(`
5
- `);return LINKED_TEST_INFRA_COLLISION_PATTERNS.some(pattern=>pattern.test(combined))||combined.split(/\r?\n/u).some(line=>LINKED_TEST_LOCK_ACQUISITION_PATTERN.test(line)&&LINKED_TEST_LOCK_CONTENTION_CONTEXT_PATTERN.test(line))}function classifyLinkedTestFailure(result){return hasInfraCollisionSignal(result)?"infra_collision":result.timedOut?"timeout":result.maxBufferExceeded?"max_buffer":result.spawnError?"spawn_error":result.signal?"signal":"assertion_failure"}function applyEnvDirectiveStage(env,directives){for(const[key,value]of Object.entries(directives.env_set))LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())||(env[key]=value);for(const key of directives.env_clear)LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())||delete env[key]}function applySharedHostSafeDefaults(env){env.PORT===void 0&&(env.PORT="0"),env.HOST===void 0&&(env.HOST="127.0.0.1"),env.PM_SHARED_HOST_SAFE===void 0&&(env.PM_SHARED_HOST_SAFE="1"),env.PLAYWRIGHT_HTML_OPEN===void 0&&(env.PLAYWRIGHT_HTML_OPEN="never"),env.PW_TEST_HTML_REPORT_OPEN===void 0&&(env.PW_TEST_HTML_REPORT_OPEN="never")}function resolveEffectiveLinkedTestDirectives(runtimeDirectives,linkedTest){const envSet={...runtimeDirectives.env_set,...linkedTest.env_set},envClear=[...new Set([...runtimeDirectives.env_clear,...linkedTest.env_clear??[]])],sharedHostSafe=linkedTest.shared_host_safe??runtimeDirectives.shared_host_safe;return{env_set:envSet,env_clear:envClear,shared_host_safe:sharedHostSafe}}function resolveRuntimeDirectives(envSetEntries,envClearEntries,sharedHostSafe){return{env_set:mergeEnvSetDirectives(envSetEntries,"--env-set"),env_clear:mergeEnvClearDirectives(envClearEntries,"--env-clear"),shared_host_safe:sharedHostSafe===!0}}async function copyIntoSandboxIfPresent(sourcePath,targetPath,recursive=!1,makeDirectory=mkdir){if(await pathExists(sourcePath))try{await withHostEnvironmentBoundary("seed_linked_test",async()=>{if(await makeDirectory(path.dirname(targetPath),{recursive:!0}),recursive){await cp(sourcePath,targetPath,{recursive:!0,force:!0});return}await cp(sourcePath,targetPath,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(error){if(typeof error=="object"&&error!==null&&"code"in error&&isFileMissingError(error))return;throw error}}async function seedLinkedTestSandbox(sandboxPmPath,sandboxGlobalPath,sourceRoots,auditSettings=!1){for(const[sourceRoot,sandboxRoot]of[[sourceRoots.projectPmRoot,sandboxPmPath],[sourceRoots.globalPmRoot,sandboxGlobalPath]])if(auditSettings){const raw=await readFileIfExists(getSettingsPath(sourceRoot));if(raw!==null){const settings=await readSettings(sandboxRoot);await writeWorkspaceJsonWithHistory({pmRoot:sandboxRoot,filePath:getSettingsPath(sandboxRoot),raw,op:"settings:write",author:resolveAuthor(void 0,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await copyIntoSandboxIfPresent(getSettingsPath(sourceRoot),getSettingsPath(sandboxRoot));await copyIntoSandboxIfPresent(path.join(sourceRoots.projectPmRoot,"extensions"),path.join(sandboxPmPath,"extensions"),!0),await copyIntoSandboxIfPresent(path.join(sourceRoots.globalPmRoot,"extensions"),path.join(sandboxGlobalPath,"extensions"),!0)}async function seedLinkedTestTrackerData(sourceRoot,sandboxRoot){if(!await pathExists(sourceRoot))return;const entries=await readdir(sourceRoot,{withFileTypes:!0});for(const entry of entries){if(LINKED_TEST_TRACKER_DIRS_TO_SKIP.has(entry.name))continue;const sourcePath=path.join(sourceRoot,entry.name),targetPath=path.join(sandboxRoot,entry.name);if(entry.isDirectory()){await copyIntoSandboxIfPresent(sourcePath,targetPath,!0);continue}entry.isFile()&&await copyIntoSandboxIfPresent(sourcePath,targetPath)}}async function seedMissingLinkedTestSettingsHistory(sourceRoot,sandboxRoot){const sourceSettingsRaw=await readFileIfExists(getSettingsPath(sourceRoot));if(sourceSettingsRaw===null||await pathExists(getWorkspaceHistoryPath(sourceRoot)))return;const sandboxSettings=await readSettings(sandboxRoot);await rm(getWorkspaceHistoryPath(sandboxRoot),{force:!0}),await rm(getSettingsPath(sandboxRoot),{force:!0}),await writeWorkspaceJsonWithHistory({pmRoot:sandboxRoot,filePath:getSettingsPath(sandboxRoot),raw:sourceSettingsRaw,op:"settings:write",author:resolveAuthor(void 0,sandboxSettings.author_default),lockTtlSeconds:sandboxSettings.locks.ttl_seconds,lockWaitMs:sandboxSettings.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function countLinkedTestItemFiles(pmRoot){if(!await pathExists(pmRoot))return 0;let total=0;const entries=await readdir(pmRoot,{withFileTypes:!0});for(const entry of entries){if(!entry.isDirectory()||LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP.has(entry.name))continue;const folderPath=path.join(pmRoot,entry.name);let files;try{files=await readdir(folderPath,{withFileTypes:!0})}catch{continue}for(const file of files)file.isFile()&&ITEM_FILE_EXTENSIONS.some(extension=>file.name.toLowerCase().endsWith(extension))&&(total+=1)}return total}function resolveLinkedTestFailureExitCode(execution){const rawExitCode=typeof execution.exitCode=="number"?execution.exitCode:1;return(execution.timedOut||execution.maxBufferExceeded)&&rawExitCode===0?1:rawExitCode}function parseAssertionLiteral(raw){const trimmed=raw.trim();if(trimmed==="true")return!0;if(trimmed==="false")return!1;if(trimmed==="null")return null;const numeric=Number(trimmed);if(trimmed.length>0&&Number.isFinite(numeric))return numeric;if(trimmed.startsWith("{")&&trimmed.endsWith("}")||trimmed.startsWith("[")&&trimmed.endsWith("]"))try{return JSON.parse(trimmed)}catch{}return trimmed}function compareAssertionValues(actual,expected){return typeof actual=="object"&&actual!==null&&typeof expected=="object"&&expected!==null?stableValueEquals(actual,expected):Object.is(actual,expected)}function evaluateLinkedTestAssertions(linkedTest,stdout,stderr){const failures=[];failures.push(...evaluateContainsAssertions("stdout",stdout,linkedTest.assert_stdout_contains)),failures.push(...evaluateRegexAssertions("stdout",stdout,linkedTest.assert_stdout_regex)),failures.push(...evaluateContainsAssertions("stderr",stderr,linkedTest.assert_stderr_contains)),failures.push(...evaluateRegexAssertions("stderr",stderr,linkedTest.assert_stderr_regex)),failures.push(...evaluateStdoutLineCountAssertion(stdout,linkedTest.assert_stdout_min_lines));const jsonEqualsAssertions=linkedTest.assert_json_field_equals??{},jsonGteAssertions=linkedTest.assert_json_field_gte??{};if(!(Object.keys(jsonEqualsAssertions).length>0||Object.keys(jsonGteAssertions).length>0))return failures;let parsedJson;try{parsedJson=JSON.parse(stdout)}catch(error){return failures.push(`stdout is not valid JSON for assert_json_field_* checks: ${error instanceof Error?error.message:String(error)}`),failures}for(const[fieldPath,expectedRaw]of Object.entries(jsonEqualsAssertions)){const resolved=readJsonPathValue(parsedJson,fieldPath);if(!resolved.found){failures.push(`assert_json_field_equals missing path "${fieldPath}"`);continue}const expected=parseAssertionLiteral(expectedRaw);compareAssertionValues(resolved.value,expected)||failures.push(`assert_json_field_equals mismatch at "${fieldPath}" (expected=${JSON.stringify(expected)} actual=${JSON.stringify(resolved.value)})`)}for(const[fieldPath,expectedMinimum]of Object.entries(jsonGteAssertions)){const resolved=readJsonPathValue(parsedJson,fieldPath);if(!resolved.found){failures.push(`assert_json_field_gte missing path "${fieldPath}"`);continue}if(typeof resolved.value!="number"||!Number.isFinite(resolved.value)){failures.push(`assert_json_field_gte path "${fieldPath}" resolved to non-numeric value`);continue}resolved.value<expectedMinimum&&failures.push(`assert_json_field_gte failed at "${fieldPath}" (expected >= ${expectedMinimum}, actual ${resolved.value})`)}return failures}function evaluateContainsAssertions(streamName,output,expectedValues){const failures=[];for(const expected of expectedValues??[])output.includes(expected)||failures.push(`${streamName} missing required text: "${expected}"`);return failures}function evaluateRegexAssertions(streamName,output,patterns){const failures=[];for(const pattern of patterns??[])try{new RegExp(pattern,"m").test(output)||failures.push(`${streamName} failed regex assertion: /${pattern}/m`)}catch(error){failures.push(`${streamName} regex assertion is invalid: /${pattern}/ (${error instanceof Error?error.message:String(error)})`)}return failures}function evaluateStdoutLineCountAssertion(stdout,minimum){if(typeof minimum!="number")return[];const lineCount=stdout.split(/\r?\n/).map(line=>line.trim()).filter(line=>line.length>0).length;return lineCount<minimum?[`stdout line count ${lineCount} is below required minimum ${minimum}`]:[]}function commandUsesTestNameFilter(command){const normalized=normalizeCommandForValidation(command);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(normalized)?!0:splitNormalizedCommandSegments(normalized).some(segment=>/(?:^|\s)-t(?:=|\s)/u.test(segment)&&segmentInvokesDirectTestRunner(segment))}function createLinkedTestSandboxLayout(sandboxRoot){return{root:sandboxRoot,schemaProjectPmPath:path.join(sandboxRoot,"schema","project",".agents","pm"),schemaGlobalPmPath:path.join(sandboxRoot,"schema","global"),trackerProjectPmPath:path.join(sandboxRoot,"tracker","project",".agents","pm"),trackerGlobalPmPath:path.join(sandboxRoot,"tracker","global"),workspaceSnapshotRoot:path.join(sandboxRoot,"workspace","project"),workspaceIsolatedRoot:path.join(sandboxRoot,"workspace","isolated")}}function linkedTestsRequireWorkspaceSnapshot(tests,runLevelMode,overrideLinkedMode){return tests.some(linkedTest=>resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelMode,overrideLinkedMode)==="snapshot")}async function bindSnapshotTracker(snapshotRoot,sandboxPmPath){const agentsRoot=path.join(snapshotRoot,".agents"),target=path.join(agentsRoot,"pm");await mkdir(agentsRoot,{recursive:!0}),await rm(target,{recursive:!0,force:!0}),await symlink(sandboxPmPath,target,process.platform==="win32"?"junction":"dir")}async function initializeLinkedTestSandboxes(layout,initialize=runInit,includeTrackerData=!0){const initOptions={defaults:!0,agentGuidance:"skip"};await initialize(void 0,{path:layout.schemaProjectPmPath},initOptions),await initialize(void 0,{path:layout.schemaGlobalPmPath},initOptions),includeTrackerData&&(await initialize(void 0,{path:layout.trackerProjectPmPath},initOptions),await initialize(void 0,{path:layout.trackerGlobalPmPath},initOptions))}async function seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData){sourceRoots&&(await seedLinkedTestSandbox(layout.schemaProjectPmPath,layout.schemaGlobalPmPath,sourceRoots,!0),includeTrackerData&&(await seedLinkedTestSandbox(layout.trackerProjectPmPath,layout.trackerGlobalPmPath,sourceRoots),await seedLinkedTestTrackerData(sourceRoots.projectPmRoot,layout.trackerProjectPmPath),await seedLinkedTestTrackerData(sourceRoots.globalPmRoot,layout.trackerGlobalPmPath),await seedMissingLinkedTestSettingsHistory(sourceRoots.projectPmRoot,layout.trackerProjectPmPath),await seedMissingLinkedTestSettingsHistory(sourceRoots.globalPmRoot,layout.trackerGlobalPmPath)))}function linkedTestsRequireTrackerData(tests,runLevelPmContextMode,options){return tests.some(linkedTest=>{const command=linkedTest.command??"",isPmTrackerReadCommand=command.length>0&&commandInvokesPmTrackerReadCommand(command),requestedPmContextMode=options?.autoPmContext===!0&&isPmTrackerReadCommand?"auto":resolveLinkedTestRequestedContextMode(linkedTest,runLevelPmContextMode,options?.overrideLinkedPmContext===!0);return resolveLinkedTestEffectiveContextMode(requestedPmContextMode,isPmTrackerReadCommand)==="tracker"})}async function countLinkedTestSandboxItems(layout,sourceRoots){return{sourceProjectItemCount:sourceRoots?await countLinkedTestItemFiles(sourceRoots.projectPmRoot):0,sourceGlobalItemCount:sourceRoots?await countLinkedTestItemFiles(sourceRoots.globalPmRoot):0,schemaProjectItemCount:await countLinkedTestItemFiles(layout.schemaProjectPmPath),schemaGlobalItemCount:await countLinkedTestItemFiles(layout.schemaGlobalPmPath),trackerProjectItemCount:await countLinkedTestItemFiles(layout.trackerProjectPmPath),trackerGlobalItemCount:await countLinkedTestItemFiles(layout.trackerGlobalPmPath)}}function buildLinkedTestExecutionContext(params){const trackerMode=params.effectivePmContextMode==="tracker",selectedSandboxProjectPmPath=trackerMode?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath,selectedSandboxGlobalPmPath=trackerMode?params.layout.trackerGlobalPmPath:params.layout.schemaGlobalPmPath,selectedSandboxProjectItemCount=trackerMode?params.counts.trackerProjectItemCount:params.counts.schemaProjectItemCount,selectedSandboxGlobalItemCount=trackerMode?params.counts.trackerGlobalItemCount:params.counts.schemaGlobalItemCount,workingDirectory=params.workspaceContextMode==="snapshot"?params.layout.workspaceSnapshotRoot:params.workspaceContextMode==="isolated"?params.layout.workspaceIsolatedRoot:params.sourceWorkspaceRoot,exposedSourceWorkspaceRoot=params.workspaceContextMode==="isolated"?"":workingDirectory;return{requested_pm_context_mode:params.requestedPmContextMode,pm_context_mode:params.effectivePmContextMode,auto_pm_context_applied:params.autoPmContextApplied,is_pm_command:params.isPmCommand,is_pm_tracker_read_command:params.isPmTrackerReadCommand,source_project_pm_path:params.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:selectedSandboxProjectPmPath,source_global_pm_path:params.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:selectedSandboxGlobalPmPath,source_project_item_count:params.counts.sourceProjectItemCount,sandbox_project_item_count:selectedSandboxProjectItemCount,source_global_item_count:params.counts.sourceGlobalItemCount,sandbox_global_item_count:selectedSandboxGlobalItemCount,mismatch_detected:params.isPmCommand&&(params.counts.sourceProjectItemCount!==selectedSandboxProjectItemCount||params.counts.sourceGlobalItemCount!==selectedSandboxGlobalItemCount),project_extensions_seeded:!!params.sourceRoots,global_extensions_seeded:!!params.sourceRoots,requested_workspace_context_mode:params.requestedWorkspaceContextMode,workspace_context_mode:params.workspaceContextMode,working_directory:workingDirectory,source_workspace_root:exposedSourceWorkspaceRoot,trust:params.trust}}async function resolveLinkedTestCommandContext(params){const linkedOverridePmContextMode=typeof params.linkedTest.pm_context_mode=="string"&&params.linkedTest.pm_context_mode.trim().length>0?parsePmContextMode(params.linkedTest.pm_context_mode):void 0,command=typeof params.linkedTest.command=="string"&&params.linkedTest.command.length>0?params.linkedTest.command:void 0,isPmCommand=command?commandInvokesPmCli(command):!1,isPmTrackerReadCommand=isPmCommand&&command?commandInvokesPmTrackerReadCommand(command):!1,autoPmContextApplied=params.options?.autoPmContext===!0&&isPmTrackerReadCommand,requestedPmContextMode=autoPmContextApplied?"auto":resolveLinkedTestRequestedContextMode(params.linkedTest,params.runLevelPmContextMode,params.options?.overrideLinkedPmContext===!0),effectivePmContextMode=resolveLinkedTestEffectiveContextMode(requestedPmContextMode,isPmTrackerReadCommand),selectedSandboxProjectPmPath=effectivePmContextMode==="tracker"?params.layout.trackerProjectPmPath:params.layout.schemaProjectPmPath;params.workspaceContextMode==="snapshot"&&await bindSnapshotTracker(params.layout.workspaceSnapshotRoot,selectedSandboxProjectPmPath);const trust=params.options?.pmRoot?await resolveLinkedTestTrust(params.options.pmRoot,params.linkedTest,params.currentSourceRef):await resolveLinkedTestTrust(params.layout.root,params.linkedTest,params.currentSourceRef);return{linkedOverridePmContextMode,executionContext:buildLinkedTestExecutionContext({layout:params.layout,counts:params.counts,sourceRoots:params.sourceRoots,isPmCommand,isPmTrackerReadCommand,requestedPmContextMode,effectivePmContextMode,autoPmContextApplied,requestedWorkspaceContextMode:params.requestedWorkspaceContextMode,workspaceContextMode:params.workspaceContextMode,sourceWorkspaceRoot:params.sourceWorkspaceRoot,trust})}}function buildLinkedTestSkippedResult(linkedTest,executionContext,error){return{command:linkedTest.command,path:linkedTest.path,status:"skipped",execution_context:executionContext,error}}function buildLinkedTestAssertionFailureResult(linkedTest,executionContext,error,output){return{command:linkedTest.command,path:linkedTest.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:executionContext,...output?{stdout:output.stdout,stderr:output.stderr}:{},error}}function buildLinkedTestTrustRefusalResult(linkedTest,executionContext,error){return{command:linkedTest.command,path:linkedTest.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:executionContext,error}}function resolveLinkedTestTrustPreflightResult(params){if(params.executionContext.trust.trusted)return null;const overrideRequested=params.options?.allowUntrustedLinkedTests===!0,policyEnabled=params.options?.untrustedLinkedTestsPolicyEnabled===!0;if(overrideRequested&&policyEnabled)return null;const recovery=policyEnabled?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return buildLinkedTestTrustRefusalResult(params.linkedTest,params.executionContext,`Linked test command is not trusted by this clone (source_ref=${params.executionContext.trust.source_ref??"unknown"}, current_ref=${params.executionContext.trust.current_source_ref??"unknown"}). ${recovery}`)}function resolveLinkedTestSafetyPreflightResult(params){if(!params.linkedTest.command)return buildLinkedTestSkippedResult(params.linkedTest,params.executionContext,"No command configured for this linked test.");const runtimeSafetySkipReason=getRuntimeSafetySkipReason(params.linkedTest.command);return runtimeSafetySkipReason?buildLinkedTestSkippedResult(params.linkedTest,params.executionContext,runtimeSafetySkipReason):null}function resolveUnboundPmContextFailure(params){return params.executionContext.pm_context_mode!=="none"?null:params.executionContext.workspace_context_mode==="source"?buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):params.executionContext.is_pm_command?buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function buildLinkedTestConfigurationRefusalResult(linkedTest,executionContext,error){return{command:linkedTest.command,path:linkedTest.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:executionContext,error}}function resolvePmContextMismatchFailure(params){const failOnMismatchByDefault=params.executionContext.pm_context_mode==="schema"&&params.executionContext.is_pm_tracker_read_command&&params.executionContext.mismatch_detected,failOnMismatchByFlag=params.options?.failOnContextMismatch===!0&&params.executionContext.is_pm_command&&params.executionContext.mismatch_detected;if(!failOnMismatchByDefault&&!failOnMismatchByFlag)return null;const mismatchHint=buildPmContextMismatchHint({executionContext:params.executionContext,runLevelPmContextMode:params.runLevelPmContextMode,linkedOverridePmContextMode:params.linkedOverridePmContextMode}),mismatchPrefix=params.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,`${mismatchPrefix} (source_project_items=${params.executionContext.source_project_item_count}, sandbox_project_items=${params.executionContext.sandbox_project_item_count}).${mismatchHint}`)}function resolveLinkedTestPreflightResult(params){return resolveLinkedTestSafetyPreflightResult(params)||resolveLinkedTestTrustPreflightResult(params)||resolveUnboundPmContextFailure(params)||resolvePmContextMismatchFailure(params)||(params.options?.requireAssertionsForPm===!0&&params.executionContext.is_pm_command&&!hasLinkedTestAssertions(params.linkedTest)?buildLinkedTestConfigurationRefusalResult(params.linkedTest,params.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function buildLinkedTestExecutionEnv(params){const effectiveDirectives=resolveEffectiveLinkedTestDirectives(params.runtimeDirectives,params.linkedTest),executionEnv={...process.env,SENTRY_ENVIRONMENT:"test"};return applyEnvDirectiveStage(executionEnv,params.runtimeDirectives),applyEnvDirectiveStage(executionEnv,{env_set:params.linkedTest.env_set??{},env_clear:params.linkedTest.env_clear??[]}),effectiveDirectives.shared_host_safe&&applySharedHostSafeDefaults(executionEnv),executionEnv.FORCE_COLOR="0",params.executionContext.pm_context_mode==="none"?delete executionEnv.PM_PATH:executionEnv.PM_PATH=params.executionContext.sandbox_project_pm_path,executionEnv.PM_GLOBAL_PATH=params.executionContext.sandbox_global_pm_path,params.executionContext.workspace_context_mode!=="source"&&(delete executionEnv.PM_BUILD_CONSUMER_LEASE,delete executionEnv.PM_BUILD_CONSUMER_LEASE_ROOT),params.executionContext.workspace_context_mode==="isolated"?(delete executionEnv.PM_SOURCE_WORKSPACE_ROOT,delete executionEnv.PM_SOURCE_PM_PATH,delete executionEnv[SOURCE_CONTEXT_ACCESS_ENV]):(executionEnv.PM_SOURCE_WORKSPACE_ROOT=params.executionContext.source_workspace_root,executionEnv.PM_SOURCE_PM_PATH=params.executionContext.workspace_context_mode==="snapshot"?params.executionContext.sandbox_project_pm_path:params.executionContext.source_project_pm_path,executionEnv[SOURCE_CONTEXT_ACCESS_ENV]="read_only"),executionEnv}function buildLinkedTestPassedResult(linkedTest,executionContext,execution,receipt){return{command:linkedTest.command,path:linkedTest.path,status:"passed",exit_code:0,execution_context:executionContext,stdout:execution.stdout,stderr:execution.stderr,...receipt?{execution_receipt:receipt}:{}}}function buildLinkedTestEmptyRunResult(params){return{command:params.linkedTest.command,path:params.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:params.executionContext,stdout:params.execution.stdout,stderr:params.execution.stderr,error:`Linked test reported an empty test run (${params.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function buildLinkedTestCommandFailureResult(params){return{command:params.linkedTest.command,path:params.linkedTest.path,status:"failed",exit_code:resolveLinkedTestFailureExitCode(params.execution),failure_category:classifyLinkedTestFailure(params.execution),execution_context:params.executionContext,stdout:params.execution.stdout,stderr:params.execution.stderr,error:formatLinkedTestExecutionError(params.execution,params.timeoutMs)}}function buildLinkedTestPassedExecutionResult(params){const receipt=findLinkedTestExecutionReceipt(params.execution.stdout,params.execution.stderr),nameFiltered=params.linkedTest.phase!=="setup"&&commandUsesTestNameFilter(params.linkedTest.command??"");if(params.options?.failOnEmptyTestRun===!0||nameFiltered){const emptyRunSignal=detectEmptyLinkedTestRun(params.execution.stdout,params.execution.stderr);if(emptyRunSignal)return buildLinkedTestEmptyRunResult({...params,emptyRunSignal});if(nameFiltered&&!receipt)return buildLinkedTestEmptyRunResult({...params,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}const assertionFailures=evaluateLinkedTestAssertions(params.linkedTest,params.execution.stdout,params.execution.stderr);return assertionFailures.length>0?buildLinkedTestAssertionFailureResult(params.linkedTest,params.executionContext,`Linked test assertion(s) failed: ${assertionFailures.join("; ")}`,params.execution):buildLinkedTestPassedResult(params.linkedTest,params.executionContext,params.execution,receipt)}async function runSingleLinkedTest(params){const command=params.linkedTest.command??"",timeoutMs=(params.linkedTest.timeout_seconds??params.defaultTimeoutSeconds??120)*1e3,execution=await runLinkedTestCommand(command,timeoutMs,buildLinkedTestExecutionEnv(params),{index:params.index+1,total:params.total,timeoutMs,command},params.progressMode,params.executionContext.working_directory);return execution.exitCode===0&&!execution.timedOut&&!execution.maxBufferExceeded?buildLinkedTestPassedExecutionResult({...params,execution}):buildLinkedTestCommandFailureResult({...params,execution,timeoutMs})}async function runLinkedTests(tests,defaultTimeoutSeconds,options){const ordered=orderLinkedTestsSetupFirst(tests);for(const test of ordered)assertLinkedTestCommand(test.command);const results=[],sandboxRoot=await mkdtemp(path.join(tmpdir(),"pm-linked-test-")),layout=createLinkedTestSandboxLayout(sandboxRoot),runLevelPmContextMode=parsePmContextMode(options?.pmContext),runLevelWorkspaceContextMode=parseWorkspaceContextMode(options?.workspaceContext),progressMode=options?.progress===!0?"always":"auto",runtimeDirectives=resolveRuntimeDirectives(options?.envSet,options?.envClear,options?.sharedHostSafe),sourceRoots=options?.sourceRoots,sourceWorkspaceRoot=resolveLinkedTestSourceWorkspaceRoot(),includeTrackerData=linkedTestsRequireTrackerData(ordered,runLevelPmContextMode,options),includeWorkspaceSnapshot=linkedTestsRequireWorkspaceSnapshot(ordered,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===!0),currentSourceRef=await resolveLinkedTestSourceRef(sourceWorkspaceRoot);try{await initializeLinkedTestSandboxes(layout,runInit,includeTrackerData),await mkdir(layout.workspaceIsolatedRoot,{recursive:!0}),await seedLinkedTestSandboxesFromSource(layout,sourceRoots,includeTrackerData),includeWorkspaceSnapshot&&await seedLinkedTestWorkspaceSnapshot(sourceWorkspaceRoot,layout.workspaceSnapshotRoot,sourceRoots?.projectPmRoot,includeTrackerData);const counts=await countLinkedTestSandboxItems(layout,sourceRoots),setupGate=createLinkedTestSetupGate(),resolveWorkspaceMode=linkedTest=>resolveLinkedTestWorkspaceContextMode(linkedTest,runLevelWorkspaceContextMode,options?.overrideLinkedWorkspaceContext===!0),regularWorkspaceModes=new Set(ordered.filter(test=>!isLinkedTestSetup(test)).map(resolveWorkspaceMode)),runEntry=async(linkedTest,index)=>{const entryOptions=setupGate.options(linkedTest,options),workspaceContextMode=resolveWorkspaceMode(linkedTest),workspaceRefusal=resolveSetupWorkspaceRefusal(linkedTest,workspaceContextMode,regularWorkspaceModes);if(workspaceRefusal)return workspaceRefusal;const commandContext=await resolveLinkedTestCommandContext({linkedTest,layout,counts,sourceRoots,runLevelPmContextMode,options,requestedWorkspaceContextMode:runLevelWorkspaceContextMode,workspaceContextMode,currentSourceRef,sourceWorkspaceRoot});return resolveLinkedTestPreflightResult({linkedTest,executionContext:commandContext.executionContext,runLevelPmContextMode,linkedOverridePmContextMode:commandContext.linkedOverridePmContextMode,options:entryOptions})??await runSingleLinkedTest({linkedTest,index,total:ordered.length,defaultTimeoutSeconds,runtimeDirectives,progressMode,executionContext:commandContext.executionContext,options:entryOptions})};for(let index=0;index<ordered.length;index+=1){const linkedTest=ordered[index];results.push(setupGate.blocked(linkedTest)??setupGate.record(linkedTest,await runEntry(linkedTest,index)))}}finally{await rm(layout.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return results}function countRemovedStoredTests(before,after){const remaining=[...after];return before.filter(entry=>{const index=remaining.findIndex(candidate=>linkedTestsHaveSameIdentity(candidate,entry));return index>=0&&remaining.splice(index,1),index<0}).length}async function readLinkedTestItem(params){const{id,pmRoot,settings,typeToFolder}=params,located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const loaded=await readLocatedItem(located,{schema:settings.schema});return{itemId:located.id,tests:loaded.document.metadata.tests??[],testRuns:loaded.document.metadata.test_runs??[],changed:!1,removed:0}}function appendMissingLinkedTests(current,additions){const next=[...current];for(const addition of additions)next.some(entry=>linkedTestsHaveSameIdentity(entry,addition))||next.push(addition);return next}function removeLinkedTestsBySelector(current,removals,removeIndexes){if(removals.length===0&&removeIndexes.length===0)return{tests:current,removed:0};const indexSet=new Set(removeIndexes),tests=current.filter((entry,index)=>indexSet.has(index+1)?!1:!removals.some(selector=>selector.kind==="command"?entry.command===selector.value:selector.kind==="path"?entry.path===selector.value:entry.command===selector.value||entry.path===selector.value));return{tests,removed:current.length-tests.length}}function applyLinkedTestMutations(previous,adds,removes,removeIndexes){return removeLinkedTestsBySelector(appendMissingLinkedTests(previous,adds),removes,removeIndexes)}function hasTestRuntimeDirectiveFlags(options){return[options.timeout!==void 0,options.progress===!0,(options.envSet?.length??0)>0,(options.envClear?.length??0)>0,options.sharedHostSafe===!0,options.pmContext!==void 0,options.overrideLinkedPmContext===!0,options.failOnContextMismatch===!0,options.failOnSkipped===!0,options.failOnEmptyTestRun===!0,options.requireAssertionsForPm===!0,options.checkContext===!0,options.fullOutput===!0,options.autoPmContext===!0,options.workspaceContext!==void 0,options.overrideLinkedWorkspaceContext===!0,options.allowUntrustedLinkedTests===!0].some(Boolean)}function assertTestRunFlagUsage(options){if(hasTestRuntimeDirectiveFlags(options)&&options.run!==!0)throw new PmCliError("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",EXIT_CODE.USAGE);if(options.acknowledgeLinkedTests===!0&&options.run===!0)throw new PmCliError("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",EXIT_CODE.USAGE);if((options.match!==void 0||options.onlyIndex!==void 0||options.onlyLast===!0)&&options.run!==!0)throw new PmCliError("--match, --only-index, and --only-last require --run",EXIT_CODE.USAGE)}async function resolveLinkedTestItem(params){const{id,options,pmRoot,settings,typeToFolder,adds,removes,removeIndexes}=params;if(adds.length===0&&removes.length===0&&removeIndexes.length===0)return readLinkedTestItem({id,pmRoot,settings,typeToFolder});let removed=0,before=[];const result=await mutateItem({pmRoot,settings,id,op:adds.length>0?"tests_add":"tests_remove",author:resolveAuthor(options.author,settings.author_default),message:options.message,force:options.force,skipNoop:!0,mutate(document){const previous=document.metadata.tests??[],mutation=applyLinkedTestMutations(previous,adds,removes,removeIndexes);if(admitLinkedTestRequest(()=>resolveTestRunOptions(options,mutation.tests)),removed=mutation.removed,(removes.length>0||removeIndexes.length>0)&&removed===0)throw new PmCliError("No linked tests matched the requested removal selector",EXIT_CODE.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...removes.map(entry=>`${entry.kind}=${entry.value}`),...removeIndexes.map(index=>`index=${index}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${id} --list`,`pm test ${id} --remove-index 1`]});return document.metadata.tests=mutation.tests,before=previous,{changedFields:stableValueEquals(previous,mutation.tests)?[]:["tests"]}}}),tests=result.item.tests??[];return{itemId:result.item.id,tests,testRuns:result.item.test_runs??[],changed:result.changedFields.length>0,removed,written:result.changedFields.length>0?writtenLinkedEntries(before,tests):[],storedRemoved:countRemovedStoredTests(before,tests)}}function resolveTestRunOptions(options,tests){const pmContextMode=parsePmContextMode(options.pmContext);parseWorkspaceContextMode(options.workspaceContext),resolveRuntimeDirectives(options.envSet,options.envClear,options.sharedHostSafe);const selectorInput={match:options.match,onlyIndex:options.onlyIndex===void 0?void 0:parseOnlyIndexValue(options.onlyIndex),onlyLast:options.onlyLast},defaultTimeoutSeconds=options.timeout===void 0?void 0:parseOptionalNumber(options.timeout,"--timeout");if(defaultTimeoutSeconds!==void 0&&defaultTimeoutSeconds<=0)throw new PmCliError(`--timeout must be a positive number (got "${options.timeout}")`,EXIT_CODE.USAGE);assertTestRunFlagUsage(options);const runSelection=options.run===!0?withLinkedTestSetupEntries(resolveLinkedTestRunSelection(tests,selectorInput),tests):void 0;if(runSelection)for(const test of runSelection.selected)assertLinkedTestCommand(test.command);return{defaultTimeoutSeconds,pmContextMode,runSelection,testsToRun:runSelection?.selected??tests}}async function executeSelectedLinkedTests(params){const{options,runOptions,pmRoot}=params;return options.run!==!0?[]:await runLinkedTests(runOptions.testsToRun,runOptions.defaultTimeoutSeconds,{progress:options.progress,envSet:options.envSet,envClear:options.envClear,sharedHostSafe:options.sharedHostSafe,pmContext:runOptions.pmContextMode,overrideLinkedPmContext:options.overrideLinkedPmContext,failOnContextMismatch:options.failOnContextMismatch,failOnEmptyTestRun:options.failOnEmptyTestRun===!0||(options.measure?.length??0)>0,requireAssertionsForPm:options.requireAssertionsForPm,checkContext:options.checkContext,autoPmContext:options.autoPmContext,workspaceContext:options.workspaceContext,overrideLinkedWorkspaceContext:options.overrideLinkedWorkspaceContext,pmRoot,allowUntrustedLinkedTests:options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:params.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:pmRoot,globalPmRoot:resolveGlobalPmRoot(process.cwd())}})}function buildTestWarnings(options,runResults){const warnings=[];if(options.run===!0&&options.checkContext===!0){const preflight=summarizeContextPreflight(runResults);warnings.push(`context_preflight:checked_pm_commands=${preflight.checked_pm_commands};tracker_read_commands=${preflight.tracker_read_commands};mismatches=${preflight.mismatches};auto_remediated=${preflight.auto_remediated}`)}return warnings}function buildTrackedTestRunSummary(params){const summary=summarizeRunResultStatuses(params.runResults),parsedAttempt=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),resumedFrom=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),recordedAt=nowIso(),measurements=parseTestRunMeasurements(params.options.measure,recordedAt);return{run_id:resolveTrackedRunId("test"),kind:"test",status:summary.failed>0||params.failOnSkippedTriggered?"failed":"passed",started_at:params.runStartedAt,finished_at:recordedAt,recorded_at:recordedAt,attempt:Number.isFinite(parsedAttempt)&&parsedAttempt>=1?parsedAttempt:void 0,resumed_from:resumedFrom&&resumedFrom.length>0?resumedFrom:void 0,passed:summary.passed,failed:summary.failed,skipped:summary.skipped,fail_on_skipped_triggered:params.failOnSkippedTriggered?!0:void 0,measurements:measurements.length>0?measurements:void 0,executions:params.runResults.filter(result=>result.command?.trim()).slice(0,32).map(result=>({command:result.command.trim(),requested_pm_context_mode:result.execution_context?.requested_pm_context_mode,pm_context_mode:result.execution_context?.pm_context_mode,workspace_context_mode:result.execution_context?.workspace_context_mode,trust_reason:result.execution_context?.trust.reason}))}}async function recordTestRunSummary(params){const{options,pmRoot,settings,itemId,runStartedAt,runResults,failOnSkippedTriggered,warnings}=params;if(options.run!==!0||!runStartedAt)return;const entry=buildTrackedTestRunSummary({options,runStartedAt,runResults,failOnSkippedTriggered});if(settings.testing.record_results_to_items!==!0)return{entry,receipt:{recorded:!1,reason:"tracking_disabled",run_id:entry.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await appendTrackedTestRunSummary({pmRoot,settings,itemId,author:resolveAuthor(options.author,settings.author_default),message:`Track test run summary (${entry.run_id})`,entry}),{entry,receipt:{recorded:!0,reason:"recorded",run_id:entry.run_id}}}catch(error){if(isItemRevisionConflict(error))throw error;return warnings.push(`test_result_tracking_failed:${itemId}:${error instanceof Error?error.message:String(error)}`),{entry,receipt:{recorded:!1,reason:"write_failed",run_id:entry.run_id}}}}function buildTestMeasurementProjection(options,runs,recordedRun){let metricBelow;if(options.metricBelow!==void 0){const separator=options.metricBelow.indexOf("="),name=options.metricBelow.slice(0,separator).trim(),thresholdText=options.metricBelow.slice(separator+1).trim(),threshold=Number(thresholdText);if(separator<=0||name.length===0||thresholdText.length===0||!Number.isFinite(threshold))throw new PmCliError("--metric-below must use name=value",EXIT_CODE.USAGE);metricBelow=queryTestRunMeasurementsBelow(runs,name,threshold)}return{measurements:recordedRun?.measurements,metric_below:metricBelow,metric_diff:options.metricDiff===void 0?void 0:diffTestRunMeasurements(runs,options.metricDiff)}}async function maybeAcknowledgeLinkedTests(options,pmRoot,tests){if(options.acknowledgeLinkedTests===!0)return acknowledgeLinkedTests(pmRoot,tests,nowIso())}function projectTestResult(input){const{item,runResults,failureCategories,runSelection,failOnSkippedTriggered,warnings,recording,measurementProjection,restoreScope}=input,mutation=projectLinkedTestMutation(item,input.fullHistory),returned=selectReturnedLinkedTests(item,runSelection,mutation,restoreScope),{counts,receipts}=linkedCollectionMutationFields(mutation);return{ok:runResults.every(entry=>entry.status!=="failed"&&entry.status!=="refused")&&failOnSkippedTriggered!==!0,id:item.itemId,tests:returned.tests,...returned.omitted,run_results:runResults,...input.ran?{failure_categories:failureCategories}:{},selection:runSelection?{selector:runSelection.selector,requested:runSelection.requested,selected_indexes:runSelection.selected_indexes,selected_count:runSelection.selected_count,skipped_count:runSelection.skipped_count,...runSelection.setup_indexes?{setup_indexes:runSelection.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:failOnSkippedTriggered?!0:void 0,warnings:warnings.length>0?warnings:void 0,changed:item.changed||recording?.receipt.recorded===!0,...recording?{evidence_recording:recording.receipt}:{},count:returned.count,...item.removed>0?{removed:item.removed}:{},...counts,...measurementProjection,...receipts}}function selectReturnedLinkedTests(item,runSelection,mutation,restoreScope){return mutation!==void 0?{tests:mutation.entries,count:mutation.returned_count,omitted:{}}:runSelection!==void 0&&runSelection.selector!==null&&runSelection.skipped_count>0?{tests:runSelection.selected,count:item.tests.length,omitted:{tests_omitted:{count:item.tests.length-runSelection.selected.length,restore_with:renderLinkedTestRestoreCommand(item.itemId,restoreScope)}}}:{tests:item.tests,count:item.tests.length,omitted:{}}}function projectLinkedTestMutation(item,fullHistory){if(item.written!==void 0)return projectLinkedCollectionMutation({collectionKey:"tests",stored:item.tests,written:item.written,removedCount:item.storedRemoved,fullHistory})}function projectLinkedTestEdit(result,fullHistory){const edited=result.tests[result.updated_index-1],mutation=projectLinkedCollectionMutation({collectionKey:"tests",stored:result.tests,written:result.changed&&edited!==void 0?[edited]:[],removedCount:0,fullHistory}),{counts,receipts}=linkedCollectionMutationFields(mutation);return{...result,tests:mutation.entries,run_results:[],count:mutation.returned_count,...counts,...receipts}}async function runTest(id,options,global2){const edit=parseLinkedTestUpdateOptions(options);if(edit){assertLinkedTestEditUsage(options),assertTestRunFlagUsage(options),assertTestMeasurementRun(id,options,global2,resolvePmRoot(process.cwd(),global2.path));const result=await updateLinkedTest(id,{...edit,author:options.author,message:options.message,force:options.force},global2);return projectLinkedTestEdit(result,options.fullHistory===!0)}const stdinResolver=createStdinTokenResolver(),pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);assertTestMeasurementRun(id,options,global2,pmRoot),parseTestRunMeasurements(options.measure,"validation"),buildTestMeasurementProjection(options,[],void 0);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),resolvedAdds=await stdinResolver.resolveList(options.add,"--add"),resolvedAddJsons=await stdinResolver.resolveList(options.addJson,"--add-json"),resolvedRemoves=await stdinResolver.resolveList(options.remove,"--remove"),parsedAdds=[...parseAddEntries(resolvedAdds),...parseAddJsonEntries(resolvedAddJsons)],adds=await attachLinkedTestMutationProvenance(parsedAdds,resolveAuthor(options.author,settings.author_default),nowIso())??[],removes=parseRemoveEntries(resolvedRemoves),removeIndexes=parseRemoveIndexes(options.removeIndex),item=await resolveLinkedTestItem({id,options,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,adds,removes,removeIndexes}),runOptions=admitLinkedTestRequest(()=>resolveTestRunOptions(options,item.tests)),trustAcknowledgement=await maybeAcknowledgeLinkedTests(options,pmRoot,item.tests),runStartedAt=options.run===!0?nowIso():void 0,runResults=await executeSelectedLinkedTests({options,runOptions,pmRoot,untrustedLinkedTestsPolicyEnabled:settings.testing.allow_untrusted_linked_tests});assertTestMeasurementExecution(id,options,global2,pmRoot,runResults);const failureCategories=countFailureCategories(runResults),failOnSkippedTriggered=options.run===!0&&options.failOnSkipped===!0&&runResults.some(entry=>entry.status==="skipped"),warnings=buildTestWarnings(options,runResults);trustAcknowledgement&&warnings.push(`linked_test_trust_acknowledged:${trustAcknowledgement.acknowledged}`);const recording=await recordTestRunSummary({options,pmRoot,settings,itemId:item.itemId,runStartedAt,runResults,failOnSkippedTriggered,warnings}),runs=recording?.receipt.recorded?buildTrackedTestRunHistory([...item.testRuns,recording.entry]):item.testRuns,measurementProjection=buildTestMeasurementProjection(options,runs,recording?.entry);return projectTestResult({item,runResults,failureCategories,runSelection:runOptions.runSelection,failOnSkippedTriggered,warnings,recording,measurementProjection,restoreScope:resolveLinkedTestRestoreScope(global2,pmRoot),ran:options.run===!0,fullHistory:options.fullHistory===!0})}const _testOnlyTestCommand={buildLinkedTestExecutionContext,buildPmContextMismatchHint,commandInvokesPmCli,commandInvokesPmTrackerReadCommand,commandUsesTestNameFilter,copyIntoSandboxIfPresent,countLinkedTestItemFiles,ensureScope,evaluateLinkedTestAssertions,endLinkedTestProgress,extractPmInvocationArgsFromSegment,firstDirectTestRunnerSubcommand,formatLinkedTestExecutionError,hasLinkedTestAssertions,initializeLinkedTestSandboxes,linkedTestsRequireTrackerData,parseAddJsonEntries,parseLinkedTestTimeoutSeconds,parsePmContextMode,readJsonPathValue,resolveAuthor,resolveDirectRunnerSubcommand,resolveLinkedTestEffectiveContextMode,resolveLinkedTestFailureExitCode,resolveLinkedTestRequestedContextMode,resolveTestRunOptions,resolveTrackedRunId,runLinkedTestCommand,seedMissingLinkedTestSettingsHistory,seedLinkedTestSandbox,seedLinkedTestTrackerData,segmentInvokesRecursiveTestAll,splitJsonPathSegments,summarizeRunResultStatuses};export{_testOnlyTestCommand,classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories2 as countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight};
1
+ import{readJsonPathValue as K,splitJsonPathSegments as xt}from"./json-path.js";import{isItemRevisionConflict as Tt}from"../lifecycle/item-revision.js";import{detectEmptyLinkedTestRun as gt,findLinkedTestExecutionReceipt as wt,renderLinkedTestRestoreCommand as Ct,resolveLinkedTestRestoreScope as Pt}from"./execution-receipts.js";import{seedLinkedTestWorkspaceSnapshot as vt}from"./workspace-snapshot.js";import{detectLinkedTestCommandNotFound as St}from"./command-resolution.js";import{updateLinkedTest as Lt,parseLinkedTestUpdateOptions as Et,assertLinkedTestEditUsage as yt}from"./update.js";import{admitLinkedTestRequest as ae,assertLinkedTestCommand as le,linkedTestsHaveSameIdentity as me}from"./entry.js";import{countFailureCategories as Rt,createLinkedTestSetupGate as bt,isLinkedTestSetup as Mt,orderLinkedTestsSetupFirst as Ot,parseLinkedTestPhase as It,resolveSetupWorkspaceRefusal as At,withLinkedTestSetupEntries as jt}from"./run-phases.js";import{assertInitializedTracker as Nt}from"../environment/tracker-preflight.js";import{spawn as Ft}from"node:child_process";import{killProcessTree as fe}from"../../core/shared/process-tree.js";const _e={taskkillTimeoutMs:null};import{cp as pe,mkdir as V,mkdtemp as he,open as J,readdir as z,rm as j,symlink as $t}from"node:fs/promises";import{tmpdir as ke}from"node:os";import f from"node:path";import{getActiveExtensionRegistrations as Dt}from"../../core/extensions/index.js";import{isFileMissingError as Ut,pathExists as D,readFileIfExists as xe}from"../../core/fs/fs-utils.js";import{getWorkspaceHistoryPath as Te,writeWorkspaceJsonWithHistory as ge}from"../../core/history/workspace-history.js";import{resolveItemTypeRegistry as Gt}from"../../core/item/type-registry.js";import{createStdinTokenResolver as Wt,parseCsvKv as we,parseOptionalNumber as Ce}from"../../core/item/parse.js";import{EXIT_CODE as p}from"../../core/shared/constants.js";import{resolveAuthor as I}from"../../core/shared/author.js";import{PmCliError as h}from"../../core/shared/errors.js";import{stableValueEquals as Pe}from"../../core/shared/serialization.js";import{nowIso as U}from"../../core/shared/time.js";import{locateItem as qt,mutateItem as Ht,readLocatedItem as Bt}from"../../core/store/item-store.js";import{getSettingsPath as b,ITEM_FILE_EXTENSIONS as Kt,resolveGlobalPmRoot as Vt,resolvePmRoot as ve}from"../../core/store/paths.js";import{readSettings as Y}from"../../core/store/settings.js";import{appendTrackedTestRunSummary as Jt,buildTrackedTestRunHistory as zt}from"../../core/test/item-test-run-tracking.js";import{runInit as Se}from"../init.js";import{looksLikeStructuredLinkedTestEntry as Yt,normalizeStructuredLinkedTestEntry as Xt}from"./entry.js";import{LINKED_TEST_PM_CONTEXT_MODE_VALUES as Le,LINKED_TEST_PROTECTED_ENV_KEYS as Ee,parseLinkedTestAssertionEqualsMap as Qt,parseLinkedTestAssertionGteMap as Zt,parseLinkedTestBoolean as en,parseLinkedTestContextMode as tn,parseLinkedTestEnvClear as ye,parseLinkedTestEnvSet as Re,parseLinkedTestJsonEntries as nn,parseLinkedTestMinLines as on,parseLinkedTestRegexList as be,parseLinkedTestStringList as Me,parseLinkedTestWorkspaceContextMode as X}from"./parsers.js";import{parseOnlyIndexValue as rn,resolveLinkedTestRunSelection as sn}from"../../core/test/run-selectors.js";import{SCOPE_VALUES as cn}from"../../types/index.js";import{diffTestRunMeasurements as dn,parseTestRunMeasurements as Oe,queryTestRunMeasurementsBelow as un}from"./measurements.js";import{withHostEnvironmentBoundary as an}from"../environment/host-environment-errors.js";import{linkedCollectionMutationFields as Ie,projectLinkedCollectionMutation as Ae,writtenLinkedEntries as ln}from"../linked-artifacts.js";import{SOURCE_CONTEXT_ACCESS_ENV as je}from"../environment/source-context.js";import{assertTestMeasurementExecution as mn,assertTestMeasurementRun as Ne}from"./prerequisites.js";import{acknowledgeLinkedTests as fn,attachLinkedTestMutationProvenance as _n,resolveLinkedTestSourceRef as pn,resolveLinkedTestSourceWorkspaceRoot as hn,resolveLinkedTestTrust as Fe}from"./trust.js";const G=20*1024*1024,kn=3e3,xn=1e4,Tn=5e3,$e=120,gn=new Set(["locks","extensions","runtime"]),wn=new Set(["history","index","search","extensions","locks","runtime"]),Cn=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],Pn=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,vn=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,Sn=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Q(e,t){const n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;const o=Number.parseInt(n,10);return!Number.isFinite(o)||o<=0?t:o}function Ln(){return Q("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",kn)}function En(){return Q("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",xn)}function yn(){return Q("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",Tn)}import{countFailureCategories as Dr}from"./run-phases.js";function De(e){const t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Ue(e){let t=0,n=0,o=0;for(const r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"||r.status==="refused"){n+=1;continue}o+=1}return{passed:t,failed:n,skipped:o}}function Rn(e){let t=0,n=0,o=0,r=0;for(const s of e){const i=s.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(o+=1),i.auto_pm_context_applied===!0&&(r+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:o,auto_remediated:r}}function Ge(e){const t=e??"project";if(!cn.includes(t))throw new h(`Invalid scope "${e}"`,p.USAGE);return t}function N(e){if(!e)return"schema";const t=e.trim().toLowerCase();if(Le.includes(t))return t;throw new h(`Invalid --pm-context value "${e}". Expected one of: ${Le.join(", ")}`,p.USAGE)}function We(e){return X(e??"source","--workspace-context")}function qe(e,t,n){return n?t:X(e.workspace_context_mode,"linked test")??t}function Z(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:N(e.pm_context_mode)}function ee(e,t){return e==="auto"?t?"tracker":"schema":e}function He(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function Be(e){const{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:o}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&o==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function bn(e,t){const n={};if(!e)return n;for(const o of e){const r=Re(o,t);if(r)for(const[s,i]of Object.entries(r))n[s]=i}return n}function Mn(e,t){if(!e)return[];const n=[];for(const o of e){const r=ye(o,t);r&&n.push(...r)}return[...new Set(n)]}import{BUN_GLOBAL_FLAGS_WITH_VALUE as On,NPM_GLOBAL_FLAGS_WITH_VALUE as In,PNPM_GLOBAL_FLAGS_WITH_VALUE as An,SCRIPT_RUN_FLAGS_WITH_VALUE as jn,SCRIPT_RUN_SUBCOMMANDS as Nn,YARN_GLOBAL_FLAGS_WITH_VALUE as Fn,extractPmInvocationArgsFromSegment as te,parseLauncherSubcommand as F,parseNpmExecCommand as $n,parseNpxCommand as Ke,parsePnpmDlxCommand as Dn,resolvePmSubcommandContext as Un,splitNormalizedCommandSegments as W,stripLeadingEnvAssignments as Gn,SHELL_COMMAND_FLAG_PATTERNS as Wn,assertNoRecursiveTestAllCommand as Ve,invokesRecursiveTestAllCommand as qn,normalizeCommandForValidation as q,segmentInvokesRecursiveTestAll as Hn}from"./linked-command-detection.js";import{extractReferencedPmItemIdsFromCommand as Gr}from"./linked-command-detection.js";function Je(e){const t=q(e);return W(t).some(n=>te(n)!==null)}function ne(e){const t=q(e);return W(t).some(n=>{const o=te(n);if(!o)return!1;const r=Un(o);return r?Sn.has(r.subcommand):!1})}function $(e){if(e)return Nn.has(e.subcommand)?F(e.args,jn)?.subcommand:e.subcommand}function oe(e,t){if(e==="npx"||e==="bunx")return Ke(t)?.command;if(e==="pnpm")return $(F(t,An));if(e==="npm")return $(F(t,In));if(e==="yarn")return $(F(t,Fn));if(e==="bun")return $(F(t,On))}function H(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function ze(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function re(e){const t=e.split(" ").filter(i=>i.length>0),n=Gn(t);if(n.length===0)return!1;const[o,...r]=n,s=Wn.get(o);if(s){const i=r.findIndex(c=>s.test(c));return i>=0&&re(r.slice(i+1).join(" "))}return o==="vitest"||o.endsWith("/vitest")||o.endsWith("/vitest.mjs")?!0:o==="node"?Bn(r):Kn(o,r)}function Bn(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function Kn(e,t){return e==="npx"||e==="bunx"?H(Ke(t)?.command):e==="pnpm"||e==="npm"?H((e==="pnpm"?Dn(t):$n(t))?.command)||H(oe(e,t)):(e==="yarn"||e==="bun")&&H(oe(e,t))}function Ar(e){const t=q(e),n=W(t),o=n.some(s=>!ze(s)&&re(s)),r=n.some(ze);return{accepted:!0,command_kind:o?"direct_runner":r?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:o?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function Vn(e){if(qn(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function Jn(e){return e?e.map(zn):[]}function zn(e){const t=e.trim(),n=Yt(t)?Xt(we(e,"--add"),"--add"):{command:t},o=x(n.command);if(!o)throw new h("--add requires command=<value> or a bare command (path=<value> is optional metadata)",p.USAGE);return Ve(o),{command:o,path:x(n.path),scope:Ge(n.scope),timeout_seconds:Ye(x(n.timeout_seconds),x(n.timeout)),pm_context_mode:tn(x(n.pm_context_mode),"--add"),workspace_context_mode:X(x(n.workspace_context_mode),"--add"),env_set:Re(x(n.env_set),"--add"),env_clear:ye(x(n.env_clear),"--add"),shared_host_safe:en(x(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Me(x(n.assert_stdout_contains)),assert_stdout_regex:be(x(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Me(x(n.assert_stderr_contains)),assert_stderr_regex:be(x(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:on(x(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Qt(x(n.assert_json_field_equals),"--add"),assert_json_field_gte:Zt(x(n.assert_json_field_gte),"--add"),note:x(n.note),phase:It(n.phase,"--add")}}function x(e){const t=e?.trim();return t&&t.length>0?t:void 0}function Ye(e,t){if(e&&t&&e!==t)throw new h("--add timeout and timeout_seconds must match when both are provided",p.USAGE);const n=e??t;if(n===void 0)return;const o=Math.floor(Ce(n,"timeout_seconds"));if(o<=0)throw new h("--add timeout_seconds must be a positive integer",p.USAGE);return o}function Xe(e){return e?e.flatMap(t=>{const n=nn(t,"--add-json");for(const o of n){const r=o.command;if(!r)throw new h("--add-json requires a non-empty command string",p.USAGE);Ve(r)}return n}):[]}function Yn(e){return e?e.map(t=>{const n=t.trim();if(!n)throw new h("--remove requires command or path value",p.USAGE);const o=/^(command|path)\s*=/i.exec(n);if(o){const r=n.slice(o[0].length).trim();if(!r)throw new h("--remove requires a non-empty command=<value> or path=<value>",p.USAGE);return{kind:o[1].toLowerCase(),value:r}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new h("--remove structured selectors require command=<value> or path=<value>",p.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){const r=we(n,"--remove"),s=r.path!==void 0?"path":"command",i=r.path??r.command;if(!i?.trim())throw new h("--remove requires command=<value> and/or path=<value>",p.USAGE);return{kind:s,value:i.trim()}}return{kind:"either",value:n}}):[]}function Xn(e){return e?[...new Set(e.map(t=>{const n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new h("--remove-index must be a positive integer",p.USAGE);return n}))]:[]}function Qn(e){try{e.stdin?.end()}catch{}}function Qe(e){const t=e.trim().replaceAll(/\s+/g," ");return t.length<=$e?t:`${t.slice(0,$e-3)}...`}function Ze(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function se(e){try{process.stderr.write(`${e}
2
+ `)}catch{}}function Zn(e,t){if(!Ze(t))return null;const n=Qe(e.command),o=Date.now();se(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);const r=setInterval(()=>{const s=Date.now()-o;se(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},En());return r.unref?.(),r}function et(e,t,n,o){if(!Ze(o))return;const r=Qe(e.command),s=Date.now()-n,c=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",d=[];t.timedOut&&d.push("reason=timeout"),t.maxBufferExceeded&&d.push("reason=max_buffer"),t.outputTruncated&&d.push("output=truncated"),t.signal&&d.push(`signal=${t.signal}`);const a=t.exitCode===null?"null":String(t.exitCode),u=d.length>0?` ${d.join(" ")}`:"";se(`[pm test] linked-test ${e.index}/${e.total} end status=${c} exit_code=${a} elapsed_ms=${s}${u} command="${r}"`)}function eo(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function to(e,t){let n=!1;return async()=>{if(n)return;n=!0;const o=e.pid,r={alive:()=>e.exitCode===null&&e.signalCode===null,kill:()=>{e.exitCode===null&&e.signalCode===null&&e.kill("SIGKILL")}};if(!o||o<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await fe(o,r,_e);return}try{process.kill(-o,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{fe(o,r,_e)},Ln()),t.forceKillTimer.unref?.()}}function no(e){return new Promise(t=>{let n=!1,o=null;const r=(s,i=!1)=>{n||(n=!0,o&&(clearTimeout(o),o=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,i)=>{n||(o=setTimeout(()=>{r({code:s,signal:i},!0)},yn()),o.unref?.())}),e.on("close",(s,i)=>{r({code:s,signal:i})})})}function oo(e,t,n,o,r){return Ft(e,{cwd:r,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,o]})}async function tt(e){const t=await J(e,"r");try{const n=(await t.stat()).size,o=Math.min(n,G),r=Buffer.alloc(o);return o>0&&await t.read(r,0,o,0),{text:r.toString("utf8"),truncated:n>G}}finally{await t.close()}}async function nt(e,t,n,o,r,s=process.cwd()){const i=Date.now(),c=await he(f.join(ke(),"pm-linked-test-output-"));try{const d=f.join(c,"stdout.log"),a=f.join(c,"stderr.log"),[u,l]=await Promise.all([J(d,"w"),J(a,"w")]);let k;try{k=oo(e,n,u.fd,l.fd,s)}catch(L){throw await Promise.all([u.close(),l.close()]),L}const w=no(k);let T;k.on("error",L=>{T=L.message}),await Promise.all([u.close(),l.close()]),Qn(k);const _={heartbeat:Zn(o,r),forceKillTimer:null,timedOutTimer:null},g=to(k,_);let v=!1;_.timedOutTimer=setTimeout(()=>{v=!0,g()},t),_.timedOutTimer.unref?.();const{code:E,signal:P}=await w;eo(_);const[O,m]=await Promise.all([tt(d),tt(a)]),C=O.truncated||m.truncated,S=C?`
3
+ [pm linked-test output truncated at ${G} bytes per stream; the child process continued to completion]
4
+ `:"";!T&&await St(e,{exitCode:E,stderr:m.text},n,s)&&(T="Linked test executable was not found. Install the tool or update the linked command before retrying.");const y={stdout:`${O.text}${S}`,stderr:m.text,exitCode:E,signal:P,timedOut:v,maxBufferExceeded:!1,outputTruncated:C,spawnError:T};return et(o,y,i,r),y}finally{await j(c,{recursive:!0,force:!0})}}function ot(e,t){const n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${G} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);const o=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,r=e.spawnError?.trim()||o||"Linked test command failed.";return n.length===0?r:`${r} ${n.join(" ")}`}function ro(e){const t=[e.spawnError??"",e.stderr,e.stdout].join(`
5
+ `);return Cn.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>Pn.test(n)&&vn.test(n))}function so(e){return ro(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function rt(e,t){for(const[n,o]of Object.entries(t.env_set))Ee.has(n.toUpperCase())||(e[n]=o);for(const n of t.env_clear)Ee.has(n.toUpperCase())||delete e[n]}function io(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function co(e,t){const n={...e.env_set,...t.env_set},o=[...new Set([...e.env_clear,...t.env_clear??[]])],r=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:o,shared_host_safe:r}}function st(e,t,n){return{env_set:bn(e,"--env-set"),env_clear:Mn(t,"--env-clear"),shared_host_safe:n===!0}}async function A(e,t,n=!1,o=V){if(await D(e))try{await an("seed_linked_test",async()=>{if(await o(f.dirname(t),{recursive:!0}),n){await pe(e,t,{recursive:!0,force:!0});return}await pe(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&Ut(r))return;throw r}}async function ie(e,t,n,o=!1){for(const[r,s]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(o){const i=await xe(b(r));if(i!==null){const c=await Y(s);await ge({pmRoot:s,filePath:b(s),raw:i,op:"settings:write",author:I(void 0,c.author_default),lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await A(b(r),b(s));await A(f.join(n.projectPmRoot,"extensions"),f.join(e,"extensions"),!0),await A(f.join(n.globalPmRoot,"extensions"),f.join(t,"extensions"),!0)}async function ce(e,t){if(!await D(e))return;const n=await z(e,{withFileTypes:!0});for(const o of n){if(gn.has(o.name))continue;const r=f.join(e,o.name),s=f.join(t,o.name);if(o.isDirectory()){await A(r,s,!0);continue}o.isFile()&&await A(r,s)}}async function de(e,t){const n=await xe(b(e));if(n===null||await D(Te(e)))return;const o=await Y(t);await j(Te(t),{force:!0}),await j(b(t),{force:!0}),await ge({pmRoot:t,filePath:b(t),raw:n,op:"settings:write",author:I(void 0,o.author_default),lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function M(e){if(!await D(e))return 0;let t=0;const n=await z(e,{withFileTypes:!0});for(const o of n){if(!o.isDirectory()||wn.has(o.name))continue;const r=f.join(e,o.name);let s;try{s=await z(r,{withFileTypes:!0})}catch{continue}for(const i of s)i.isFile()&&Kt.some(c=>i.name.toLowerCase().endsWith(c))&&(t+=1)}return t}function it(e){const t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function uo(e){const t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;const n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function ao(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Pe(e,t):Object.is(e,t)}function ct(e,t,n){const o=[];o.push(...dt("stdout",t,e.assert_stdout_contains)),o.push(...ut("stdout",t,e.assert_stdout_regex)),o.push(...dt("stderr",n,e.assert_stderr_contains)),o.push(...ut("stderr",n,e.assert_stderr_regex)),o.push(...lo(t,e.assert_stdout_min_lines));const r=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(r).length>0||Object.keys(s).length>0))return o;let c;try{c=JSON.parse(t)}catch(d){return o.push(`stdout is not valid JSON for assert_json_field_* checks: ${d instanceof Error?d.message:String(d)}`),o}for(const[d,a]of Object.entries(r)){const u=K(c,d);if(!u.found){o.push(`assert_json_field_equals missing path "${d}"`);continue}const l=uo(a);ao(u.value,l)||o.push(`assert_json_field_equals mismatch at "${d}" (expected=${JSON.stringify(l)} actual=${JSON.stringify(u.value)})`)}for(const[d,a]of Object.entries(s)){const u=K(c,d);if(!u.found){o.push(`assert_json_field_gte missing path "${d}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){o.push(`assert_json_field_gte path "${d}" resolved to non-numeric value`);continue}u.value<a&&o.push(`assert_json_field_gte failed at "${d}" (expected >= ${a}, actual ${u.value})`)}return o}function dt(e,t,n){const o=[];for(const r of n??[])t.includes(r)||o.push(`${e} missing required text: "${r}"`);return o}function ut(e,t,n){const o=[];for(const r of n??[])try{new RegExp(r,"m").test(t)||o.push(`${e} failed regex assertion: /${r}/m`)}catch(s){o.push(`${e} regex assertion is invalid: /${r}/ (${s instanceof Error?s.message:String(s)})`)}return o}function lo(e,t){if(typeof t!="number")return[];const n=e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function at(e){const t=q(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:W(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&re(n))}function mo(e){return{root:e,schemaProjectPmPath:f.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:f.join(e,"schema","global"),trackerProjectPmPath:f.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:f.join(e,"tracker","global"),workspaceSnapshotRoot:f.join(e,"workspace","project"),workspaceIsolatedRoot:f.join(e,"workspace","isolated")}}function fo(e,t,n){return e.some(o=>qe(o,t,n)==="snapshot")}async function _o(e,t){const n=f.join(e,".agents"),o=f.join(n,"pm");await V(n,{recursive:!0}),await j(o,{recursive:!0,force:!0}),await $t(t,o,process.platform==="win32"?"junction":"dir")}async function lt(e,t=Se,n=!0){const o={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},o),await t(void 0,{path:e.schemaGlobalPmPath},o),n&&(await t(void 0,{path:e.trackerProjectPmPath},o),await t(void 0,{path:e.trackerGlobalPmPath},o))}async function po(e,t,n){t&&(await ie(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await ie(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await ce(t.projectPmRoot,e.trackerProjectPmPath),await ce(t.globalPmRoot,e.trackerGlobalPmPath),await de(t.projectPmRoot,e.trackerProjectPmPath),await de(t.globalPmRoot,e.trackerGlobalPmPath)))}function mt(e,t,n){return e.some(o=>{const r=o.command??"",s=r.length>0&&ne(r),i=n?.autoPmContext===!0&&s?"auto":Z(o,t,n?.overrideLinkedPmContext===!0);return ee(i,s)==="tracker"})}async function ho(e,t){return{sourceProjectItemCount:t?await M(t.projectPmRoot):0,sourceGlobalItemCount:t?await M(t.globalPmRoot):0,schemaProjectItemCount:await M(e.schemaProjectPmPath),schemaGlobalItemCount:await M(e.schemaGlobalPmPath),trackerProjectItemCount:await M(e.trackerProjectPmPath),trackerGlobalItemCount:await M(e.trackerGlobalPmPath)}}function ft(e){const t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,o=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,r=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,c=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:o,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:r,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==r||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:c,trust:e.trust}}async function ko(e){const t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?N(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,o=n?Je(n):!1,r=o&&n?ne(n):!1,s=e.options?.autoPmContext===!0&&r,i=s?"auto":Z(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),c=ee(i,r),d=c==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await _o(e.layout.workspaceSnapshotRoot,d);const a=e.options?.pmRoot?await Fe(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Fe(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:ft({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:o,isPmTrackerReadCommand:r,requestedPmContextMode:i,effectivePmContextMode:c,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:a})}}function _t(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function xo(e,t,n,o){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...o?{stdout:o.stdout,stderr:o.stderr}:{},error:n}}function To(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function go(e){if(e.executionContext.trust.trusted)return null;const t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;const o=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return To(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${o}`)}function wo(e){if(!e.linkedTest.command)return _t(e.linkedTest,e.executionContext,"No command configured for this linked test.");const t=Vn(e.linkedTest.command);return t?_t(e.linkedTest,e.executionContext,t):null}function Co(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?B(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?B(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function B(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function Po(e){const t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;const o=Be({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),r=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return B(e.linkedTest,e.executionContext,`${r} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${o}`)}function vo(e){const t=wo(e);if(t)return t;const n=go(e);if(n)return n;const o=Co(e);if(o)return o;const r=Po(e);return r||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!He(e.linkedTest)?B(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function So(e){const t=co(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return rt(n,e.runtimeDirectives),rt(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&io(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[je]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[je]="read_only"),n}function Lo(e,t,n,o){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...o?{execution_receipt:o}:{}}}function pt(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function Eo(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:it(e.execution),failure_category:so(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:ot(e.execution,e.timeoutMs)}}function yo(e){const t=wt(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&at(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){const r=gt(e.execution.stdout,e.execution.stderr);if(r)return pt({...e,emptyRunSignal:r});if(n&&!t)return pt({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}const o=ct(e.linkedTest,e.execution.stdout,e.execution.stderr);return o.length>0?xo(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${o.join("; ")}`,e.execution):Lo(e.linkedTest,e.executionContext,e.execution,t)}async function Ro(e){const t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,o=await nt(t,n,So(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return o.exitCode===0&&!o.timedOut&&!o.maxBufferExceeded?yo({...e,execution:o}):Eo({...e,execution:o,timeoutMs:n})}async function bo(e,t,n){const o=Ot(e);for(const g of o)le(g.command);const r=[],s=await he(f.join(ke(),"pm-linked-test-")),i=mo(s),c=N(n?.pmContext),d=We(n?.workspaceContext),a=n?.progress===!0?"always":"auto",u=st(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,k=hn(),w=mt(o,c,n),T=fo(o,d,n?.overrideLinkedWorkspaceContext===!0),_=await pn(k);try{await lt(i,Se,w),await V(i.workspaceIsolatedRoot,{recursive:!0}),await po(i,l,w),T&&await vt(k,i.workspaceSnapshotRoot,l?.projectPmRoot,w);const g=await ho(i,l),v=bt(),E=m=>qe(m,d,n?.overrideLinkedWorkspaceContext===!0),P=new Set(o.filter(m=>!Mt(m)).map(E)),O=async(m,C)=>{const S=v.options(m,n),y=E(m),L=At(m,y,P);if(L)return L;const R=await ko({linkedTest:m,layout:i,counts:g,sourceRoots:l,runLevelPmContextMode:c,options:n,requestedWorkspaceContextMode:d,workspaceContextMode:y,currentSourceRef:_,sourceWorkspaceRoot:k});return vo({linkedTest:m,executionContext:R.executionContext,runLevelPmContextMode:c,linkedOverridePmContextMode:R.linkedOverridePmContextMode,options:S})??await Ro({linkedTest:m,index:C,total:o.length,defaultTimeoutSeconds:t,runtimeDirectives:u,progressMode:a,executionContext:R.executionContext,options:S})};for(let m=0;m<o.length;m+=1){const C=o[m];r.push(v.blocked(C)??v.record(C,await O(C,m)))}}finally{await j(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}function Mo(e,t){const n=[...t];return e.filter(o=>{const r=n.findIndex(s=>me(s,o));return r>=0&&n.splice(r,1),r<0}).length}async function Oo(e){const{id:t,pmRoot:n,settings:o,typeToFolder:r}=e,s=await qt(n,t,o.id_prefix,o.item_format,r);if(!s)throw new h(`Item ${t} not found`,p.NOT_FOUND);const i=await Bt(s,{schema:o.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function Io(e,t){const n=[...e];for(const o of t)n.some(r=>me(r,o))||n.push(o);return n}function Ao(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};const o=new Set(n),r=e.filter((s,i)=>o.has(i+1)?!1:!t.some(c=>c.kind==="command"?s.command===c.value:c.kind==="path"?s.path===c.value:s.command===c.value||s.path===c.value));return{tests:r,removed:e.length-r.length}}function jo(e,t,n,o){return Ao(Io(e,t),n,o)}function No(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function ht(e){if(No(e)&&e.run!==!0)throw new h("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",p.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new h("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",p.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new h("--match, --only-index, and --only-last require --run",p.USAGE)}async function Fo(e){const{id:t,options:n,pmRoot:o,settings:r,typeToFolder:s,adds:i,removes:c,removeIndexes:d}=e;if(i.length===0&&c.length===0&&d.length===0)return Oo({id:t,pmRoot:o,settings:r,typeToFolder:s});let a=0,u=[];const l=await Ht({pmRoot:o,settings:r,id:t,op:i.length>0?"tests_add":"tests_remove",author:I(n.author,r.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(w){const T=w.metadata.tests??[],_=jo(T,i,c,d);if(ae(()=>ue(n,_.tests)),a=_.removed,(c.length>0||d.length>0)&&a===0)throw new h("No linked tests matched the requested removal selector",p.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...c.map(g=>`${g.kind}=${g.value}`),...d.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return w.metadata.tests=_.tests,u=T,{changedFields:Pe(T,_.tests)?[]:["tests"]}}}),k=l.item.tests??[];return{itemId:l.item.id,tests:k,testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:a,written:l.changedFields.length>0?ln(u,k):[],storedRemoved:Mo(u,k)}}function ue(e,t){const n=N(e.pmContext);We(e.workspaceContext),st(e.envSet,e.envClear,e.sharedHostSafe);const o={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:rn(e.onlyIndex),onlyLast:e.onlyLast},r=e.timeout===void 0?void 0:Ce(e.timeout,"--timeout");if(r!==void 0&&r<=0)throw new h(`--timeout must be a positive number (got "${e.timeout}")`,p.USAGE);ht(e);const s=e.run===!0?jt(sn(t,o),t):void 0;if(s)for(const i of s.selected)le(i.command);return{defaultTimeoutSeconds:r,pmContextMode:n,runSelection:s,testsToRun:s?.selected??t}}async function $o(e){const{options:t,runOptions:n,pmRoot:o}=e;return t.run!==!0?[]:await bo(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:o,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:o,globalPmRoot:Vt(process.cwd())}})}function Do(e,t){const n=[];if(e.run===!0&&e.checkContext===!0){const o=Rn(t);n.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return n}function Uo(e){const t=Ue(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),o=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),r=U(),s=Oe(e.options.measure,r);return{run_id:De("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:r,recorded_at:r,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:o&&o.length>0?o:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function Go(e){const{options:t,pmRoot:n,settings:o,itemId:r,runStartedAt:s,runResults:i,failOnSkippedTriggered:c,warnings:d}=e;if(t.run!==!0||!s)return;const a=Uo({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:c});if(o.testing.record_results_to_items!==!0)return{entry:a,receipt:{recorded:!1,reason:"tracking_disabled",run_id:a.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Jt({pmRoot:n,settings:o,itemId:r,author:I(t.author,o.author_default),message:`Track test run summary (${a.run_id})`,entry:a}),{entry:a,receipt:{recorded:!0,reason:"recorded",run_id:a.run_id}}}catch(u){if(Tt(u))throw u;return d.push(`test_result_tracking_failed:${r}:${u instanceof Error?u.message:String(u)}`),{entry:a,receipt:{recorded:!1,reason:"write_failed",run_id:a.run_id}}}}function kt(e,t,n){let o;if(e.metricBelow!==void 0){const r=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,r).trim(),i=e.metricBelow.slice(r+1).trim(),c=Number(i);if(r<=0||s.length===0||i.length===0||!Number.isFinite(c))throw new h("--metric-below must use name=value",p.USAGE);o=un(t,s,c)}return{measurements:n?.measurements,metric_below:o,metric_diff:e.metricDiff===void 0?void 0:dn(t,e.metricDiff)}}async function Wo(e,t,n){if(e.acknowledgeLinkedTests===!0)return fn(t,n,U())}function qo(e){const{item:t,runResults:n,failureCategories:o,runSelection:r,failOnSkippedTriggered:s,warnings:i,recording:c,measurementProjection:d,restoreScope:a}=e,u=Bo(t,e.fullHistory),l=Ho(t,r,u,a),{counts:k,receipts:w}=Ie(u);return{ok:n.every(T=>T.status!=="failed"&&T.status!=="refused")&&s!==!0,id:t.itemId,tests:l.tests,...l.omitted,run_results:n,...e.ran?{failure_categories:o}:{},selection:r?{selector:r.selector,requested:r.requested,selected_indexes:r.selected_indexes,selected_count:r.selected_count,skipped_count:r.skipped_count,...r.setup_indexes?{setup_indexes:r.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:s?!0:void 0,warnings:i.length>0?i:void 0,changed:t.changed||c?.receipt.recorded===!0,...c?{evidence_recording:c.receipt}:{},count:l.count,...t.removed>0?{removed:t.removed}:{},...k,...d,...w}}function Ho(e,t,n,o){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:Ct(e.itemId,o)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function Bo(e,t){if(e.written!==void 0)return Ae({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function Ko(e,t){const n=e.tests[e.updated_index-1],o=Ae({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:r,receipts:s}=Ie(o);return{...e,tests:o.entries,run_results:[],count:o.returned_count,...r,...s}}async function jr(e,t,n){const o=Et(t);if(o){yt(t),ht(t),Ne(e,t,n,ve(process.cwd(),n.path));const R=await Lt(e,{...o,author:t.author,message:t.message,force:t.force},n);return Ko(R,t.fullHistory===!0)}const r=Wt(),s=ve(process.cwd(),n.path);await Nt(s);const i=await Y(s);Ne(e,t,n,s),Oe(t.measure,"validation"),kt(t,[],void 0);const c=Gt(i,Dt()),d=await r.resolveList(t.add,"--add"),a=await r.resolveList(t.addJson,"--add-json"),u=await r.resolveList(t.remove,"--remove"),l=[...Jn(d),...Xe(a)],k=await _n(l,I(t.author,i.author_default),U())??[],w=Yn(u),T=Xn(t.removeIndex),_=await Fo({id:e,options:t,pmRoot:s,settings:i,typeToFolder:c.type_to_folder,adds:k,removes:w,removeIndexes:T}),g=ae(()=>ue(t,_.tests)),v=await Wo(t,s,_.tests),E=t.run===!0?U():void 0,P=await $o({options:t,runOptions:g,pmRoot:s,untrustedLinkedTestsPolicyEnabled:i.testing.allow_untrusted_linked_tests});mn(e,t,n,s,P);const O=Rt(P),m=t.run===!0&&t.failOnSkipped===!0&&P.some(R=>R.status==="skipped"),C=Do(t,P);v&&C.push(`linked_test_trust_acknowledged:${v.acknowledged}`);const S=await Go({options:t,pmRoot:s,settings:i,itemId:_.itemId,runStartedAt:E,runResults:P,failOnSkippedTriggered:m,warnings:C}),y=S?.receipt.recorded?zt([..._.testRuns,S.entry]):_.testRuns,L=kt(t,y,S?.entry);return qo({item:_,runResults:P,failureCategories:O,runSelection:g.runSelection,failOnSkippedTriggered:m,warnings:C,recording:S,measurementProjection:L,restoreScope:Pt(n,s),ran:t.run===!0,fullHistory:t.fullHistory===!0})}const Nr={buildLinkedTestExecutionContext:ft,buildPmContextMismatchHint:Be,commandInvokesPmCli:Je,commandInvokesPmTrackerReadCommand:ne,commandUsesTestNameFilter:at,copyIntoSandboxIfPresent:A,countLinkedTestItemFiles:M,ensureScope:Ge,evaluateLinkedTestAssertions:ct,endLinkedTestProgress:et,extractPmInvocationArgsFromSegment:te,firstDirectTestRunnerSubcommand:oe,formatLinkedTestExecutionError:ot,hasLinkedTestAssertions:He,initializeLinkedTestSandboxes:lt,linkedTestsRequireTrackerData:mt,parseAddJsonEntries:Xe,parseLinkedTestTimeoutSeconds:Ye,parsePmContextMode:N,readJsonPathValue:K,resolveAuthor:I,resolveDirectRunnerSubcommand:$,resolveLinkedTestEffectiveContextMode:ee,resolveLinkedTestFailureExitCode:it,resolveLinkedTestRequestedContextMode:Z,resolveTestRunOptions:ue,resolveTrackedRunId:De,runLinkedTestCommand:nt,seedMissingLinkedTestSettingsHistory:de,seedLinkedTestSandbox:ie,seedLinkedTestTrackerData:ce,segmentInvokesRecursiveTestAll:Hn,splitJsonPathSegments:xt,summarizeRunResultStatuses:Ue};export{Nr as _testOnlyTestCommand,Ar as classifyLinkedTestCommandSafety,so as classifyLinkedTestFailure,Dr as countFailureCategories,Gr as extractReferencedPmItemIdsFromCommand,it as resolveLinkedTestFailureExitCode,bo as runLinkedTests,jr as runTest,Rn as summarizeContextPreflight};
6
6
  //# sourceMappingURL=execution.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]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function splitJsonPathSegments(fieldPath){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(fieldPath))return[];const segments=[],tokens=fieldPath.matchAll(/[^.[\]]+|\[\d+\]/g);for(const[token]of tokens){if(token.startsWith("[")&&token.endsWith("]")){const parsedIndex=Number.parseInt(token.slice(1,-1),10);if(!Number.isSafeInteger(parsedIndex))return[];segments.push(parsedIndex);continue}segments.push(token)}return segments}function readJsonPathValue(root,fieldPath){const normalizedPath=fieldPath.trim();if(normalizedPath.length===0)return{found:!1,value:void 0};const segments=splitJsonPathSegments(normalizedPath);if(segments.length===0)return{found:!1,value:void 0};let current=root;for(const segment of segments){if(typeof current!="object"||current===null)return{found:!1,value:void 0};if(typeof segment=="number"&&(!Array.isArray(current)||segment>=current.length))return{found:!1,value:void 0};const property=Object.getOwnPropertyDescriptor(current,segment);if(!property||!Object.hasOwn(property,"value"))return{found:!1,value:void 0};current=property.value}return{found:!0,value:current}}export{readJsonPathValue,splitJsonPathSegments};
1
+ function f(r){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(r))return[];const t=[],u=r.matchAll(/[^.[\]]+|\[\d+\]/g);for(const[n]of u){if(n.startsWith("[")&&n.endsWith("]")){const e=Number.parseInt(n.slice(1,-1),10);if(!Number.isSafeInteger(e))return[];t.push(e);continue}t.push(n)}return t}function a(r,t){const u=t.trim();if(u.length===0)return{found:!1,value:void 0};const n=f(u);if(n.length===0)return{found:!1,value:void 0};let e=r;for(const s of n){if(typeof e!="object"||e===null)return{found:!1,value:void 0};if(typeof s=="number"&&(!Array.isArray(e)||s>=e.length))return{found:!1,value:void 0};const o=Object.getOwnPropertyDescriptor(e,s);if(!o||!Object.hasOwn(o,"value"))return{found:!1,value:void 0};e=o.value}return{found:!0,value:e}}export{a as readJsonPathValue,f as splitJsonPathSegments};
2
2
  //# sourceMappingURL=json-path.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]="d88c7294-44f1-5b65-9467-f94ed2db11ca")}catch{}})();import{readFileSync}from"node:fs";import path from"node:path";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";const PM_SUBCOMMANDS_WITH_ITEM_REFERENCE=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),PM_GLOBAL_FLAGS_WITH_VALUE=new Set(["--pm-path","--path","--author","--expect-hash"]),PM_ITEM_REFERENCE_FLAGS_WITH_VALUE={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},NPX_FLAGS_WITH_VALUE=new Set(["-p","--package"]),NPX_COMMAND_STRING_FLAGS=new Set(["-c","--call"]),PNPM_GLOBAL_FLAGS_WITH_VALUE=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),NPM_GLOBAL_FLAGS_WITH_VALUE=new Set(["-C","--prefix","--userconfig","--cache"]),YARN_GLOBAL_FLAGS_WITH_VALUE=new Set(["--cwd"]),BUN_GLOBAL_FLAGS_WITH_VALUE=new Set(["--cwd"]),NPM_EXEC_SUBCOMMANDS=new Set(["exec","x"]),SCRIPT_RUN_SUBCOMMANDS=new Set(["run","run-script"]),SCRIPT_RUN_FLAGS_WITH_VALUE=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function splitNormalizedCommandSegments(normalizedCommand){return normalizedCommand.split(/&&|\|\||\||;/).map(segment=>segment.trim()).filter(segment=>segment.length>0)}function extractPmInvocationArgsFromSegment(segment,cwd=process.cwd()){const tokens=stripLeadingEnvAssignments(segment.split(" ").filter(token=>token.length>0));if(tokens.length===0)return null;const[executable,...args]=tokens;if(isPmExecutableToken(executable)||isPmCliScriptToken(executable,cwd))return args;if(executable==="node"&&args[0]&&isPmCliScriptToken(args[0],cwd))return args.slice(1);const invocation=executable==="npx"||executable==="bunx"?parseNpxCommand(args):executable==="pnpm"?parsePnpmDlxCommand(args):executable==="npm"?parseNpmExecCommand(args):null;return invocation&&(isPmExecutableToken(invocation.command)||isPmCliPackageToken(invocation.command))?invocation.args:null}const extractReferencedPmItemIdsFromCommand=(command,idPrefix="pm")=>{const lowered=idPrefix.trim().toLowerCase();let prefixEnd=lowered.length;for(;prefixEnd>0&&lowered[prefixEnd-1]==="-";)prefixEnd-=1;const normalizedPrefix=lowered.slice(0,prefixEnd);if(normalizedPrefix.length===0)return[];const normalizedCommand=command.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),ids=new Set;for(const segment of splitNormalizedCommandSegments(normalizedCommand)){const invocationArgs=extractPmInvocationArgsFromSegment(segment),context=invocationArgs?resolvePmSubcommandContext(invocationArgs):null,candidate=context&&PM_SUBCOMMANDS_WITH_ITEM_REFERENCE.has(context.subcommand)?firstPositionalToken(context.remaining,PM_ITEM_REFERENCE_FLAGS_WITH_VALUE[context.subcommand]):void 0,normalizedCandidate=candidate?.trim().toLowerCase();normalizedCandidate?.startsWith(`${normalizedPrefix}-`)===!0&&normalizedCandidate.length>normalizedPrefix.length+1&&ids.add(candidate)}return[...ids].sort((left,right)=>left.localeCompare(right))};function stripLeadingEnvAssignments(tokens){let start=0;for(tokens[start]==="env"&&(start+=1);start<tokens.length;){const token=tokens[start];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(token)){start+=1;continue}break}return tokens.slice(start)}function firstPmSubcommand(args){let index=0;for(;index<args.length;){const token=args[index];if(token==="--"){index+=1;continue}if(token.startsWith("-")){if(PM_GLOBAL_FLAGS_WITH_VALUE.has(token)){index+=2;continue}index+=1;continue}return token}}function isPmExecutableToken(token){return token==="pm"||token==="pm.cmd"||token==="pm.exe"||token.endsWith("/pm")||token.endsWith("/pm.cmd")||token.endsWith("/pm.exe")}function normalizePackageSpecifier(token){const trimmed=token.trim();if(!trimmed.startsWith("@")){const versionSeparator2=trimmed.indexOf("@");return versionSeparator2===-1?trimmed:trimmed.slice(0,versionSeparator2)}const scopeSeparator=trimmed.indexOf("/");if(scopeSeparator===-1)return trimmed;const versionSeparator=trimmed.indexOf("@",scopeSeparator+1);return versionSeparator===-1?trimmed:trimmed.slice(0,versionSeparator)}function isPmCliPackageToken(token){const normalizedSpecifier=normalizePackageSpecifier(token);return normalizedSpecifier==="pm-cli"||normalizedSpecifier.endsWith("/pm-cli")||token==="pm-cli"||token.endsWith("/pm-cli")}function isPmCliScriptToken(token,cwd=process.cwd()){const normalized=token.replaceAll("\\","/");if(normalized!=="dist/cli.js"&&normalized!=="./dist/cli.js"&&!normalized.endsWith("/dist/cli.js"))return!1;const scriptPath=path.resolve(cwd,token);try{return JSON.parse(readFileSync(path.join(path.dirname(path.dirname(scriptPath)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function parseNpxCommand(tokens){let index=0;for(;index<tokens.length;){const token=tokens[index];if(token==="--"){index+=1;break}if(!token.startsWith("-"))break;const inlineCommandMatch=/^(?:-c|--call)=(.*)$/.exec(token);if(inlineCommandMatch){const command2=inlineCommandMatch[1];return command2?{command:command2,args:tokens.slice(index+1)}:null}if(NPX_COMMAND_STRING_FLAGS.has(token)){index+=1;break}index+=NPX_FLAGS_WITH_VALUE.has(token)&&!token.includes("=")?2:1}const command=tokens[index];return command?{command,args:tokens.slice(index+1)}:null}function parseLauncherSubcommand(tokens,flagsWithValue){let index=0;for(;index<tokens.length;){const token=tokens[index];if(token==="--"){index+=1;continue}if(token.startsWith("-")){if(token.includes("=")){index+=1;continue}if(flagsWithValue.has(token)){index+=2;continue}index+=1;continue}return{subcommand:token,args:tokens.slice(index+1)}}return null}function parsePnpmDlxCommand(tokens){const parsed=parseLauncherSubcommand(tokens,PNPM_GLOBAL_FLAGS_WITH_VALUE);return parsed?.subcommand!=="dlx"?null:parseNpxCommand(parsed.args)}function parseNpmExecCommand(tokens){const parsed=parseLauncherSubcommand(tokens,NPM_GLOBAL_FLAGS_WITH_VALUE);return!parsed||!NPM_EXEC_SUBCOMMANDS.has(parsed.subcommand)?null:parseNpxCommand(parsed.args)}function resolvePmSubcommandContext(args){let index=0;for(;index<args.length;){const token=args[index];if(token==="--"){index+=1;continue}if(token.startsWith("-")){if(PM_GLOBAL_FLAGS_WITH_VALUE.has(token)){index+=2;continue}index+=1;continue}return{subcommand:token,remaining:args.slice(index+1)}}return null}function firstPositionalToken(tokens,flagsWithValue=new Set){for(let index=0;index<tokens.length;index+=1){const token=tokens[index];if(token==="--")return tokens[index+1];if(!token.startsWith("-"))return token;!token.includes("=")&&(PM_GLOBAL_FLAGS_WITH_VALUE.has(token)||flagsWithValue.has(token))&&(index+=1)}}function parsedLauncherInvokesRecursiveTestAll(parsed){return!parsed||!isPmExecutableToken(parsed.command)&&!isPmCliPackageToken(parsed.command)?!1:firstPmSubcommand(parsed.args)==="test-all"}const SHELL_COMMAND_FLAG_PATTERNS=new Map([...["sh","bash","dash","zsh"].map(executable=>[executable,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(executable=>[executable,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(executable=>[executable,/^-(?:c|command)$/u])]),PACKAGE_EXEC_EXECUTABLES=new Set(["npx","bunx"]);function segmentInvokesRecursiveTestAll(segment){const rawTokens=segment.split(" ").filter(token=>token.length>0),tokens=stripLeadingEnvAssignments(rawTokens);if(tokens.length===0)return!1;const[executable,...args]=tokens,shellCommandFlagPattern=SHELL_COMMAND_FLAG_PATTERNS.get(executable);if(shellCommandFlagPattern){const commandFlagIndex=args.findIndex(arg=>shellCommandFlagPattern.test(arg));return commandFlagIndex>=0?segmentInvokesRecursiveTestAll(args.slice(commandFlagIndex+1).join(" ")):!1}return isPmExecutableToken(executable)||isPmCliScriptToken(executable)?firstPmSubcommand(args)==="test-all":executable==="node"&&args.length>0&&isPmCliScriptToken(args[0])?firstPmSubcommand(args.slice(1))==="test-all":PACKAGE_EXEC_EXECUTABLES.has(executable)?parsedLauncherInvokesRecursiveTestAll(parseNpxCommand(args)):executable==="pnpm"?parsedLauncherInvokesRecursiveTestAll(parsePnpmDlxCommand(args)):executable==="npm"?parsedLauncherInvokesRecursiveTestAll(parseNpmExecCommand(args)):!1}function invokesRecursiveTestAllCommand(command){const normalized=normalizeCommandForValidation(command);return splitNormalizedCommandSegments(normalized).some(segment=>segmentInvokesRecursiveTestAll(segment))}function assertNoRecursiveTestAllCommand(command){if(invokesRecursiveTestAllCommand(command))throw new PmCliError('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',EXIT_CODE.USAGE)}function normalizeCommandForValidation(command){return command.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}export{BUN_GLOBAL_FLAGS_WITH_VALUE,NPM_EXEC_SUBCOMMANDS,NPM_GLOBAL_FLAGS_WITH_VALUE,NPX_COMMAND_STRING_FLAGS,NPX_FLAGS_WITH_VALUE,PM_GLOBAL_FLAGS_WITH_VALUE,PM_ITEM_REFERENCE_FLAGS_WITH_VALUE,PNPM_GLOBAL_FLAGS_WITH_VALUE,SCRIPT_RUN_FLAGS_WITH_VALUE,SCRIPT_RUN_SUBCOMMANDS,SHELL_COMMAND_FLAG_PATTERNS,YARN_GLOBAL_FLAGS_WITH_VALUE,assertNoRecursiveTestAllCommand,extractPmInvocationArgsFromSegment,extractReferencedPmItemIdsFromCommand,firstPmSubcommand,firstPositionalToken,invokesRecursiveTestAllCommand,isPmCliPackageToken,isPmCliScriptToken,isPmExecutableToken,normalizeCommandForValidation,normalizePackageSpecifier,parseLauncherSubcommand,parseNpmExecCommand,parseNpxCommand,parsePnpmDlxCommand,resolvePmSubcommandContext,segmentInvokesRecursiveTestAll,splitNormalizedCommandSegments,stripLeadingEnvAssignments};
1
+ import{readFileSync as E}from"node:fs";import m from"node:path";import{EXIT_CODE as P}from"../../core/shared/constants.js";import{PmCliError as T}from"../../core/shared/errors.js";const N=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),f=new Set(["--pm-path","--path","--author","--expect-hash"]),k={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},y=new Set(["-p","--package"]),I=new Set(["-c","--call"]),W=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),M=new Set(["-C","--prefix","--userconfig","--cache"]),J=new Set(["--cwd"]),K=new Set(["--cwd"]),F=new Set(["exec","x"]),Y=new Set(["run","run-script"]),q=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function S(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function G(e,t=process.cwd()){const n=w(e.split(" ").filter(i=>i.length>0));if(n.length===0)return null;const[r,...s]=n;if(d(r)||p(r,t))return s;if(r==="node"&&s[0]&&p(s[0],t))return s.slice(1);const o=r==="npx"||r==="bunx"?u(s):r==="pnpm"?L(s):r==="npm"?C(s):null;return o&&(d(o.command)||A(o.command))?o.args:null}const Q=(e,t="pm")=>{const n=t.trim().toLowerCase();let r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;const s=n.slice(0,r);if(s.length===0)return[];const o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),i=new Set;for(const a of S(o)){const c=G(a),l=c?R(c):null,h=l&&N.has(l.subcommand)?U(l.remaining,k[l.subcommand]):void 0,_=h?.trim().toLowerCase();_?.startsWith(`${s}-`)===!0&&_.length>s.length+1&&i.add(h)}return[...i].sort((a,c)=>a.localeCompare(c))};function w(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){const n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function g(e){let t=0;for(;t<e.length;){const n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(f.has(n)){t+=2;continue}t+=1;continue}return n}}function d(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function z(e){const t=e.trim();if(!t.startsWith("@")){const s=t.indexOf("@");return s===-1?t:t.slice(0,s)}const n=t.indexOf("/");if(n===-1)return t;const r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function A(e){const t=z(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function p(e,t=process.cwd()){const n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;const r=m.resolve(t,e);try{return JSON.parse(E(m.join(m.dirname(m.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function u(e){let t=0;for(;t<e.length;){const r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;const s=/^(?:-c|--call)=(.*)$/.exec(r);if(s){const o=s[1];return o?{command:o,args:e.slice(t+1)}:null}if(I.has(r)){t+=1;break}t+=y.has(r)&&!r.includes("=")?2:1}const n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function v(e,t){let n=0;for(;n<e.length;){const r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function L(e){const t=v(e,W);return t?.subcommand!=="dlx"?null:u(t.args)}function C(e){const t=v(e,M);return!t||!F.has(t.subcommand)?null:u(t.args)}function R(e){let t=0;for(;t<e.length;){const n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(f.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function U(e,t=new Set){for(let n=0;n<e.length;n+=1){const r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(f.has(r)||t.has(r))&&(n+=1)}}function x(e){return!e||!d(e.command)&&!A(e.command)?!1:g(e.args)==="test-all"}const O=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),B=new Set(["npx","bunx"]);function b(e){const t=e.split(" ").filter(i=>i.length>0),n=w(t);if(n.length===0)return!1;const[r,...s]=n,o=O.get(r);if(o){const i=s.findIndex(a=>o.test(a));return i>=0?b(s.slice(i+1).join(" ")):!1}return d(r)||p(r)?g(s)==="test-all":r==="node"&&s.length>0&&p(s[0])?g(s.slice(1))==="test-all":B.has(r)?x(u(s)):r==="pnpm"?x(L(s)):r==="npm"?x(C(s)):!1}function H(e){const t=V(e);return S(t).some(n=>b(n))}function Z(e){if(H(e))throw new T('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',P.USAGE)}function V(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}export{K as BUN_GLOBAL_FLAGS_WITH_VALUE,F as NPM_EXEC_SUBCOMMANDS,M as NPM_GLOBAL_FLAGS_WITH_VALUE,I as NPX_COMMAND_STRING_FLAGS,y as NPX_FLAGS_WITH_VALUE,f as PM_GLOBAL_FLAGS_WITH_VALUE,k as PM_ITEM_REFERENCE_FLAGS_WITH_VALUE,W as PNPM_GLOBAL_FLAGS_WITH_VALUE,q as SCRIPT_RUN_FLAGS_WITH_VALUE,Y as SCRIPT_RUN_SUBCOMMANDS,O as SHELL_COMMAND_FLAG_PATTERNS,J as YARN_GLOBAL_FLAGS_WITH_VALUE,Z as assertNoRecursiveTestAllCommand,G as extractPmInvocationArgsFromSegment,Q as extractReferencedPmItemIdsFromCommand,g as firstPmSubcommand,U as firstPositionalToken,H as invokesRecursiveTestAllCommand,A as isPmCliPackageToken,p as isPmCliScriptToken,d as isPmExecutableToken,V as normalizeCommandForValidation,z as normalizePackageSpecifier,v as parseLauncherSubcommand,C as parseNpmExecCommand,u as parseNpxCommand,L as parsePnpmDlxCommand,R as resolvePmSubcommandContext,b as segmentInvokesRecursiveTestAll,S as splitNormalizedCommandSegments,w as stripLeadingEnvAssignments};
2
2
  //# sourceMappingURL=linked-command-detection.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]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();import{EXIT_CODE,PmCliError}from"../runtime-primitives.js";const TEST_RUN_MEASUREMENT_LIMIT=32;function splitTestRunMeasurementSpecs(values){const specs=[];for(const raw of values??[]){let current=[];for(const segment of raw.split(",")){const key=segment.slice(0,segment.indexOf("=")).trim();current.length>0&&key!=="unit"&&key!=="threshold"&&(specs.push(current.join(",")),current=[]),current.push(segment)}specs.push(current.join(","))}return specs}function parseTestRunMeasurements(values,recordedAt){const measurements=splitTestRunMeasurementSpecs(values).map(raw=>{const[metricPair,...attributes]=raw.split(","),separator=metricPair.indexOf("="),name=metricPair.slice(0,separator).trim(),valueText=metricPair.slice(separator+1).trim(),value=Number(valueText);if(separator<=0||name.length===0||valueText.length===0||!Number.isFinite(value))throw new PmCliError(`Invalid --measure "${raw}"; expected name=value[,unit=...][,threshold=...]`,EXIT_CODE.USAGE);let unit,threshold;for(const attribute of attributes){const attributeSeparator=attribute.indexOf("="),key=attribute.slice(0,attributeSeparator).trim(),attributeValue=attribute.slice(attributeSeparator+1).trim();if(key==="unit"&&attributeValue.length>0)unit=attributeValue;else if(key==="threshold"&&attributeValue.length>0&&Number.isFinite(Number(attributeValue)))threshold=Number(attributeValue);else throw new PmCliError(`Invalid --measure attribute "${attribute}"`,EXIT_CODE.USAGE)}return{name,value,unit,threshold,recorded_at:recordedAt}});return[...new Map(measurements.map(measurement=>[measurement.name,measurement])).values()].sort((left,right)=>left.name.localeCompare(right.name)).slice(0,TEST_RUN_MEASUREMENT_LIMIT)}function queryTestRunMeasurementsBelow(runs,name,threshold){return runs.flatMap(run=>(run.measurements??[]).filter(measurement=>measurement.name===name&&measurement.value<threshold).map(measurement=>({...measurement,run_id:run.run_id})))}function diffTestRunMeasurements(runs,name){const values=runs.flatMap(run=>run.measurements??[]).filter(measurement=>measurement.name===name).sort((left,right)=>right.recorded_at.localeCompare(left.recorded_at)),latest=values[0],previous=values[1];return{name,latest:latest?.value??null,previous:previous?.value??null,delta:latest!==void 0&&previous!==void 0?latest.value-previous.value:null,unit:latest?.unit}}export{TEST_RUN_MEASUREMENT_LIMIT,diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow};
1
+ import{EXIT_CODE as b,PmCliError as M}from"../runtime-primitives.js";const T=32;function x(u){const r=[];for(const s of u??[]){let t=[];for(const e of s.split(",")){const n=e.slice(0,e.indexOf("=")).trim();t.length>0&&n!=="unit"&&n!=="threshold"&&(r.push(t.join(",")),t=[]),t.push(e)}r.push(t.join(","))}return r}function _(u,r){const s=x(u).map(e=>{const[n,...a]=e.split(","),l=n.indexOf("="),c=n.slice(0,l).trim(),m=n.slice(l+1).trim(),d=Number(m);if(l<=0||c.length===0||m.length===0||!Number.isFinite(d))throw new M(`Invalid --measure "${e}"; expected name=value[,unit=...][,threshold=...]`,b.USAGE);let p,f;for(const o of a){const h=o.indexOf("="),v=o.slice(0,h).trim(),i=o.slice(h+1).trim();if(v==="unit"&&i.length>0)p=i;else if(v==="threshold"&&i.length>0&&Number.isFinite(Number(i)))f=Number(i);else throw new M(`Invalid --measure attribute "${o}"`,b.USAGE)}return{name:c,value:d,unit:p,threshold:f,recorded_at:r}});return[...new Map(s.map(e=>[e.name,e])).values()].sort((e,n)=>e.name.localeCompare(n.name)).slice(0,T)}function N(u,r,s){return u.flatMap(t=>(t.measurements??[]).filter(e=>e.name===r&&e.value<s).map(e=>({...e,run_id:t.run_id})))}function g(u,r){const s=u.flatMap(n=>n.measurements??[]).filter(n=>n.name===r).sort((n,a)=>a.recorded_at.localeCompare(n.recorded_at)),t=s[0],e=s[1];return{name:r,latest:t?.value??null,previous:e?.value??null,delta:t!==void 0&&e!==void 0?t.value-e.value:null,unit:t?.unit}}export{T as TEST_RUN_MEASUREMENT_LIMIT,g as diffTestRunMeasurements,_ as parseTestRunMeasurements,N as queryTestRunMeasurementsBelow};
2
2
  //# sourceMappingURL=measurements.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]="ef8e6aec-bd75-5615-bcda-a51d055b65d7")}catch{}})();import{parseOptionalNumber}from"../../core/item/parse.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{splitCommaList}from"../../core/shared/split-comma-list.js";import{STRUCTURED_LINKED_TEST_KEYS}from"./entry.js";import{parseLinkedTestPhase}from"./run-phases.js";import{SCOPE_VALUES}from"../../types/index.js";import{SOURCE_CONTEXT_ACCESS_ENV,SOURCE_CONTEXT_WRITE_OVERRIDE_ENV}from"../environment/source-context.js";const LINKED_TEST_PROTECTED_ENV_KEYS=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",SOURCE_CONTEXT_ACCESS_ENV,SOURCE_CONTEXT_WRITE_OVERRIDE_ENV,"FORCE_COLOR"]),LINKED_TEST_ENV_NAME_PATTERN=/^[A-Za-z_][A-Za-z0-9_]*$/,LINKED_TEST_PM_CONTEXT_MODE_VALUES=["schema","tracker","auto","none"],LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES=["source","isolated","snapshot"];function parseLinkedTestEnvSet(raw,optionName){if(!raw)return;const assignments=raw.split(/[;\n]/).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(assignments.length===0)throw new PmCliError(`${optionName} env_set must include at least one KEY=VALUE assignment`,EXIT_CODE.USAGE);const envSet=Object.create(null);for(const assignment of assignments){const separatorIndex=assignment.indexOf("=");if(separatorIndex<=0)throw new PmCliError(`${optionName} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,EXIT_CODE.USAGE);const key=assignment.slice(0,separatorIndex).trim(),value=assignment.slice(separatorIndex+1);if(!LINKED_TEST_ENV_NAME_PATTERN.test(key))throw new PmCliError(`${optionName} env_set key "${key}" is invalid`,EXIT_CODE.USAGE);if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase()))throw new PmCliError(`${optionName} env_set key "${key}" is reserved for sandbox safety`,EXIT_CODE.USAGE);envSet[key]=value}return Object.keys(envSet).length>0?envSet:void 0}function parseLinkedTestEnvClear(raw,optionName){if(!raw)return;const keys=splitCommaList(raw,{separators:/[;,\n]/});if(keys.length===0)throw new PmCliError(`${optionName} env_clear must include at least one environment variable name`,EXIT_CODE.USAGE);for(const key of keys){if(!LINKED_TEST_ENV_NAME_PATTERN.test(key))throw new PmCliError(`${optionName} env_clear key "${key}" is invalid`,EXIT_CODE.USAGE);if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase()))throw new PmCliError(`${optionName} env_clear key "${key}" is reserved for sandbox safety`,EXIT_CODE.USAGE)}return keys}function parseLinkedTestBoolean(raw,optionName,fieldLabel){if(!raw)return;const value=raw.trim().toLowerCase();if(value==="true"||value==="1"||value==="yes")return!0;if(value==="false"||value==="0"||value==="no")return!1;throw new PmCliError(`${optionName} ${fieldLabel} must be one of true|false|1|0|yes|no`,EXIT_CODE.USAGE)}function parseLinkedTestContextMode(raw,optionName){if(!raw)return;const value=raw.trim().toLowerCase();if(LINKED_TEST_PM_CONTEXT_MODE_VALUES.includes(value))return value;throw new PmCliError(`${optionName} pm_context_mode must be one of: ${LINKED_TEST_PM_CONTEXT_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseLinkedTestWorkspaceContextMode(raw,optionName){if(!raw)return;const value=raw.trim().toLowerCase();if(LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.includes(value))return value;throw new PmCliError(`${optionName} workspace_context_mode must be one of: ${LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}function parseLinkedTestStringList(raw){if(!raw)return;const values=splitCommaList(raw,{separators:/[;\n]/});return values.length>0?values:void 0}function parseLinkedTestRegexList(raw,optionName,fieldLabel){const values=parseLinkedTestStringList(raw);if(!(!values||values.length===0)){for(const pattern of values)try{new RegExp(pattern,"m")}catch(error){throw new PmCliError(`${optionName} ${fieldLabel} includes invalid regex "${pattern}": ${error instanceof Error?error.message:String(error)}`,EXIT_CODE.USAGE)}return values}}function parseLinkedTestMinLines(raw,optionName){if(!raw)return;const parsed=parseOptionalNumber(raw,"assert_stdout_min_lines");if(!Number.isInteger(parsed)||parsed<0)throw new PmCliError(`${optionName} assert_stdout_min_lines must be an integer >= 0`,EXIT_CODE.USAGE);return parsed}function parseLinkedTestAssertionEqualsMap(raw,optionName){if(!raw)return;const assignments=raw.split(/[;\n]/).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(assignments.length===0)throw new PmCliError(`${optionName} assert_json_field_equals must include at least one path=value assignment`,EXIT_CODE.USAGE);const values=Object.create(null);for(const assignment of assignments){const separatorIndex=assignment.indexOf("=");if(separatorIndex<=0)throw new PmCliError(`${optionName} assert_json_field_equals entries must use path=value and be separated by semicolons`,EXIT_CODE.USAGE);const key=assignment.slice(0,separatorIndex).trim(),value=assignment.slice(separatorIndex+1).trim();if(key.length===0||value.length===0)throw new PmCliError(`${optionName} assert_json_field_equals entries must include non-empty path and value`,EXIT_CODE.USAGE);values[key]=value}return Object.keys(values).length>0?values:void 0}function parseLinkedTestAssertionGteMap(raw,optionName){if(!raw)return;const assignments=raw.split(/[;\n]/).map(entry=>entry.trim()).filter(entry=>entry.length>0);if(assignments.length===0)throw new PmCliError(`${optionName} assert_json_field_gte must include at least one path=value assignment`,EXIT_CODE.USAGE);const values=Object.create(null);for(const assignment of assignments){const separatorIndex=assignment.indexOf("=");if(separatorIndex<=0)throw new PmCliError(`${optionName} assert_json_field_gte entries must use path=value and be separated by semicolons`,EXIT_CODE.USAGE);const key=assignment.slice(0,separatorIndex).trim(),valueRaw=assignment.slice(separatorIndex+1).trim();if(key.length===0||valueRaw.length===0)throw new PmCliError(`${optionName} assert_json_field_gte entries must include non-empty path and value`,EXIT_CODE.USAGE);const value=Number(valueRaw);if(!Number.isFinite(value))throw new PmCliError(`${optionName} assert_json_field_gte value for "${key}" must be numeric`,EXIT_CODE.USAGE);values[key]=value}return Object.keys(values).length>0?values:void 0}const LINKED_TEST_JSON_KEY_SET=new Set(STRUCTURED_LINKED_TEST_KEYS);function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function normalizeJsonEntryKeys(entry,fail){const normalized={},unknownKeys=[];for(const[key,value]of Object.entries(entry)){const normalizedKey=key.toLowerCase();if(!LINKED_TEST_JSON_KEY_SET.has(normalizedKey)){unknownKeys.push(key);continue}if(Object.hasOwn(normalized,normalizedKey))throw fail(`provides key "${key}" more than once after case normalization`);normalized[normalizedKey]=value}if(unknownKeys.length>0)throw fail(`does not recognize key${unknownKeys.length>1?"s":""} ${unknownKeys.map(key=>`"${key}"`).join(", ")}. Allowed keys: ${STRUCTURED_LINKED_TEST_KEYS.join(", ")}.`);return normalized}function readJsonEntryString(entry,key,fail){if(!Object.hasOwn(entry,key))return;const value=entry[key];if(value!==void 0){if(typeof value!="string")throw fail(`field "${key}" must be a JSON string`);return value}}function readJsonEntryStringList(entry,key,fail){if(!Object.hasOwn(entry,key))return;const value=entry[key];if(value===void 0)return;const list=typeof value=="string"?[value]:value;if(!Array.isArray(list)||list.some(item=>typeof item!="string"))throw fail(`field "${key}" must be a string or an array of strings`);const values=list.filter(item=>item.length>0);return values.length>0?values:void 0}function readJsonEntryRegexList(entry,key,fail){const values=readJsonEntryStringList(entry,key,fail);if(values){for(const pattern of values)try{new RegExp(pattern,"m")}catch(error){throw fail(`field "${key}" includes invalid regex "${pattern}": ${error instanceof Error?error.message:String(error)}`)}return values}}function readJsonEntryNumber(value,key,fail){const parsed=typeof value=="number"?value:typeof value=="string"&&value.trim().length>0?Number(value.trim()):Number.NaN;if(typeof value=="boolean"||!Number.isFinite(parsed))throw fail(`field "${key}" must be a finite number (or numeric string)`);return parsed}function readJsonEntryTimeoutSeconds(entry,fail){const timeoutSecondsRaw=entry.timeout_seconds,timeoutAliasRaw=entry.timeout;if(timeoutSecondsRaw===void 0&&timeoutAliasRaw===void 0)return;const timeoutSeconds=timeoutSecondsRaw===void 0?void 0:readJsonEntryNumber(timeoutSecondsRaw,"timeout_seconds",fail),timeoutAlias=timeoutAliasRaw===void 0?void 0:readJsonEntryNumber(timeoutAliasRaw,"timeout",fail);if(timeoutSeconds!==void 0&&timeoutAlias!==void 0&&timeoutSeconds!==timeoutAlias)throw fail("timeout and timeout_seconds must match when both are provided");const timeout=timeoutSeconds??timeoutAlias;if(!Number.isInteger(timeout)||timeout<=0)throw fail("timeout_seconds must be a positive integer");return timeout}function readJsonEntryScope(entry,fail){const value=readJsonEntryString(entry,"scope",fail);if(value===void 0)return"project";if(!SCOPE_VALUES.includes(value))throw fail(`field "scope" must be one of: ${SCOPE_VALUES.join(", ")}`);return value}function readJsonEntryEnvSet(entry,fail){if(!Object.hasOwn(entry,"env_set"))return;const value=entry.env_set;if(value===void 0)return;if(!isPlainObject(value))throw fail('field "env_set" must be a JSON object mapping environment names to string values');const envSet=Object.create(null);for(const[key,entryValue]of Object.entries(value)){if(typeof entryValue!="string")throw fail(`field "env_set" value for "${key}" must be a string`);if(!LINKED_TEST_ENV_NAME_PATTERN.test(key))throw fail(`field "env_set" key "${key}" is invalid`);if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase()))throw fail(`field "env_set" key "${key}" is reserved for sandbox safety`);envSet[key]=entryValue}return Object.keys(envSet).length>0?envSet:void 0}function readJsonEntryEnvClear(entry,fail){const keys=readJsonEntryStringList(entry,"env_clear",fail);if(keys){for(const key of keys){if(!LINKED_TEST_ENV_NAME_PATTERN.test(key))throw fail(`field "env_clear" key "${key}" is invalid`);if(LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase()))throw fail(`field "env_clear" key "${key}" is reserved for sandbox safety`)}return keys}}function readJsonEntryBoolean(entry,key,fail){if(!Object.hasOwn(entry,key))return;const value=entry[key];if(value!==void 0){if(typeof value!="boolean")throw fail(`field "${key}" must be a JSON boolean (true or false)`);return value}}function readJsonEntryMinLines(entry,fail){if(!Object.hasOwn(entry,"assert_stdout_min_lines"))return;const value=entry.assert_stdout_min_lines;if(value===void 0)return;const parsed=readJsonEntryNumber(value,"assert_stdout_min_lines",fail);if(!Number.isInteger(parsed)||parsed<0)throw fail('field "assert_stdout_min_lines" must be an integer >= 0');return parsed}function readJsonEntryEqualsMap(entry,fail){if(!Object.hasOwn(entry,"assert_json_field_equals"))return;const value=entry.assert_json_field_equals;if(value===void 0)return;if(!isPlainObject(value))throw fail('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');const values=Object.create(null);for(const[key,entryValue]of Object.entries(value)){if(key.trim().length===0)throw fail('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof entryValue!="string"&&typeof entryValue!="number"&&typeof entryValue!="boolean")throw fail(`field "assert_json_field_equals" value for "${key}" must be a string, number, or boolean`);values[key]=String(entryValue)}return Object.keys(values).length>0?values:void 0}function readJsonEntryGteMap(entry,fail){if(!Object.hasOwn(entry,"assert_json_field_gte"))return;const value=entry.assert_json_field_gte;if(value===void 0)return;if(!isPlainObject(value))throw fail('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');const values=Object.create(null);for(const[key,entryValue]of Object.entries(value)){if(key.trim().length===0)throw fail('field "assert_json_field_gte" keys must be non-empty field paths');values[key]=readJsonEntryNumber(entryValue,`assert_json_field_gte.${key}`,fail)}return Object.keys(values).length>0?values:void 0}function parseLinkedTestJsonEntry(rawEntry,label,optionName){const fail=message=>new PmCliError(`${optionName} ${label} ${message}`,EXIT_CODE.USAGE);if(!isPlainObject(rawEntry))throw fail(`must be a JSON object with linked-test fields. Allowed keys: ${STRUCTURED_LINKED_TEST_KEYS.join(", ")}.`);const entry=normalizeJsonEntryKeys(rawEntry,fail),commandValue=readJsonEntryString(entry,"command",fail),cmdAlias=readJsonEntryString(entry,"cmd",fail);if(commandValue!==void 0&&cmdAlias!==void 0&&commandValue!==cmdAlias)throw fail("command and cmd must match when both are provided");const command=commandValue??cmdAlias;if(command===void 0||command.trim().length===0)throw fail('requires a non-empty "command" string');const pathValue=readJsonEntryString(entry,"path",fail),pmContextModeValue=readJsonEntryString(entry,"pm_context_mode",fail);if(pmContextModeValue!==void 0&&!LINKED_TEST_PM_CONTEXT_MODE_VALUES.includes(pmContextModeValue))throw fail(`field "pm_context_mode" must be one of: ${LINKED_TEST_PM_CONTEXT_MODE_VALUES.join(", ")}`);const workspaceContextModeValue=parseLinkedTestWorkspaceContextMode(readJsonEntryString(entry,"workspace_context_mode",fail),`${optionName} ${label}`),noteValue=readJsonEntryString(entry,"note",fail);return{command,path:pathValue!==void 0&&pathValue.length>0?pathValue:void 0,scope:readJsonEntryScope(entry,fail),timeout_seconds:readJsonEntryTimeoutSeconds(entry,fail),pm_context_mode:pmContextModeValue,workspace_context_mode:workspaceContextModeValue,env_set:readJsonEntryEnvSet(entry,fail),env_clear:readJsonEntryEnvClear(entry,fail),shared_host_safe:readJsonEntryBoolean(entry,"shared_host_safe",fail),assert_stdout_contains:readJsonEntryStringList(entry,"assert_stdout_contains",fail),assert_stdout_regex:readJsonEntryRegexList(entry,"assert_stdout_regex",fail),assert_stderr_contains:readJsonEntryStringList(entry,"assert_stderr_contains",fail),assert_stderr_regex:readJsonEntryRegexList(entry,"assert_stderr_regex",fail),assert_stdout_min_lines:readJsonEntryMinLines(entry,fail),assert_json_field_equals:readJsonEntryEqualsMap(entry,fail),assert_json_field_gte:readJsonEntryGteMap(entry,fail),note:noteValue!==void 0&&noteValue.trim().length>0?noteValue.trim():void 0,phase:parseLinkedTestPhase(entry.phase,`${optionName} ${label}`)}}function parseLinkedTestJsonEntries(raw,optionName){const trimmed=raw.trim();if(trimmed.length===0)throw new PmCliError(`${optionName} requires a JSON object or array of objects describing linked-test entries`,EXIT_CODE.USAGE);let parsed;try{parsed=JSON.parse(trimmed)}catch(error){throw new PmCliError(`${optionName} value is not valid JSON: ${error instanceof Error?error.message:String(error)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,EXIT_CODE.USAGE)}const entries=Array.isArray(parsed)?parsed:[parsed];if(entries.length===0)throw new PmCliError(`${optionName} array must include at least one linked-test entry object`,EXIT_CODE.USAGE);return entries.map((entry,index)=>parseLinkedTestJsonEntry(entry,entries.length>1?`entry ${index+1}`:"entry",optionName))}const _testOnlyLinkedTestParsers={parseLinkedTestJsonEntry};export{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,_testOnlyLinkedTestParsers,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode};
1
+ import{parseOptionalNumber as T}from"../../core/item/parse.js";import{EXIT_CODE as a}from"../../core/shared/constants.js";import{PmCliError as d}from"../../core/shared/errors.js";import{splitCommaList as y}from"../../core/shared/split-comma-list.js";import{STRUCTURED_LINKED_TEST_KEYS as b}from"./entry.js";import{parseLinkedTestPhase as k}from"./run-phases.js";import{SCOPE_VALUES as S}from"../../types/index.js";import{SOURCE_CONTEXT_ACCESS_ENV as x,SOURCE_CONTEXT_WRITE_OVERRIDE_ENV as L}from"../environment/source-context.js";const l=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",x,L,"FORCE_COLOR"]),_=/^[A-Za-z_][A-Za-z0-9_]*$/,m=["schema","tracker","auto","none"],O=["source","isolated","snapshot"];function Z(s,t){if(!s)return;const r=s.split(/[;\n]/).map(n=>n.trim()).filter(n=>n.length>0);if(r.length===0)throw new d(`${t} env_set must include at least one KEY=VALUE assignment`,a.USAGE);const e=Object.create(null);for(const n of r){const o=n.indexOf("=");if(o<=0)throw new d(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,a.USAGE);const i=n.slice(0,o).trim(),u=n.slice(o+1);if(!_.test(i))throw new d(`${t} env_set key "${i}" is invalid`,a.USAGE);if(l.has(i.toUpperCase()))throw new d(`${t} env_set key "${i}" is reserved for sandbox safety`,a.USAGE);e[i]=u}return Object.keys(e).length>0?e:void 0}function Q(s,t){if(!s)return;const r=y(s,{separators:/[;,\n]/});if(r.length===0)throw new d(`${t} env_clear must include at least one environment variable name`,a.USAGE);for(const e of r){if(!_.test(e))throw new d(`${t} env_clear key "${e}" is invalid`,a.USAGE);if(l.has(e.toUpperCase()))throw new d(`${t} env_clear key "${e}" is reserved for sandbox safety`,a.USAGE)}return r}function ee(s,t,r){if(!s)return;const e=s.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes")return!0;if(e==="false"||e==="0"||e==="no")return!1;throw new d(`${t} ${r} must be one of true|false|1|0|yes|no`,a.USAGE)}function te(s,t){if(!s)return;const r=s.trim().toLowerCase();if(m.includes(r))return r;throw new d(`${t} pm_context_mode must be one of: ${m.join(", ")}`,a.USAGE)}function U(s,t){if(!s)return;const r=s.trim().toLowerCase();if(O.includes(r))return r;throw new d(`${t} workspace_context_mode must be one of: ${O.join(", ")}`,a.USAGE)}function C(s){if(!s)return;const t=y(s,{separators:/[;\n]/});return t.length>0?t:void 0}function ne(s,t,r){const e=C(s);if(!(!e||e.length===0)){for(const n of e)try{new RegExp(n,"m")}catch(o){throw new d(`${t} ${r} includes invalid regex "${n}": ${o instanceof Error?o.message:String(o)}`,a.USAGE)}return e}}function se(s,t){if(!s)return;const r=T(s,"assert_stdout_min_lines");if(!Number.isInteger(r)||r<0)throw new d(`${t} assert_stdout_min_lines must be an integer >= 0`,a.USAGE);return r}function re(s,t){if(!s)return;const r=s.split(/[;\n]/).map(n=>n.trim()).filter(n=>n.length>0);if(r.length===0)throw new d(`${t} assert_json_field_equals must include at least one path=value assignment`,a.USAGE);const e=Object.create(null);for(const n of r){const o=n.indexOf("=");if(o<=0)throw new d(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,a.USAGE);const i=n.slice(0,o).trim(),u=n.slice(o+1).trim();if(i.length===0||u.length===0)throw new d(`${t} assert_json_field_equals entries must include non-empty path and value`,a.USAGE);e[i]=u}return Object.keys(e).length>0?e:void 0}function oe(s,t){if(!s)return;const r=s.split(/[;\n]/).map(n=>n.trim()).filter(n=>n.length>0);if(r.length===0)throw new d(`${t} assert_json_field_gte must include at least one path=value assignment`,a.USAGE);const e=Object.create(null);for(const n of r){const o=n.indexOf("=");if(o<=0)throw new d(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,a.USAGE);const i=n.slice(0,o).trim(),u=n.slice(o+1).trim();if(i.length===0||u.length===0)throw new d(`${t} assert_json_field_gte entries must include non-empty path and value`,a.USAGE);const c=Number(u);if(!Number.isFinite(c))throw new d(`${t} assert_json_field_gte value for "${i}" must be numeric`,a.USAGE);e[i]=c}return Object.keys(e).length>0?e:void 0}const R=new Set(b);function h(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function G(s,t){const r={},e=[];for(const[n,o]of Object.entries(s)){const i=n.toLowerCase();if(!R.has(i)){e.push(n);continue}if(Object.hasOwn(r,i))throw t(`provides key "${n}" more than once after case normalization`);r[i]=o}if(e.length>0)throw t(`does not recognize key${e.length>1?"s":""} ${e.map(n=>`"${n}"`).join(", ")}. Allowed keys: ${b.join(", ")}.`);return r}function f(s,t,r){if(!Object.hasOwn(s,t))return;const e=s[t];if(e!==void 0){if(typeof e!="string")throw r(`field "${t}" must be a JSON string`);return e}}function p(s,t,r){if(!Object.hasOwn(s,t))return;const e=s[t];if(e===void 0)return;const n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||n.some(i=>typeof i!="string"))throw r(`field "${t}" must be a string or an array of strings`);const o=n.filter(i=>i.length>0);return o.length>0?o:void 0}function v(s,t,r){const e=p(s,t,r);if(e){for(const n of e)try{new RegExp(n,"m")}catch(o){throw r(`field "${t}" includes invalid regex "${n}": ${o instanceof Error?o.message:String(o)}`)}return e}}function E(s,t,r){const e=typeof s=="number"?s:typeof s=="string"&&s.trim().length>0?Number(s.trim()):Number.NaN;if(typeof s=="boolean"||!Number.isFinite(e))throw r(`field "${t}" must be a finite number (or numeric string)`);return e}function J(s,t){const r=s.timeout_seconds,e=s.timeout;if(r===void 0&&e===void 0)return;const n=r===void 0?void 0:E(r,"timeout_seconds",t),o=e===void 0?void 0:E(e,"timeout",t);if(n!==void 0&&o!==void 0&&n!==o)throw t("timeout and timeout_seconds must match when both are provided");const i=n??o;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function N(s,t){const r=f(s,"scope",t);if(r===void 0)return"project";if(!S.includes(r))throw t(`field "scope" must be one of: ${S.join(", ")}`);return r}function M(s,t){if(!Object.hasOwn(s,"env_set"))return;const r=s.env_set;if(r===void 0)return;if(!h(r))throw t('field "env_set" must be a JSON object mapping environment names to string values');const e=Object.create(null);for(const[n,o]of Object.entries(r)){if(typeof o!="string")throw t(`field "env_set" value for "${n}" must be a string`);if(!_.test(n))throw t(`field "env_set" key "${n}" is invalid`);if(l.has(n.toUpperCase()))throw t(`field "env_set" key "${n}" is reserved for sandbox safety`);e[n]=o}return Object.keys(e).length>0?e:void 0}function P(s,t){const r=p(s,"env_clear",t);if(r){for(const e of r){if(!_.test(e))throw t(`field "env_clear" key "${e}" is invalid`);if(l.has(e.toUpperCase()))throw t(`field "env_clear" key "${e}" is reserved for sandbox safety`)}return r}}function I(s,t,r){if(!Object.hasOwn(s,t))return;const e=s[t];if(e!==void 0){if(typeof e!="boolean")throw r(`field "${t}" must be a JSON boolean (true or false)`);return e}}function V(s,t){if(!Object.hasOwn(s,"assert_stdout_min_lines"))return;const r=s.assert_stdout_min_lines;if(r===void 0)return;const e=E(r,"assert_stdout_min_lines",t);if(!Number.isInteger(e)||e<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return e}function K(s,t){if(!Object.hasOwn(s,"assert_json_field_equals"))return;const r=s.assert_json_field_equals;if(r===void 0)return;if(!h(r))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');const e=Object.create(null);for(const[n,o]of Object.entries(r)){if(n.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")throw t(`field "assert_json_field_equals" value for "${n}" must be a string, number, or boolean`);e[n]=String(o)}return Object.keys(e).length>0?e:void 0}function D(s,t){if(!Object.hasOwn(s,"assert_json_field_gte"))return;const r=s.assert_json_field_gte;if(r===void 0)return;if(!h(r))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');const e=Object.create(null);for(const[n,o]of Object.entries(r)){if(n.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');e[n]=E(o,`assert_json_field_gte.${n}`,t)}return Object.keys(e).length>0?e:void 0}function $(s,t,r){const e=A=>new d(`${r} ${t} ${A}`,a.USAGE);if(!h(s))throw e(`must be a JSON object with linked-test fields. Allowed keys: ${b.join(", ")}.`);const n=G(s,e),o=f(n,"command",e),i=f(n,"cmd",e);if(o!==void 0&&i!==void 0&&o!==i)throw e("command and cmd must match when both are provided");const u=o??i;if(u===void 0||u.trim().length===0)throw e('requires a non-empty "command" string');const c=f(n,"path",e),g=f(n,"pm_context_mode",e);if(g!==void 0&&!m.includes(g))throw e(`field "pm_context_mode" must be one of: ${m.join(", ")}`);const j=U(f(n,"workspace_context_mode",e),`${r} ${t}`),w=f(n,"note",e);return{command:u,path:c!==void 0&&c.length>0?c:void 0,scope:N(n,e),timeout_seconds:J(n,e),pm_context_mode:g,workspace_context_mode:j,env_set:M(n,e),env_clear:P(n,e),shared_host_safe:I(n,"shared_host_safe",e),assert_stdout_contains:p(n,"assert_stdout_contains",e),assert_stdout_regex:v(n,"assert_stdout_regex",e),assert_stderr_contains:p(n,"assert_stderr_contains",e),assert_stderr_regex:v(n,"assert_stderr_regex",e),assert_stdout_min_lines:V(n,e),assert_json_field_equals:K(n,e),assert_json_field_gte:D(n,e),note:w!==void 0&&w.trim().length>0?w.trim():void 0,phase:k(n.phase,`${r} ${t}`)}}function ie(s,t){const r=s.trim();if(r.length===0)throw new d(`${t} requires a JSON object or array of objects describing linked-test entries`,a.USAGE);let e;try{e=JSON.parse(r)}catch(o){throw new d(`${t} value is not valid JSON: ${o instanceof Error?o.message:String(o)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,a.USAGE)}const n=Array.isArray(e)?e:[e];if(n.length===0)throw new d(`${t} array must include at least one linked-test entry object`,a.USAGE);return n.map((o,i)=>$(o,n.length>1?`entry ${i+1}`:"entry",t))}const ae={parseLinkedTestJsonEntry:$};export{_ as LINKED_TEST_ENV_NAME_PATTERN,m as LINKED_TEST_PM_CONTEXT_MODE_VALUES,l as LINKED_TEST_PROTECTED_ENV_KEYS,O as LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,ae as _testOnlyLinkedTestParsers,re as parseLinkedTestAssertionEqualsMap,oe as parseLinkedTestAssertionGteMap,ee as parseLinkedTestBoolean,te as parseLinkedTestContextMode,Q as parseLinkedTestEnvClear,Z as parseLinkedTestEnvSet,ie as parseLinkedTestJsonEntries,se as parseLinkedTestMinLines,ne as parseLinkedTestRegexList,C as parseLinkedTestStringList,U as parseLinkedTestWorkspaceContextMode};
2
2
  //# sourceMappingURL=parsers.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]="47772627-d807-55f3-95b3-69e3b00c6522")}catch{}})();import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{renderPmCommand}from"../command-line.js";import{buildBackgroundTestCommandArgs}from"./command-args.js";import{detectEmptyLinkedTestRun}from"./execution-receipts.js";function assertTestMeasurementExecution(id,options,global2,pmRoot,results){if((options.measure?.length??0)===0||results.some(result=>result.phase!=="setup"&&typeof result.stdout=="string"&&result.failure_category!=="spawn_error"&&result.failure_category!=="empty_run"&&detectEmptyLinkedTestRun(result.stdout,result.stderr??"")===null))return;const retryArgs=["--pm-path",pmRoot,...global2.noExtensions?["--no-extensions"]:[],...global2.author?["--author",global2.author]:[],"test",id,"--list","--json"];throw new PmCliError("--measure requires an executed linked test",EXIT_CODE.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs}})}function assertTestMeasurementRun(id,options,global2,pmRoot,background=!1){if((options.measure?.length??0)===0||options.run===!0)return;const scopeArgs=["--pm-path",pmRoot,...global2.noExtensions?["--no-extensions"]:[],...global2.author?["--author",global2.author]:[]],measurementArgs=[...scopeArgs,...buildBackgroundTestCommandArgs(id,options),...options.list?["--list"]:[],...background?["--background"]:[]],retryArgs=options.acknowledgeLinkedTests?[...scopeArgs,"test",id,"--help"]:measurementArgs,acknowledgementArgs=[...scopeArgs,"test",id,"--acknowledge-linked-tests",...options.author?["--author",options.author]:[]];throw new PmCliError("--measure requires --run",EXIT_CODE.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...options.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${renderPmCommand([...scopeArgs,"test",id,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${renderPmCommand(acknowledgementArgs)}`,`Then run the measurement without --acknowledge-linked-tests: ${renderPmCommand(measurementArgs)}`]}:{},recovery:{missing:["--run"],suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs}})}export{assertTestMeasurementExecution,assertTestMeasurementRun};
1
+ import{EXIT_CODE as i}from"../../core/shared/constants.js";import{PmCliError as m}from"../../core/shared/errors.js";import{renderPmCommand as u}from"../command-line.js";import{buildBackgroundTestCommandArgs as g}from"./command-args.js";import{detectEmptyLinkedTestRun as h}from"./execution-receipts.js";function w(n,e,r,a,o){if((e.measure?.length??0)===0||o.some(t=>t.phase!=="setup"&&typeof t.stdout=="string"&&t.failure_category!=="spawn_error"&&t.failure_category!=="empty_run"&&h(t.stdout,t.stderr??"")===null))return;const s=["--pm-path",a,...r.noExtensions?["--no-extensions"]:[],...r.author?["--author",r.author]:[],"test",n,"--list","--json"];throw new m("--measure requires an executed linked test",i.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:u(s),suggested_retry_args:s}})}function _(n,e,r,a,o=!1){if((e.measure?.length??0)===0||e.run===!0)return;const s=["--pm-path",a,...r.noExtensions?["--no-extensions"]:[],...r.author?["--author",r.author]:[]],t=[...s,...g(n,e),...e.list?["--list"]:[],...o?["--background"]:[]],d=e.acknowledgeLinkedTests?[...s,"test",n,"--help"]:t,c=[...s,"test",n,"--acknowledge-linked-tests",...e.author?["--author",e.author]:[]];throw new m("--measure requires --run",i.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...e.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${u([...s,"test",n,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${u(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${u(t)}`]}:{},recovery:{missing:["--run"],suggested_retry:u(d),suggested_retry_args:d}})}export{w as assertTestMeasurementExecution,_ as assertTestMeasurementRun};
2
2
  //# sourceMappingURL=prerequisites.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]="e67d1a06-77f7-5e86-8f15-bde8b6db0d5a")}catch{}})();import{execFile}from"node:child_process";import{readdir,realpath}from"node:fs/promises";import path from"node:path";import{promisify}from"node:util";import{isFileMissingError}from"../../core/fs/fs-utils.js";import{MERGE_RECEIPT_FILE_MAX_BYTES}from"../merge/receipt-file-boundary.js";import{gitWorkspaceEnvironment}from"../merge/worktree-config.js";const execFileAsync=promisify(execFile),RECEIPT_NAMESPACE=".agents/pm/merge-receipts";async function seedSnapshotReceiptIndex(sourceRoot,snapshotRoot,sourcePmRoot){const directory=path.join(sourcePmRoot,"merge-receipts"),names=(await readdir(directory).catch(error=>{if(isFileMissingError(error))return[];throw error})).filter(name=>name.endsWith(".json")),{readIndexedReceiptBlobs}=await import("../merge/indexed-receipt-blobs.js"),blobs=names.length===0?new Map:await readIndexedReceiptBlobs(sourceRoot,directory,names,MERGE_RECEIPT_FILE_MAX_BYTES,await realpath(directory),{failOnReadError:!0}),options={cwd:snapshotRoot,env:gitWorkspaceEnvironment(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await execFileAsync("git",["rm","-q","-r","--cached","--ignore-unmatch","--",RECEIPT_NAMESPACE],options);for(const[name,raw]of blobs){const pending=execFileAsync("git",["hash-object","-w","--stdin"],options),input=pending.child.stdin;input!==null&&(input.on("error",()=>{pending.child.kill()}),input.end(raw));const objectId=(await pending).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(objectId))throw new Error("Invalid snapshot receipt object identity.");await execFileAsync("git",["update-index","--add","--cacheinfo","100644",objectId,`${RECEIPT_NAMESPACE}/${name}`],options)}}export{seedSnapshotReceiptIndex};
1
+ import{execFile as w}from"node:child_process";import{readdir as E,realpath as u}from"node:fs/promises";import g from"node:path";import{promisify as x}from"node:util";import{isFileMissingError as I}from"../../core/fs/fs-utils.js";import{MERGE_RECEIPT_FILE_MAX_BYTES as b}from"../merge/receipt-file-boundary.js";import{gitWorkspaceEnvironment as R}from"../merge/worktree-config.js";const n=x(w),c=".agents/pm/merge-receipts";async function B(d,m,p){const e=g.join(p,"merge-receipts"),a=(await E(e).catch(t=>{if(I(t))return[];throw t})).filter(t=>t.endsWith(".json")),{readIndexedReceiptBlobs:f}=await import("../merge/indexed-receipt-blobs.js"),h=a.length===0?new Map:await f(d,e,a,b,await u(e),{failOnReadError:!0}),i={cwd:m,env:R(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await n("git",["rm","-q","-r","--cached","--ignore-unmatch","--",c],i);for(const[t,l]of h){const o=n("git",["hash-object","-w","--stdin"],i),r=o.child.stdin;r!==null&&(r.on("error",()=>{o.child.kill()}),r.end(l));const s=(await o).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(s))throw new Error("Invalid snapshot receipt object identity.");await n("git",["update-index","--add","--cacheinfo","100644",s,`${c}/${t}`],i)}}export{B as seedSnapshotReceiptIndex};
2
2
  //# sourceMappingURL=receipt-index-snapshot.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]="35d8018b-d17b-5d63-9d85-9db0b416326a")}catch{}})();import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";const LINKED_TEST_PHASE_VALUES=["setup","test"];function isLinkedTestSetup(test){return test.phase==="setup"}function parseLinkedTestPhase(value,optionName){if(value===void 0)return;const normalized=typeof value=="string"?value.trim().toLowerCase():value;if(normalized==="setup")return"setup";if(!(normalized==="test"||normalized===""))throw new PmCliError(`${optionName} field "phase" must be one of: ${LINKED_TEST_PHASE_VALUES.join(", ")}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function orderLinkedTestsSetupFirst(tests){return[...tests.filter(isLinkedTestSetup),...tests.filter(test=>!isLinkedTestSetup(test))]}function withLinkedTestSetupEntries(selection,stored){if(!selection.selected.some(test=>!isLinkedTestSetup(test)))return selection;const setupIndexes=stored.flatMap((test,index)=>isLinkedTestSetup(test)?[index+1]:[]);if(setupIndexes.length===0)return selection;const regular=selection.selected_indexes.filter(index=>!isLinkedTestSetup(stored[index-1])),prepended=setupIndexes.filter(index=>!selection.selected_indexes.includes(index));return{...selection,selected:[...setupIndexes,...regular].map(index=>stored[index-1]),selected_indexes:[...setupIndexes,...regular],selected_count:setupIndexes.length+regular.length,skipped_count:stored.length-setupIndexes.length-regular.length,...prepended.length>0?{setup_indexes:prepended}:{}}}function resolveSetupWorkspaceRefusal(linkedTest,setupMode,regularModes){if(!isLinkedTestSetup(linkedTest))return;const mismatched=[...regularModes].filter(mode=>mode!==setupMode).sort();if(mismatched.length!==0)return{command:linkedTest.command,path:linkedTest.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${setupMode} workspace, but linked commands it prepares run in ${mismatched.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function createLinkedTestSetupGate(){let failure;return{blocked(linkedTest){if(failure!==void 0)return{command:linkedTest.command,path:linkedTest.path,status:"skipped",...isLinkedTestSetup(linkedTest)?{phase:"setup"}:{},error:`Skipped because setup entry "${failure.label}" did not pass (${failure.outcome}); no later linked command ran.`}},options(linkedTest,options){return!isLinkedTestSetup(linkedTest)||options===void 0?options:{...options,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(linkedTest,result){if(!isLinkedTestSetup(linkedTest))return result;if(result.status==="passed")return{...result,phase:"setup"};const row=result.status==="refused"||result.failure_category==="trust_refusal"||result.failure_category==="setup_failed"?{...result,phase:"setup"}:{...result,status:"failed",phase:"setup",failure_category:"setup_failed",...result.failure_category===void 0?{}:{setup_failure_cause:result.failure_category}};return failure={label:linkedTest.command??linkedTest.path??"<no command>",outcome:row.failure_category??row.status},row}}}function createEmptyFailureCategoryCounts(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0,setup_failed:0}}function countFailureCategories(runResults){const counts=createEmptyFailureCategoryCounts();for(const result of runResults)result.status!=="failed"&&result.status!=="refused"||!result.failure_category||(counts[result.failure_category]+=1);return counts}export{LINKED_TEST_PHASE_VALUES,countFailureCategories,createEmptyFailureCategoryCounts,createLinkedTestSetupGate,isLinkedTestSetup,orderLinkedTestsSetupFirst,parseLinkedTestPhase,resolveSetupWorkspaceRefusal,withLinkedTestSetupEntries};
1
+ import{EXIT_CODE as i}from"../../core/shared/constants.js";import{PmCliError as f}from"../../core/shared/errors.js";const d=["setup","test"];function u(t){return t.phase==="setup"}function m(t,r){if(t===void 0)return;const e=typeof t=="string"?t.trim().toLowerCase():t;if(e==="setup")return"setup";if(!(e==="test"||e===""))throw new f(`${r} field "phase" must be one of: ${d.join(", ")}`,i.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function _(t){return[...t.filter(u),...t.filter(r=>!u(r))]}function h(t,r){if(!t.selected.some(n=>!u(n)))return t;const e=r.flatMap((n,o)=>u(n)?[o+1]:[]);if(e.length===0)return t;const s=t.selected_indexes.filter(n=>!u(r[n-1])),a=e.filter(n=>!t.selected_indexes.includes(n));return{...t,selected:[...e,...s].map(n=>r[n-1]),selected_indexes:[...e,...s],selected_count:e.length+s.length,skipped_count:r.length-e.length-s.length,...a.length>0?{setup_indexes:a}:{}}}function g(t,r,e){if(!u(t))return;const s=[...e].filter(a=>a!==r).sort();if(s.length!==0)return{command:t.command,path:t.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${r} workspace, but linked commands it prepares run in ${s.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function x(){let t;return{blocked(r){if(t!==void 0)return{command:r.command,path:r.path,status:"skipped",...u(r)?{phase:"setup"}:{},error:`Skipped because setup entry "${t.label}" did not pass (${t.outcome}); no later linked command ran.`}},options(r,e){return!u(r)||e===void 0?e:{...e,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(r,e){if(!u(r))return e;if(e.status==="passed")return{...e,phase:"setup"};const a=e.status==="refused"||e.failure_category==="trust_refusal"||e.failure_category==="setup_failed"?{...e,phase:"setup"}:{...e,status:"failed",phase:"setup",failure_category:"setup_failed",...e.failure_category===void 0?{}:{setup_failure_cause:e.failure_category}};return t={label:r.command??r.path??"<no command>",outcome:a.failure_category??a.status},a}}}function p(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0,setup_failed:0}}function y(t){const r=p();for(const e of t)e.status!=="failed"&&e.status!=="refused"||!e.failure_category||(r[e.failure_category]+=1);return r}export{d as LINKED_TEST_PHASE_VALUES,y as countFailureCategories,p as createEmptyFailureCategoryCounts,x as createLinkedTestSetupGate,u as isLinkedTestSetup,_ as orderLinkedTestsSetupFirst,m as parseLinkedTestPhase,g as resolveSetupWorkspaceRefusal,h as withLinkedTestSetupEntries};
2
2
  //# sourceMappingURL=run-phases.js.map