@unbrained/pm-cli 2026.11.16 → 2026.11.17

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 (399) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/main.js +2 -2
  3. package/dist/cli/register-mutation.js +3 -2
  4. package/dist/cli/runtime/invocation-rewrites.js +2 -0
  5. package/dist/cli-bundle/bundle-manifest.json +1 -1
  6. package/dist/cli-bundle/chunks/{chunk-ERD2RYWM.js → chunk-2WHXFKMY.js} +31 -31
  7. package/dist/cli-bundle/chunks/{chunk-VJLZHOTP.js → chunk-36R3JTAD.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-FZ4XWWLO.js → chunk-3IU2S5UQ.js} +43 -43
  9. package/dist/cli-bundle/chunks/chunk-4FIN2XWC.js +2 -0
  10. package/dist/cli-bundle/chunks/{chunk-NHNM3GIP.js → chunk-5OFMWP3Q.js} +3 -3
  11. package/dist/cli-bundle/chunks/{chunk-2WNORBVN.js → chunk-77MGDTK4.js} +83 -83
  12. package/dist/cli-bundle/chunks/{chunk-F7P42FL5.js → chunk-7K2RUKMK.js} +4 -4
  13. package/dist/cli-bundle/chunks/chunk-7UUPLMCU.js +115 -0
  14. package/dist/cli-bundle/chunks/chunk-ABFHWRLE.js +2 -0
  15. package/dist/cli-bundle/chunks/{chunk-KGOGLKL2.js → chunk-ACLBUVQG.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-DZWRNL6R.js → chunk-ADKDFCVT.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-AM26RAG7.js +124 -0
  18. package/dist/cli-bundle/chunks/chunk-CR5GC3VO.js +9 -0
  19. package/dist/cli-bundle/chunks/chunk-DXSZL3T6.js +3 -0
  20. package/dist/cli-bundle/chunks/chunk-FXSLODOK.js +2 -0
  21. package/dist/cli-bundle/chunks/chunk-H64BNM4A.js +8 -0
  22. package/dist/cli-bundle/chunks/{chunk-2D26HRXB.js → chunk-HQYIKAC6.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-I3T2FVUA.js → chunk-KIQNEOKJ.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-O4ZSIMNC.js +8 -0
  25. package/dist/cli-bundle/chunks/chunk-QANUQMDL.js +6 -0
  26. package/dist/cli-bundle/chunks/{chunk-4I7YG3VZ.js → chunk-QZNL5XDT.js} +2 -2
  27. package/dist/cli-bundle/chunks/chunk-RXNBNF6O.js +2 -0
  28. package/dist/cli-bundle/chunks/chunk-VLKCFZY6.js +2 -0
  29. package/dist/cli-bundle/chunks/{chunk-J257NZRD.js → chunk-X5TFNFTS.js} +11 -11
  30. package/dist/cli-bundle/chunks/chunk-XP35IEHT.js +2 -0
  31. package/dist/cli-bundle/chunks/chunk-XPBADEUK.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-NYN5OR2T.js → chunk-Y4LXVPA5.js} +2 -2
  33. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-HNLN6UXH.js → indexed-receipt-blobs-ELEMA7IW.js} +2 -2
  34. package/dist/cli-bundle/chunks/{item-revision-PSOL5I4H.js → item-revision-7RVMVXTE.js} +2 -2
  35. package/dist/cli-bundle/chunks/item-transaction-NVX6P3FK.js +2 -0
  36. package/dist/cli-bundle/chunks/{mutation-actor-BDBBH3ZS.js → mutation-actor-DDYJW5B4.js} +2 -2
  37. package/dist/cli-bundle/chunks/mutation-admission-3PKQOAYK.js +2 -0
  38. package/dist/cli-bundle/chunks/{register-list-query-AESCVO6H.js → register-list-query-TPZLHFHQ.js} +2 -2
  39. package/dist/cli-bundle/chunks/register-mutation-JG5AEBRJ.js +21 -0
  40. package/dist/cli-bundle/chunks/register-operations-3CNXP46P.js +2 -0
  41. package/dist/cli-bundle/chunks/register-setup-4N56VL2P.js +2 -0
  42. package/dist/cli-bundle/chunks/{settlement-hook-MVVVUIVZ.js → settlement-hook-E5LHZ4RD.js} +2 -2
  43. package/dist/cli-bundle/chunks/{stage-RMU3JAWM.js → stage-XGWW3T64.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-2MQNIDKG.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-DFBHW7HP.js → chunk-5JVB42Z7.js} +3 -3
  46. package/dist/cli-bundle/focused-chunks/{chunk-SFATIM77.js → chunk-6JQXDGHM.js} +9 -9
  47. package/dist/cli-bundle/focused-chunks/{chunk-HHMMIHZP.js → chunk-7RF2YPZ5.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/chunk-7Z2NYAK4.js +2 -0
  49. package/dist/cli-bundle/focused-chunks/chunk-A2CLYPDA.js +102 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-BNLLST32.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/{chunk-7SEPCQV2.js → chunk-DH4DHL6V.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-EZXLY6S4.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-KRNF3WTC.js → chunk-FPPYE6CY.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-ONM2R32I.js → chunk-GD2YWUAD.js} +50 -50
  55. package/dist/cli-bundle/focused-chunks/chunk-HO2YUD4P.js +91 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-BEHIMEV2.js → chunk-ICEHI4SN.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-PDXSMSO5.js → chunk-IXYBN6D2.js} +3 -3
  58. package/dist/cli-bundle/focused-chunks/chunk-MTBC32ZR.js +8 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-OAIAZHRG.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-OPY43DNJ.js +2 -0
  61. package/dist/cli-bundle/focused-chunks/{chunk-DZMP3VYQ.js → chunk-SESMRMEE.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{chunk-PEL4SQXV.js → chunk-VBA4BIHN.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{chunk-UBBTBNUY.js → chunk-XJS4COL2.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/chunk-XS2YZCT5.js +2 -0
  65. package/dist/cli-bundle/focused-chunks/chunk-YWPLBFPC.js +44 -0
  66. package/dist/cli-bundle/focused-chunks/{chunk-6E4X7MQA.js → chunk-ZDY5L2C2.js} +7 -7
  67. package/dist/cli-bundle/focused-chunks/chunk-ZFUZ4YYN.js +8 -0
  68. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ADMQXF3N.js → indexed-receipt-blobs-ZTRFCPH7.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/item-revision-U7GDVAH7.js +2 -0
  70. package/dist/cli-bundle/focused-chunks/item-transaction-7C4BH47O.js +2 -0
  71. package/dist/cli-bundle/focused-chunks/mutation-actor-2SVBO324.js +2 -0
  72. package/dist/cli-bundle/focused-chunks/mutation-admission-SKXVITP5.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/{settlement-hook-5U2M75BY.js → settlement-hook-OUBUN45C.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/stage-LVAGKCEE.js +2 -0
  75. package/dist/cli-bundle/main.js +27 -27
  76. package/dist/cli-bundle/sdk-authoring.js +1 -1
  77. package/dist/cli-bundle/sdk-contracts.js +2 -2
  78. package/dist/cli-bundle/sdk-core.js +1 -1
  79. package/dist/cli-bundle/sdk-governance.js +1 -1
  80. package/dist/cli-bundle/sdk-graph.js +1 -1
  81. package/dist/cli-bundle/sdk-merge.js +57 -57
  82. package/dist/cli-bundle/sdk-query.js +1 -1
  83. package/dist/cli-bundle/sdk-runtime.js +1 -1
  84. package/dist/cli-bundle/sdk-testing.js +1 -1
  85. package/dist/cli-bundle/sdk.js +4 -4
  86. package/dist/core/extensions/extension-hook-runtime.d.ts +14 -2
  87. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  88. package/dist/core/extensions/extension-types.d.ts +14 -0
  89. package/dist/core/extensions/extension-types.js +1 -1
  90. package/dist/core/extensions/index.d.ts +1 -1
  91. package/dist/core/extensions/index.js +1 -1
  92. package/dist/core/policy/workflow-policy-store.js +1 -1
  93. package/dist/core/store/item-mutation-precondition.d.ts +32 -1
  94. package/dist/core/store/item-mutation-precondition.js +1 -1
  95. package/dist/core/store/item-store.js +1 -1
  96. package/dist/core/store/transaction-coordinator-scope.js +2 -0
  97. package/dist/sdk/authoring.d.ts +1 -1
  98. package/dist/sdk/authoring.js +1 -1
  99. package/dist/sdk/cli-bootstrap.js +1 -1
  100. package/dist/sdk/item-transaction.js +1 -1
  101. package/dist/sdk/lifecycle/copy.js +1 -1
  102. package/dist/sdk/lifecycle/create.js +1 -1
  103. package/dist/sdk/lifecycle/restore.js +1 -1
  104. package/dist/sdk/package-import-adapters.d.ts +14 -1
  105. package/dist/sdk/package-import-adapters.js +1 -1
  106. package/dist/sdk/public-surface.json +1 -1
  107. package/dist/sdk/testing.d.ts +21 -3
  108. package/dist/sdk/testing.js +2 -2
  109. package/dist/sdk/workspace-transaction.js +2 -2
  110. package/docs/EXTENSIONS.md +1 -1
  111. package/docs/MIGRATION_CLI_SIMPLIFICATION.md +1 -1
  112. package/docs/SDK.md +40 -3
  113. package/docs/WORKFLOW_POLICIES.md +23 -0
  114. package/marketplace.json +1 -1
  115. package/node_modules/@opentelemetry/core/build/esm/version.d.ts +1 -1
  116. package/node_modules/@opentelemetry/core/build/esm/version.js +1 -1
  117. package/node_modules/@opentelemetry/core/build/esnext/version.d.ts +1 -1
  118. package/node_modules/@opentelemetry/core/build/esnext/version.js +1 -1
  119. package/node_modules/@opentelemetry/core/build/src/version.d.ts +1 -1
  120. package/node_modules/@opentelemetry/core/build/src/version.js +1 -1
  121. package/node_modules/@opentelemetry/core/package.json +2 -2
  122. package/node_modules/@opentelemetry/resources/build/esm/detectors/platform/node/machine-id/execAsync.d.ts +1 -0
  123. package/node_modules/@opentelemetry/resources/build/esm/detectors/platform/node/machine-id/execAsync.js +1 -0
  124. package/node_modules/@opentelemetry/resources/build/esm/detectors/platform/node/machine-id/getMachineId-bsd.js +3 -2
  125. package/node_modules/@opentelemetry/resources/build/esm/detectors/platform/node/machine-id/getMachineId-darwin.js +3 -2
  126. package/node_modules/@opentelemetry/resources/build/esm/version.d.ts +1 -1
  127. package/node_modules/@opentelemetry/resources/build/esm/version.js +1 -1
  128. package/node_modules/@opentelemetry/resources/build/esnext/detectors/platform/node/machine-id/execAsync.d.ts +1 -0
  129. package/node_modules/@opentelemetry/resources/build/esnext/detectors/platform/node/machine-id/execAsync.js +1 -0
  130. package/node_modules/@opentelemetry/resources/build/esnext/detectors/platform/node/machine-id/getMachineId-bsd.js +3 -2
  131. package/node_modules/@opentelemetry/resources/build/esnext/detectors/platform/node/machine-id/getMachineId-darwin.js +3 -2
  132. package/node_modules/@opentelemetry/resources/build/esnext/version.d.ts +1 -1
  133. package/node_modules/@opentelemetry/resources/build/esnext/version.js +1 -1
  134. package/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.d.ts +1 -0
  135. package/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js +2 -1
  136. package/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js +2 -1
  137. package/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js +2 -1
  138. package/node_modules/@opentelemetry/resources/build/src/version.d.ts +1 -1
  139. package/node_modules/@opentelemetry/resources/build/src/version.js +1 -1
  140. package/node_modules/@opentelemetry/resources/package.json +3 -3
  141. package/node_modules/@opentelemetry/sdk-trace/build/esm/version.d.ts +1 -1
  142. package/node_modules/@opentelemetry/sdk-trace/build/esm/version.js +1 -1
  143. package/node_modules/@opentelemetry/sdk-trace/build/esnext/version.d.ts +1 -1
  144. package/node_modules/@opentelemetry/sdk-trace/build/esnext/version.js +1 -1
  145. package/node_modules/@opentelemetry/sdk-trace/build/src/version.d.ts +1 -1
  146. package/node_modules/@opentelemetry/sdk-trace/build/src/version.js +1 -1
  147. package/node_modules/@opentelemetry/sdk-trace/package.json +5 -5
  148. package/node_modules/@opentelemetry/sdk-trace-base/build/esm/version.d.ts +1 -1
  149. package/node_modules/@opentelemetry/sdk-trace-base/build/esm/version.js +1 -1
  150. package/node_modules/@opentelemetry/sdk-trace-base/build/esnext/version.d.ts +1 -1
  151. package/node_modules/@opentelemetry/sdk-trace-base/build/esnext/version.js +1 -1
  152. package/node_modules/@opentelemetry/sdk-trace-base/build/src/version.d.ts +1 -1
  153. package/node_modules/@opentelemetry/sdk-trace-base/build/src/version.js +1 -1
  154. package/node_modules/@opentelemetry/sdk-trace-base/package.json +7 -7
  155. package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_attributes.cjs +18202 -0
  156. package/node_modules/@opentelemetry/semantic-conventions/{build/src/experimental_attributes.js → dist/experimental_attributes.d.cts} +3328 -1993
  157. package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/experimental_attributes.js → dist/experimental_attributes.d.mts} +3328 -1935
  158. package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_attributes.mjs +16385 -0
  159. package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_events.cjs +325 -0
  160. package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/experimental_events.js → dist/experimental_events.d.cts} +37 -41
  161. package/node_modules/@opentelemetry/semantic-conventions/{build/esm/experimental_events.js → dist/experimental_events.d.mts} +37 -41
  162. package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_events.mjs +295 -0
  163. package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_metrics.cjs +4929 -0
  164. package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/experimental_metrics.js → dist/experimental_metrics.d.cts} +955 -597
  165. package/node_modules/@opentelemetry/semantic-conventions/{build/esm/experimental_metrics.js → dist/experimental_metrics.d.mts} +955 -597
  166. package/node_modules/@opentelemetry/semantic-conventions/dist/experimental_metrics.mjs +4419 -0
  167. package/node_modules/@opentelemetry/semantic-conventions/dist/index-incubating.cjs +2619 -0
  168. package/node_modules/@opentelemetry/semantic-conventions/dist/index-incubating.d.cts +7 -0
  169. package/node_modules/@opentelemetry/semantic-conventions/dist/index-incubating.d.mts +7 -0
  170. package/node_modules/@opentelemetry/semantic-conventions/dist/index-incubating.mjs +7 -0
  171. package/node_modules/@opentelemetry/semantic-conventions/dist/index.cjs +670 -0
  172. package/node_modules/@opentelemetry/semantic-conventions/dist/index.d.cts +6 -0
  173. package/node_modules/@opentelemetry/semantic-conventions/dist/index.d.mts +6 -0
  174. package/node_modules/@opentelemetry/semantic-conventions/dist/index.mjs +6 -0
  175. package/node_modules/@opentelemetry/semantic-conventions/dist/internal/utils.cjs +20 -0
  176. package/node_modules/@opentelemetry/semantic-conventions/dist/internal/utils.mjs +20 -0
  177. package/node_modules/@opentelemetry/semantic-conventions/dist/resource/SemanticResourceAttributes.cjs +1326 -0
  178. package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/resource/SemanticResourceAttributes.d.ts → dist/resource/SemanticResourceAttributes.d.cts} +600 -597
  179. package/node_modules/@opentelemetry/semantic-conventions/{build/src/resource/SemanticResourceAttributes.d.ts → dist/resource/SemanticResourceAttributes.d.mts} +600 -597
  180. package/node_modules/@opentelemetry/semantic-conventions/dist/resource/SemanticResourceAttributes.mjs +1188 -0
  181. package/node_modules/@opentelemetry/semantic-conventions/dist/stable_attributes.cjs +2038 -0
  182. package/node_modules/@opentelemetry/semantic-conventions/{build/esm/stable_attributes.js → dist/stable_attributes.d.cts} +327 -220
  183. package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/stable_attributes.js → dist/stable_attributes.d.mts} +327 -220
  184. package/node_modules/@opentelemetry/semantic-conventions/dist/stable_attributes.mjs +1841 -0
  185. package/node_modules/@opentelemetry/semantic-conventions/dist/stable_events.cjs +9 -0
  186. package/node_modules/@opentelemetry/semantic-conventions/dist/stable_events.d.cts +8 -0
  187. package/node_modules/@opentelemetry/semantic-conventions/dist/stable_events.d.mts +8 -0
  188. package/node_modules/@opentelemetry/semantic-conventions/dist/stable_events.mjs +9 -0
  189. package/node_modules/@opentelemetry/semantic-conventions/dist/stable_metrics.cjs +378 -0
  190. package/node_modules/@opentelemetry/semantic-conventions/{build/src/stable_metrics.js → dist/stable_metrics.d.cts} +69 -63
  191. package/node_modules/@opentelemetry/semantic-conventions/{build/esm/stable_metrics.js → dist/stable_metrics.d.mts} +69 -59
  192. package/node_modules/@opentelemetry/semantic-conventions/dist/stable_metrics.mjs +326 -0
  193. package/node_modules/@opentelemetry/semantic-conventions/dist/trace/SemanticAttributes.cjs +2508 -0
  194. package/node_modules/@opentelemetry/semantic-conventions/{build/esnext/trace/SemanticAttributes.d.ts → dist/trace/SemanticAttributes.d.cts} +1097 -1094
  195. package/node_modules/@opentelemetry/semantic-conventions/{build/src/trace/SemanticAttributes.d.ts → dist/trace/SemanticAttributes.d.mts} +1097 -1094
  196. package/node_modules/@opentelemetry/semantic-conventions/dist/trace/SemanticAttributes.mjs +2236 -0
  197. package/node_modules/@opentelemetry/semantic-conventions/package.json +27 -42
  198. package/node_modules/@sentry/core/build/cjs/client.js +14 -5
  199. package/node_modules/@sentry/core/build/cjs/integrations/express/patch-layer.js +15 -1
  200. package/node_modules/@sentry/core/build/cjs/integrations/http/client-subscriptions.js +10 -1
  201. package/node_modules/@sentry/core/build/cjs/scope.js +0 -1
  202. package/node_modules/@sentry/core/build/cjs/tracing/openai/utils.js +1 -7
  203. package/node_modules/@sentry/core/build/cjs/tracing/sentrySpan.js +11 -0
  204. package/node_modules/@sentry/core/build/cjs/utils/envelope.js +1 -1
  205. package/node_modules/@sentry/core/build/cjs/utils/sql.js +1 -1
  206. package/node_modules/@sentry/core/build/cjs/utils/tunnel.js +9 -0
  207. package/node_modules/@sentry/core/build/cjs/utils/version.js +1 -1
  208. package/node_modules/@sentry/core/build/esm/client.js +14 -5
  209. package/node_modules/@sentry/core/build/esm/integrations/express/patch-layer.js +15 -1
  210. package/node_modules/@sentry/core/build/esm/integrations/http/client-subscriptions.js +10 -1
  211. package/node_modules/@sentry/core/build/esm/package.json +1 -1
  212. package/node_modules/@sentry/core/build/esm/scope.js +0 -1
  213. package/node_modules/@sentry/core/build/esm/tracing/openai/utils.js +1 -7
  214. package/node_modules/@sentry/core/build/esm/tracing/sentrySpan.js +11 -0
  215. package/node_modules/@sentry/core/build/esm/utils/envelope.js +1 -1
  216. package/node_modules/@sentry/core/build/esm/utils/sql.js +1 -1
  217. package/node_modules/@sentry/core/build/esm/utils/tunnel.js +9 -1
  218. package/node_modules/@sentry/core/build/esm/utils/version.js +1 -1
  219. package/node_modules/@sentry/core/build/types/types/datacategory.d.ts +1 -1
  220. package/node_modules/@sentry/core/build/types/utils/tunnel.d.ts +1 -0
  221. package/node_modules/@sentry/core/build/types-ts3.8/types/datacategory.d.ts +1 -1
  222. package/node_modules/@sentry/core/build/types-ts3.8/utils/tunnel.d.ts +1 -0
  223. package/node_modules/@sentry/core/package.json +1 -1
  224. package/node_modules/@sentry/node/build/cjs/integrations/tracing/redis/index.js +1 -1
  225. package/node_modules/@sentry/node/build/esm/package.json +1 -1
  226. package/node_modules/@sentry/node/package.json +6 -6
  227. package/node_modules/@sentry/node-core/build/cjs/integrations/anr/index.js +1 -1
  228. package/node_modules/@sentry/node-core/build/cjs/integrations/contextlines.js +6 -4
  229. package/node_modules/@sentry/node-core/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  230. package/node_modules/@sentry/node-core/build/cjs/integrations/modules.js +21 -2
  231. package/node_modules/@sentry/node-core/build/cjs/integrations/node-fetch/undici-instrumentation.js +8 -0
  232. package/node_modules/@sentry/node-core/build/esm/integrations/anr/index.js +1 -1
  233. package/node_modules/@sentry/node-core/build/esm/integrations/anr/worker-script.js +2 -2
  234. package/node_modules/@sentry/node-core/build/esm/integrations/contextlines.js +7 -5
  235. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  236. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/worker-script.js +1 -1
  237. package/node_modules/@sentry/node-core/build/esm/integrations/node-fetch/undici-instrumentation.js +8 -0
  238. package/node_modules/@sentry/node-core/build/esm/package.json +1 -1
  239. package/node_modules/@sentry/node-core/package.json +9 -9
  240. package/node_modules/@sentry/opentelemetry/build/esm/package.json +1 -1
  241. package/node_modules/@sentry/opentelemetry/package.json +6 -6
  242. package/node_modules/@sentry/server-utils/build/THIRD-PARTY-LICENSES.txt +32 -32
  243. package/node_modules/@sentry/server-utils/build/cjs/integrations/tracing-channel/express/instrumentation.js +12 -1
  244. package/node_modules/@sentry/server-utils/build/esm/integrations/tracing-channel/express/instrumentation.js +13 -2
  245. package/node_modules/@sentry/server-utils/build/esm/package.json +1 -1
  246. package/node_modules/@sentry/server-utils/build/types/integrations/tracing-channel/express/types.d.ts +1 -1
  247. package/node_modules/@sentry/server-utils/build/types-ts3.8/integrations/tracing-channel/express/types.d.ts +1 -1
  248. package/node_modules/@sentry/server-utils/package.json +2 -2
  249. package/node_modules/debug/package.json +1 -1
  250. package/node_modules/es-module-lexer/dist/lexer.asm.js +2 -2
  251. package/node_modules/es-module-lexer/dist/lexer.cjs +1 -1
  252. package/node_modules/es-module-lexer/dist/lexer.js +2 -2
  253. package/node_modules/es-module-lexer/dist/lexer.minimal.asm.js +2 -2
  254. package/node_modules/es-module-lexer/dist/lexer.minimal.cjs +1 -1
  255. package/node_modules/es-module-lexer/dist/lexer.minimal.js +2 -2
  256. package/node_modules/es-module-lexer/package.json +1 -1
  257. package/node_modules/import-in-the-middle/CHANGELOG.md +35 -0
  258. package/node_modules/import-in-the-middle/README.md +15 -1
  259. package/node_modules/import-in-the-middle/create-hook.mjs +370 -155
  260. package/node_modules/import-in-the-middle/index.d.ts +8 -2
  261. package/node_modules/import-in-the-middle/index.js +80 -53
  262. package/node_modules/import-in-the-middle/lib/get-esm-exports.mjs +37 -3
  263. package/node_modules/import-in-the-middle/lib/get-exports.mjs +33 -40
  264. package/node_modules/import-in-the-middle/lib/register.js +81 -16
  265. package/node_modules/import-in-the-middle/package.json +9 -5
  266. package/node_modules/supports-color/browser.js +21 -2
  267. package/node_modules/supports-color/index.js +41 -24
  268. package/node_modules/supports-color/license +1 -1
  269. package/node_modules/supports-color/package.json +11 -6
  270. package/node_modules/supports-color/readme.md +8 -7
  271. package/package.json +4 -4
  272. package/packages/pm-beads/package.json +1 -1
  273. package/packages/pm-calendar/package.json +1 -1
  274. package/packages/pm-command-kit/package.json +1 -1
  275. package/packages/pm-digital-twin/package.json +1 -1
  276. package/packages/pm-governance-audit/package.json +1 -1
  277. package/packages/pm-guide-shell/package.json +1 -1
  278. package/packages/pm-kanban/package.json +1 -1
  279. package/packages/pm-lifecycle-hooks/package.json +1 -1
  280. package/packages/pm-linked-test-adapters/package.json +1 -1
  281. package/packages/pm-search-advanced/package.json +1 -1
  282. package/packages/pm-templates/package.json +1 -1
  283. package/packages/pm-todos/package.json +1 -1
  284. package/packages/pm-vcs/package.json +1 -1
  285. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  286. package/plugins/pm-claude/package.json +1 -1
  287. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  288. package/plugins/pm-codex/package.json +1 -1
  289. package/plugins/pm-codex/plugin.json +1 -1
  290. package/runtime-dependencies.json +1 -1
  291. package/dist/cli-bundle/chunks/chunk-4WIVCOA7.js +0 -2
  292. package/dist/cli-bundle/chunks/chunk-A3WCP4TU.js +0 -6
  293. package/dist/cli-bundle/chunks/chunk-AB5S6TWE.js +0 -124
  294. package/dist/cli-bundle/chunks/chunk-BV7J3LRH.js +0 -114
  295. package/dist/cli-bundle/chunks/chunk-E4BQRZF2.js +0 -10
  296. package/dist/cli-bundle/chunks/chunk-IGEBFNWE.js +0 -2
  297. package/dist/cli-bundle/chunks/chunk-IYICNCK2.js +0 -2
  298. package/dist/cli-bundle/chunks/chunk-JD3XWF66.js +0 -3
  299. package/dist/cli-bundle/chunks/chunk-JLHD7OQ2.js +0 -2
  300. package/dist/cli-bundle/chunks/chunk-LC4DJVXR.js +0 -2
  301. package/dist/cli-bundle/chunks/chunk-OFZQEQ6X.js +0 -2
  302. package/dist/cli-bundle/chunks/chunk-QGL5IAP4.js +0 -8
  303. package/dist/cli-bundle/chunks/chunk-R24NZ2TB.js +0 -8
  304. package/dist/cli-bundle/chunks/chunk-VO2HSB5F.js +0 -2
  305. package/dist/cli-bundle/chunks/item-transaction-55QTCU2M.js +0 -2
  306. package/dist/cli-bundle/chunks/mutation-admission-WUN7JYVJ.js +0 -2
  307. package/dist/cli-bundle/chunks/register-mutation-SKCEP5QU.js +0 -20
  308. package/dist/cli-bundle/chunks/register-operations-ZT4OYCF3.js +0 -2
  309. package/dist/cli-bundle/chunks/register-setup-JVWNS2TY.js +0 -2
  310. package/dist/cli-bundle/focused-chunks/chunk-3WVMEA2A.js +0 -6
  311. package/dist/cli-bundle/focused-chunks/chunk-5UVJOAUP.js +0 -91
  312. package/dist/cli-bundle/focused-chunks/chunk-5WQ3LNUK.js +0 -78
  313. package/dist/cli-bundle/focused-chunks/chunk-7XHE335U.js +0 -2
  314. package/dist/cli-bundle/focused-chunks/chunk-CZFZCSOX.js +0 -2
  315. package/dist/cli-bundle/focused-chunks/chunk-HPC2M6JD.js +0 -6
  316. package/dist/cli-bundle/focused-chunks/chunk-HR5FEUUL.js +0 -2
  317. package/dist/cli-bundle/focused-chunks/chunk-J7ESCE7M.js +0 -24
  318. package/dist/cli-bundle/focused-chunks/chunk-KWZLY35A.js +0 -2
  319. package/dist/cli-bundle/focused-chunks/chunk-M4IA4LC6.js +0 -8
  320. package/dist/cli-bundle/focused-chunks/chunk-NASE6JC2.js +0 -2
  321. package/dist/cli-bundle/focused-chunks/chunk-QJ647CQE.js +0 -2
  322. package/dist/cli-bundle/focused-chunks/chunk-ZCN35TCK.js +0 -2
  323. package/dist/cli-bundle/focused-chunks/chunk-ZSQ2FT22.js +0 -44
  324. package/dist/cli-bundle/focused-chunks/item-revision-GNKYO6GZ.js +0 -2
  325. package/dist/cli-bundle/focused-chunks/item-transaction-AUUQHR5Z.js +0 -2
  326. package/dist/cli-bundle/focused-chunks/mutation-actor-OBRD7HFZ.js +0 -2
  327. package/dist/cli-bundle/focused-chunks/mutation-admission-6TX3EOJX.js +0 -2
  328. package/dist/cli-bundle/focused-chunks/stage-LERF2YJU.js +0 -2
  329. package/node_modules/@opentelemetry/semantic-conventions/build/esm/experimental_attributes.d.ts +0 -14984
  330. package/node_modules/@opentelemetry/semantic-conventions/build/esm/experimental_attributes.js +0 -14991
  331. package/node_modules/@opentelemetry/semantic-conventions/build/esm/experimental_events.d.ts +0 -291
  332. package/node_modules/@opentelemetry/semantic-conventions/build/esm/experimental_metrics.d.ts +0 -4053
  333. package/node_modules/@opentelemetry/semantic-conventions/build/esm/index-incubating.d.ts +0 -7
  334. package/node_modules/@opentelemetry/semantic-conventions/build/esm/index-incubating.js +0 -13
  335. package/node_modules/@opentelemetry/semantic-conventions/build/esm/index.d.ts +0 -6
  336. package/node_modules/@opentelemetry/semantic-conventions/build/esm/index.js +0 -16
  337. package/node_modules/@opentelemetry/semantic-conventions/build/esm/internal/utils.d.ts +0 -7
  338. package/node_modules/@opentelemetry/semantic-conventions/build/esm/internal/utils.js +0 -23
  339. package/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.d.ts +0 -1453
  340. package/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/SemanticResourceAttributes.js +0 -1250
  341. package/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.d.ts +0 -2
  342. package/node_modules/@opentelemetry/semantic-conventions/build/esm/resource/index.js +0 -10
  343. package/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.d.ts +0 -1726
  344. package/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_events.d.ts +0 -5
  345. package/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_events.js +0 -12
  346. package/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_metrics.d.ts +0 -308
  347. package/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.d.ts +0 -2664
  348. package/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js +0 -2360
  349. package/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.d.ts +0 -2
  350. package/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/index.js +0 -10
  351. package/node_modules/@opentelemetry/semantic-conventions/build/esm/version.d.ts +0 -2
  352. package/node_modules/@opentelemetry/semantic-conventions/build/esm/version.js +0 -7
  353. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/experimental_attributes.d.ts +0 -14984
  354. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/experimental_events.d.ts +0 -291
  355. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/experimental_metrics.d.ts +0 -4053
  356. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/index-incubating.d.ts +0 -7
  357. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/index-incubating.js +0 -13
  358. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/index.d.ts +0 -6
  359. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/index.js +0 -16
  360. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/internal/utils.d.ts +0 -7
  361. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/internal/utils.js +0 -23
  362. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/resource/SemanticResourceAttributes.js +0 -1250
  363. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/resource/index.d.ts +0 -2
  364. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/resource/index.js +0 -10
  365. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_attributes.d.ts +0 -1726
  366. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_events.d.ts +0 -5
  367. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_events.js +0 -12
  368. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_metrics.d.ts +0 -308
  369. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/stable_metrics.js +0 -315
  370. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/trace/SemanticAttributes.js +0 -2360
  371. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/trace/index.d.ts +0 -2
  372. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/trace/index.js +0 -10
  373. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/version.d.ts +0 -2
  374. package/node_modules/@opentelemetry/semantic-conventions/build/esnext/version.js +0 -7
  375. package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_attributes.d.ts +0 -14984
  376. package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_events.d.ts +0 -291
  377. package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_events.js +0 -301
  378. package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_metrics.d.ts +0 -4053
  379. package/node_modules/@opentelemetry/semantic-conventions/build/src/experimental_metrics.js +0 -4072
  380. package/node_modules/@opentelemetry/semantic-conventions/build/src/index-incubating.d.ts +0 -7
  381. package/node_modules/@opentelemetry/semantic-conventions/build/src/index-incubating.js +0 -29
  382. package/node_modules/@opentelemetry/semantic-conventions/build/src/index.d.ts +0 -6
  383. package/node_modules/@opentelemetry/semantic-conventions/build/src/index.js +0 -32
  384. package/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.d.ts +0 -7
  385. package/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js +0 -27
  386. package/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js +0 -1255
  387. package/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.d.ts +0 -2
  388. package/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js +0 -26
  389. package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.d.ts +0 -1726
  390. package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js +0 -1759
  391. package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.d.ts +0 -5
  392. package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js +0 -15
  393. package/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.d.ts +0 -308
  394. package/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js +0 -2368
  395. package/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.d.ts +0 -2
  396. package/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js +0 -26
  397. package/node_modules/@opentelemetry/semantic-conventions/build/src/version.d.ts +0 -2
  398. package/node_modules/@opentelemetry/semantic-conventions/build/src/version.js +0 -10
  399. /package/node_modules/import-in-the-middle/{register-hooks.d.ts → register-hooks.d.mts} +0 -0
@@ -3,7 +3,9 @@
3
3
  *
4
4
  * Defines public SDK APIs and package-author helpers for Testing.
5
5
  */
6
- import type{AfterCommandHookContext,BeforeCommandHookContext,BeforeMutationHookContext,MutationActor,CommandHandlerResult,CommandOverrideContext,CommandOverrideResult,ExtensionActivationResult,ExtensionCapability,ExtensionCommandRegistry,ExtensionDeactivationResult,ExtensionGovernancePolicy,ExtensionHookRegistry,ExtensionCommandSdk,ExtensionLayer,ExtensionManifest,ExtensionParserRegistry,ExtensionPreflightRegistry,ExtensionRegistrationRegistry,ExtensionRendererRegistry,ExtensionServiceName,ExtensionServiceRegistry,FlagDefinition,OnIndexHookContext,OnReadHookContext,OnWriteHookContext,OutputRendererFormat,ParserOverrideContext,ParserOverrideResult,PreflightOverrideContext,PreflightOverrideResult,RegisteredExtensionCommandDefinition,RegisteredExtensionCommandOverride,RegisteredExtensionExporter,RegisteredExtensionFlagDefinitions,RegisteredExtensionImporter,RegisteredExtensionParserOverride,RegisteredExtensionPreflightOverride,RegisteredExtensionProjectProfile,RegisteredExtensionRendererOverride,RegisteredExtensionSchemaFieldDefinitions,RegisteredExtensionSchemaItemTypeDefinitions,RegisteredExtensionSchemaMigrationDefinition,RegisteredExtensionSearchProvider,RegisteredExtensionServiceOverride,RegisteredExtensionVectorStoreAdapter,RendererOverrideContext,RendererOverrideResult,SchemaFieldDefinition,SchemaItemTypeDefinition,SearchProviderEmbedBatchContext,SearchProviderEmbedContext,SearchProviderQueryContext,SearchProviderQueryExpansionContext,SearchProviderQueryExpansionResult,SearchProviderQueryResult,SearchProviderRerankContext,SearchProviderRerankResult,ServiceOverrideContext,ServiceOverrideResult,VectorStoreDeleteContext,VectorStoreQueryContext,VectorStoreQueryHit,VectorStoreUpsertContext}from "../core/extensions/loader.js";import{describeExtensionBlueprint,lintExtensionBlueprint}from "./compose.js";import{describeExtensionActivation}from "../core/extensions/activation-summary.js";import type{DescribeExtensionActivationOptions,ExtensionActivationSummary}from "../core/extensions/activation-summary.js";import type{ProjectProfileDefinition}from "../core/profile/profile-presets.js";import{type ProjectProfileLintReport}from "../core/profile/profile-lint.js";import{renderExtensionSurfaceMarkdown}from "../core/extensions/activation-summary-markdown.js";import type{ExtensionSurfaceMarkdownOptions}from "../core/extensions/activation-summary-markdown.js";import type{ExtensionBlueprint,ExtensionBlueprintLintCode,ExtensionBlueprintLintFinding,ExtensionBlueprintLintResult,ExtensionBlueprintLintSeverity,ExtensionManifestCompatibilityManifest,ExtensionManifestCompatibilityResult,ExtensionManifestCompatibilityTarget,ExtensionPreflightReport,LintExtensionBlueprintOptions,PreflightExtensionOptions}from "./compose.js";import type{GlobalOptions}from "../core/shared/command-types.js";import type{PmPackageManifest,PmPackageResourceKind}from "../core/packages/manifest.js";
6
+ import type{AfterCommandHookContext,BeforeCommandHookContext,BeforeMutationHookContext,MutationActor,CommandHandlerResult,CommandOverrideContext,CommandOverrideResult,ExtensionActivationResult,ExtensionCapability,ExtensionCommandRegistry,ExtensionDeactivationResult,ExtensionGovernancePolicy,ExtensionHookRegistry,ExtensionCommandSdk,ExtensionLayer,ExtensionManifest,ExtensionParserRegistry,ExtensionPreflightRegistry,ExtensionRegistrationRegistry,ExtensionRendererRegistry,ExtensionServiceName,ExtensionServiceRegistry,FlagDefinition,OnIndexHookContext,OnReadHookContext,OnWriteHookContext,OutputRendererFormat,ParserOverrideContext,ParserOverrideResult,PreflightOverrideContext,PreflightOverrideResult,RegisteredExtensionCommandDefinition,RegisteredExtensionCommandOverride,RegisteredExtensionExporter,RegisteredExtensionFlagDefinitions,RegisteredExtensionImporter,RegisteredExtensionParserOverride,RegisteredExtensionPreflightOverride,RegisteredExtensionProjectProfile,RegisteredExtensionRendererOverride,RegisteredExtensionSchemaFieldDefinitions,RegisteredExtensionSchemaItemTypeDefinitions,RegisteredExtensionSchemaMigrationDefinition,RegisteredExtensionSearchProvider,RegisteredExtensionServiceOverride,RegisteredExtensionVectorStoreAdapter,RendererOverrideContext,RendererOverrideResult,SchemaFieldDefinition,SchemaItemTypeDefinition,SearchProviderEmbedBatchContext,SearchProviderEmbedContext,SearchProviderQueryContext,SearchProviderQueryExpansionContext,SearchProviderQueryExpansionResult,SearchProviderQueryResult,SearchProviderRerankContext,SearchProviderRerankResult,ServiceOverrideContext,ServiceOverrideResult,VectorStoreDeleteContext,VectorStoreQueryContext,VectorStoreQueryHit,VectorStoreUpsertContext}from "../core/extensions/loader.js";import type{MutationGuardOverride}from "../core/extensions/extension-hook-runtime.js";import type{MutationCompensation}from "../core/extensions/extension-types.js";
7
+ /** A guard refusal a journal-proven rollback recorded instead of obeying (pm-wb6ktl). */
8
+ export type{MutationGuardOverride};import{describeExtensionBlueprint,lintExtensionBlueprint}from "./compose.js";import{describeExtensionActivation}from "../core/extensions/activation-summary.js";import type{DescribeExtensionActivationOptions,ExtensionActivationSummary}from "../core/extensions/activation-summary.js";import type{ProjectProfileDefinition}from "../core/profile/profile-presets.js";import{type ProjectProfileLintReport}from "../core/profile/profile-lint.js";import{renderExtensionSurfaceMarkdown}from "../core/extensions/activation-summary-markdown.js";import type{ExtensionSurfaceMarkdownOptions}from "../core/extensions/activation-summary-markdown.js";import type{ExtensionBlueprint,ExtensionBlueprintLintCode,ExtensionBlueprintLintFinding,ExtensionBlueprintLintResult,ExtensionBlueprintLintSeverity,ExtensionManifestCompatibilityManifest,ExtensionManifestCompatibilityResult,ExtensionManifestCompatibilityTarget,ExtensionPreflightReport,LintExtensionBlueprintOptions,PreflightExtensionOptions}from "./compose.js";import type{GlobalOptions}from "../core/shared/command-types.js";import type{PmPackageManifest,PmPackageResourceKind}from "../core/packages/manifest.js";
7
9
  /** Host-pinned TOON codecs for semantic package-output assertions without deep imports. */
8
10
  export{decode as decodeToon,encode as encodeToon}from "@toon-format/toon";
9
11
  /** Codec options and JSON values owned by the exact implementation used by the host. */
@@ -54,8 +56,10 @@ pmRoot:string;global:GlobalOptions;})=> ExtensionCommandSdk;}
54
56
  * optional so tests written before GH-1719 keep compiling: an omitted actor is
55
57
  * resolved from `author` exactly as a host resolves it (an omitted author is
56
58
  * the unattributed `unknown` actor), and an omitted `dry_run` is `false`.
59
+ * It never carries `compensation`: a rollback context is the
60
+ * {@link RunRegisteredMutationGuardRollbackForTestOptions} context instead.
57
61
  */
58
- export type MutationGuardTestContext=Omit<BeforeMutationHookContext,"actor"|"dry_run">&{
62
+ export type MutationGuardTestContext=Omit<BeforeMutationHookContext,"actor"|"dry_run"|"compensation">&{
59
63
  /** Actor the guard should see; overrides `author`. */
60
64
  actor?:MutationActor;
61
65
  /** Author to resolve the actor from when `actor` is omitted. */
@@ -423,7 +427,19 @@ export declare function deactivateExtensionForTest(module:unknown,options?:Deact
423
427
  * propagates the throw, matching runtime semantics.
424
428
  */
425
429
  export declare function runRegisteredCommandForTest(commands:ExtensionCommandRegistry,options:RunRegisteredCommandForTestOptions):Promise<CommandHandlerResult>;
426
- /** Invoke registered transactional mutation guards through the same fail-closed runtime used by real writes. */
430
+ /** Guard-test options whose context is a journal-proven transaction rollback (pm-wb6ktl). */
431
+ export interface RunRegisteredMutationGuardRollbackForTestOptions extends RunRegisteredMutationGuardForTestOptions{
432
+ /** Synthetic rollback context: `compensation` names the transaction step being undone. */
433
+ context:MutationGuardTestContext&{compensation:MutationCompensation;};}
434
+ /**
435
+ * Invoke registered transactional mutation guards through the same fail-closed
436
+ * runtime used by real writes: a denial or failure refuses. A context carrying
437
+ * `compensation` is a journal-proven rollback instead (pm-wb6ktl): each denial
438
+ * or failure is recorded rather than refused, and the helper resolves the list
439
+ * a host records in the rollback's history entry.
440
+ */
441
+ export declare function runRegisteredMutationGuardForTest(hooks:ExtensionHookRegistry,options:RunRegisteredMutationGuardRollbackForTestOptions):Promise<MutationGuardOverride[]>;
442
+ /** Invoke the guards for an ordinary write; a denial or failure refuses. */
427
443
  export declare function runRegisteredMutationGuardForTest(hooks:ExtensionHookRegistry,options:RunRegisteredMutationGuardForTestOptions):Promise<void>;
428
444
  /**
429
445
  * Fire every registered lifecycle hook of a given `kind` through pm's real hook
@@ -910,6 +926,8 @@ assertCapabilityUsage(expectation:ExtensionCapabilityUsageExpectation):Extension
910
926
  runCommand(options:RunRegisteredCommandForTestOptions):Promise<CommandHandlerResult>;
911
927
  /** Bound {@link runRegisteredHookForTest} over `activation.hooks`. */
912
928
  runHook(options:RunRegisteredHookForTestOptions):Promise<string[]>;
929
+ /** Bound transactional mutation-guard runner over `activation.hooks`; a rollback context resolves the recorded overrides. */
930
+ runMutationGuard(options:RunRegisteredMutationGuardRollbackForTestOptions):Promise<MutationGuardOverride[]>;
913
931
  /** Bound transactional mutation-guard runner over `activation.hooks`. */
914
932
  runMutationGuard(options:RunRegisteredMutationGuardForTestOptions):Promise<void>;
915
933
  /** Bound {@link runRegisteredCommandOverrideForTest} over `activation.commands`. */
@@ -1,8 +1,8 @@
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]="4f61bbc3-cf6d-5a5c-91df-88b8fda25be0")}catch{}})();import{activateExtensions,deactivateExtensions,runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride}from"../core/extensions/loader.js";import{createDefaultExtensionGovernancePolicy}from"../core/extensions/extension-types.js";import{getMigrationRuntimeDefinition,resolveRegisteredSearchProvider,resolveRegisteredVectorStoreAdapter}from"../core/extensions/runtime-registrations.js";import{collectUsedExtensionCapabilities}from"../core/extensions/capability-usage.js";import{normalizeKnownExtensionCapability}from"../core/extensions/extension-capability-aliases.js";import{checkExtensionManifestCompatibility,describeExtensionBlueprint,lintExtensionBlueprint,preflightExtension}from"./compose.js";import{describeExtensionActivation}from"../core/extensions/activation-summary.js";import{lintProjectProfile}from"../core/profile/profile-lint.js";import{renderExtensionSurfaceMarkdown}from"../core/extensions/activation-summary-markdown.js";import{asPropertyRecord,resolveActivatablePropertyRecord}from"../core/shared/primitives.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{collectExtensionFlagDefinitionsForCommand,normalizeDirectExtensionCommandOptions}from"./extension/command-options.js";import{resolveDirectExtensionOptionPolicy}from"./extension/native-command-options.js";import{formatOutput,projectPrintedResult}from"../core/output/output.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{resolvePortableWorkspaceContext,runWithIsolatedExtensionRuntime,setActiveCommandContext,setActiveExtensionCommands,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices}from"../core/extensions/index.js";import{PmClient}from"./runtime.js";import{decode,encode}from"@toon-format/toon";const ACTIVATED_COMMAND_FLAG_REGISTRATIONS=Symbol.for("pm.sdk.testing.activatedFlagRegistrations");function readActivatedFlagRegistrations(commands){return commands[ACTIVATED_COMMAND_FLAG_REGISTRATIONS]}const ACTIVATED_COMMAND_SERVICES=Symbol.for("pm.sdk.testing.activatedServices"),ACTIVATED_COMMAND_RENDERERS=Symbol.for("pm.sdk.testing.activatedRenderers");function readActivatedRenderers(commands){return commands[ACTIVATED_COMMAND_RENDERERS]}function readActivatedServices(commands){return commands[ACTIVATED_COMMAND_SERVICES]}async function admitRegisteredReadOutputResult(registrations,commands,context,outcome){if(registrations===void 0||!outcome.handled||[...registrations.commands].reverse().find(entry=>entry.command===context.command)?.read_output===void 0)return outcome;const exitCode=process.exitCode;let omittedForBudget=!1;return await runWithIsolatedExtensionRuntime(async()=>{setActiveExtensionCommands(commands),setActiveExtensionServices(readActivatedServices(commands)??null),setActiveExtensionRenderers(readActivatedRenderers(commands)??null),setActiveExtensionRegistrations(registrations),setActiveCommandContext({command:context.command,args:context.args,options:context.options,global:context.global,pm_root:context.pm_root});const global2=context.global;process.exitCode=0;try{formatOutput(projectPrintedResult(outcome.result,global2),{...global2,command:context.command,commandArgs:context.args,commandOptions:context.options,pmRoot:context.pm_root}),omittedForBudget=process.exitCode===EXIT_CODE.USAGE}finally{process.exitCode=exitCode}}),omittedForBudget&&refuseOmittedForBudget(context.command),outcome}function refuseOmittedForBudget(command){throw new PmCliError(`Read output for extension command '${command}' does not fit the requested output budget; native delivery omits the result and exits 2.`,EXIT_CODE.USAGE,{code:"output_budget_exceeded",required:"Raise outputBudget, or return fewer or smaller rows so the delivered output fits.",why:"The delivered output, including any output_format or renderer string, answers to the caller's output budget, and an infeasible budget omits the result natively.",nextSteps:["Re-run with a larger outputBudget, or without one, to inspect the full result."]})}function registeredExpectationName(expectation,legacyValue){return expectation.name??legacyValue??""}const HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"},RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function normalizeSdkIdentifier(value){return value.trim().toLowerCase()}function normalizeSdkProfileMatchKey(value){return normalizeSdkIdentifier(value).replaceAll("-","_")}function extensionNameSuffix(extensionName){return extensionName?` from extension "${extensionName}"`:""}function sortedUnique(values){return[...new Set(values)].sort((left,right)=>left.localeCompare(right))}function normalizeSdkCommandName(command){if(typeof command!="string")throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.');return command.trim().toLowerCase().split(/\s+/).filter(part=>part.length>0).join(" ")}function formatAvailable(values){return values.length>0?values.join(", "):"(none)"}function assertStringSetIncludes(actual,expected,label){const actualValues=new Set(actual??[]),missing=sortedUnique(expected.filter(value=>!actualValues.has(value)));if(missing.length>0)throw new Error(`Expected package manifest ${label} to include ${missing.join(", ")}; available: ${formatAvailable(sortedUnique(actual??[]))}`)}function collectFlagLabels(flags){const labels=new Set;for(const flag of flags)typeof flag.long=="string"&&flag.long.trim().length>0&&labels.add(flag.long.trim()),typeof flag.short=="string"&&flag.short.trim().length>0&&labels.add(flag.short.trim());return labels}function readTestExtensionManifest(module){const moduleRecord=asPropertyRecord(module);if(!moduleRecord)return{};const manifest=asPropertyRecord(moduleRecord.manifest);if(manifest)return manifest;const defaultExport=asPropertyRecord(moduleRecord.default);return asPropertyRecord(defaultExport?.manifest)||(defaultExport&&typeof moduleRecord.default!="function"&&("name"in defaultExport||"capabilities"in defaultExport)?defaultExport:typeof module!="function"&&("name"in moduleRecord||"capabilities"in moduleRecord)?moduleRecord:{})}function resolveTestExtensionName(manifest,explicitName){return explicitName??(typeof manifest.name=="string"&&manifest.name.trim().length>0?manifest.name.trim():"test-extension")}function readTestExtensionCapabilities(manifest,options){return Array.isArray(options.capabilities)?[...options.capabilities]:Array.isArray(manifest.capabilities)?manifest.capabilities.filter(capability=>typeof capability=="string"):[]}function buildSingleExtensionLoadResult(module,manifest,identity){return{disabled_by_flag:!1,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:identity.policy,failed:[],loaded:[{layer:identity.layer,directory:"",manifest_path:"",name:identity.name,version:typeof manifest.version=="string"?manifest.version:"0.0.0",entry:typeof manifest.entry=="string"?manifest.entry:"./index.js",priority:typeof manifest.priority=="number"?manifest.priority:0,entry_path:"",capabilities:identity.capabilities,manifest_version:typeof manifest.manifest_version=="number"?manifest.manifest_version:void 0,pm_min_version:typeof manifest.pm_min_version=="string"?manifest.pm_min_version:void 0,pm_max_version:typeof manifest.pm_max_version=="string"?manifest.pm_max_version:void 0,engines:manifest.engines,trusted:manifest.trusted,provenance:manifest.provenance,sandbox_profile:manifest.sandbox_profile,permissions:manifest.permissions,activation:manifest.activation,module}]}}async function activateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module),activation=await activateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,options),policy:options.policy??createDefaultExtensionGovernancePolicy()}));return Object.defineProperty(activation.commands,ACTIVATED_COMMAND_FLAG_REGISTRATIONS,{value:activation.registrations,enumerable:!1}),Object.defineProperty(activation.commands,ACTIVATED_COMMAND_SERVICES,{value:activation.services,enumerable:!1}),Object.defineProperty(activation.commands,ACTIVATED_COMMAND_RENDERERS,{value:activation.renderers,enumerable:!1}),activation}async function deactivateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module);return deactivateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,{}),policy:createDefaultExtensionGovernancePolicy()}),options.activation,options.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:options.deactivateTimeoutMs})}async function runRegisteredCommandForTest(commands,options){const command=normalizeSdkCommandName(options.command);if(command.length===0)throw new Error("Expected command name must be a non-empty string");if(!commands.handlers.some(entry=>entry.command===command)){const available=sortedUnique(commands.handlers.map(entry=>entry.command));throw new Error(`Expected a registered command handler for "${command}" to invoke. Available command handlers: ${formatAvailable(available)}`)}if(options.sdk!==void 0&&options.sdkFactory!==void 0)throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both");const pmRoot=options.pmRoot??"",global2={json:!0,quiet:!0,noPager:!0,...options.global},sdk=options.sdk??options.sdkFactory?.({pmRoot,global:global2})??(pmRoot.length>0?createExtensionCommandSdk(pmRoot,new PmClient({pmRoot}),void 0,command):void 0),registrations=readActivatedFlagRegistrations(commands),handlerOptions=options.options?{...options.options}:{},context={command,args:options.args?[...options.args]:[],options:registrations===void 0?handlerOptions:normalizeDirectExtensionCommandOptions(handlerOptions,collectExtensionFlagDefinitionsForCommand(registrations,command),command,resolveDirectExtensionOptionPolicy(command)),global:global2,pm_root:pmRoot,...resolvePortableWorkspaceContext(pmRoot.length>0?pmRoot:void 0),...sdk===void 0?{}:{sdk}},outcome=await runCommandHandler(commands,context);return await admitRegisteredReadOutputResult(registrations,commands,context,outcome)}async function runRegisteredMutationGuardForTest(hooks,options){if((hooks.beforeMutation?.length??0)===0)throw new Error("Expected a registered before_mutation hook to invoke");const{actor,author,dry_run:dryRun,...context}=options.context,{resolveMutationActor}=await import("../core/extensions/mutation-actor.js");await runBeforeMutationHooks(hooks,{...context,actor:actor??resolveMutationActor(author??"unknown"),dry_run:dryRun===!0})}async function runRegisteredHookForTest(hooks,options){const kind=options.kind;if(kind==="before_mutation")throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.");if((hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[kind]]?.length??0)===0){const populatedKinds=sortedUnique(Object.keys(RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD).filter(candidateKind=>(hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[candidateKind]]?.length??0)>0));throw new Error(`Expected a registered "${kind}" hook to invoke. Hook kinds with registrations: ${formatAvailable(populatedKinds)}`)}switch(options.kind){case"before_command":return runBeforeCommandHooks(hooks,options.context);case"after_command":return runAfterCommandHooks(hooks,options.context);case"on_read":return runOnReadHooks(hooks,options.context);case"on_write":return runOnWriteHooks(hooks,options.context);case"on_index":return runOnIndexHooks(hooks,options.context)}}async function runRegisteredParserOverrideForTest(parsers,context){const command=normalizeSdkCommandName(context.command);if(!parsers.overrides.some(entry=>entry.command===command))throw new Error(`Expected a registered parser override for command "${command}" to invoke. Available parser override commands: ${formatAvailable(sortedUnique(parsers.overrides.map(entry=>entry.command)))}`);return runParserOverride(parsers,context)}async function runRegisteredPreflightOverrideForTest(preflight,context){if(preflight.overrides.length===0)throw new Error("Expected a registered preflight override to invoke, but none are registered.");return runPreflightOverride(preflight,context)}async function runRegisteredCommandOverrideForTest(commands,context){const command=normalizeSdkCommandName(context.command);if(!commands.overrides.some(entry=>entry.command===command))throw new Error(`Expected a registered command override for command "${command}" to invoke. Available command override commands: ${formatAvailable(sortedUnique(commands.overrides.map(entry=>entry.command)))}`);return runCommandOverride(commands,context)}async function runRegisteredRendererOverrideForTest(renderers,context){if(!renderers.overrides.some(entry=>entry.format===context.format))throw new Error(`Expected a registered renderer override for format "${context.format}" to invoke. Available renderer override formats: ${formatAvailable(sortedUnique(renderers.overrides.map(entry=>entry.format)))}`);return runRendererOverride(renderers,context)}async function runRegisteredServiceOverrideForTest(services,context){if(!services.overrides.some(entry=>entry.service===context.service))throw new Error(`Expected a registered service override for service "${context.service}" to invoke. Available service override services: ${formatAvailable(sortedUnique(services.overrides.map(entry=>entry.service)))}`);return runServiceOverride(services,context)}const SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function runRegisteredSearchProviderForTest(registrations,options){const registration=resolveRegisteredSearchProvider(registrations,options.provider);if(!registration){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected a registered search provider "${options.provider}" to invoke. Available search providers: ${formatAvailable(available)}`)}const runtimeDefinition=registration.runtime_definition,operationFn=SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS[options.operation].map(key=>runtimeDefinition[key]).find(value=>typeof value=="function");if(typeof operationFn!="function")throw new Error(`Registered search provider "${options.provider}" does not implement the "${options.operation}" operation.`);return await operationFn(options.context)}async function runRegisteredVectorStoreAdapterForTest(registrations,options){const registration=resolveRegisteredVectorStoreAdapter(registrations,options.adapter);if(!registration){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected a registered vector store adapter "${options.adapter}" to invoke. Available vector store adapters: ${formatAvailable(available)}`)}const operationFn=registration.runtime_definition[options.operation];if(typeof operationFn!="function")throw new Error(`Registered vector store adapter "${options.adapter}" does not implement the "${options.operation}" operation.`);return await operationFn(options.context)}async function runRegisteredMigrationForTest(registrations,options){const migration=assertRegisteredMigration(registrations,{migration:options.migration,extensionName:options.extensionName}),run=getMigrationRuntimeDefinition(migration).run;if(typeof run!="function")throw new Error(`Registered migration "${options.migration}" does not implement a run function to invoke.`);const declaredStatus=migration.definition.status,context={id:migration.definition.id,command:"migration",layer:migration.layer,extension:migration.name,pm_root:options.pmRoot??"",status:(typeof declaredStatus=="string"?declaredStatus.trim().toLowerCase():"")||"pending"};return await run(context)}async function runRegisteredImporterForTest(activation,options){const importer=assertRegisteredImporter(activation.registrations,{importer:options.importer,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${importer.importer} import`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}async function runRegisteredExporterForTest(activation,options){const exporter=assertRegisteredExporter(activation.registrations,{exporter:options.exporter,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${exporter.exporter} export`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}function assertExtensionDeactivated(result,expectation={}){const expectedDeactivated=expectation.deactivated??1;if(result.deactivated!==expectedDeactivated)throw new Error(`Expected ${expectedDeactivated} extension${expectedDeactivated===1?"":"s"} to deactivate cleanly, but ${result.deactivated} did.`);const expectedFailed=expectation.failed??0;if(result.failed.length!==expectedFailed){const detail=result.failed.map(failure=>`${failure.layer}:${failure.name} (${failure.error})`).join(", ");throw new Error(`Expected ${expectedFailed} teardown failure${expectedFailed===1?"":"s"}, but observed ${result.failed.length}${detail.length>0?`: ${detail}`:""}.`)}return result}function assertPackageManifest(manifest,expectation){if(expectation.packageName!==void 0&&manifest.package_name!==expectation.packageName)throw new Error(`Expected package manifest package_name to be "${expectation.packageName}"; received "${manifest.package_name??"(none)"}"`);if(expectation.aliases!==void 0&&assertStringSetIncludes(manifest.aliases,expectation.aliases,"aliases"),expectation.resources!==void 0)for(const[kind,expectedPaths]of Object.entries(expectation.resources))assertStringSetIncludes(manifest.resources[kind],expectedPaths,`pm.${kind}`);return manifest}function assertRegisteredCommandContract(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const commandCandidates=registrations.commands.filter(entry=>entry.command===expectedCommand),command=expectation.extensionName?commandCandidates.find(entry=>entry.name===expectation.extensionName):commandCandidates[0];if(!command){const available=registrations.commands.map(entry=>entry.command).sort((left,right)=>left.localeCompare(right)),extensionSuffix=expectation.extensionName?` from extension "${expectation.extensionName}"`:"";throw new Error(`Expected extension command "${expectedCommand}"${extensionSuffix} to be registered. Available commands: ${formatAvailable(available)}`)}if(expectation.action!==void 0&&command.action!==expectation.action)throw new Error(`Expected extension command "${expectedCommand}" action "${expectation.action}", received "${command.action}"`);if(expectation.arguments!==void 0){const actualArguments=(command.arguments??[]).map(argument=>argument.name),missingArguments=expectation.arguments.filter(argument=>!actualArguments.includes(argument));if(missingArguments.length>0)throw new Error(`Expected extension command "${expectedCommand}" arguments ${formatAvailable(expectation.arguments)}; missing ${formatAvailable(missingArguments)}; available ${formatAvailable(actualArguments)}`)}const flags=registrations.flags.filter(entry=>entry.target_command===expectedCommand&&(expectation.extensionName===void 0||entry.name===expectation.extensionName)).flatMap(entry=>entry.flags);if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(flags),missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0)throw new Error(`Expected extension command "${expectedCommand}" flags ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}return{command,flags}}function assertRegisteredFlags(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.targetCommand));if(expectedCommand.length===0)throw new Error("Expected target command name must be a non-empty string");const candidates=registrations.flags.filter(entry=>entry.target_command===expectedCommand);let registration;if(expectation.extensionName)registration=candidates.find(entry=>entry.name===expectation.extensionName);else if(candidates.length===1)registration=candidates[0];else if(candidates.length>1){const availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}" matched multiple extensions: ${formatAvailable(availableExtensions)}. Specify extensionName to choose one registration.`)}if(!registration){const available=sortedUnique(registrations.flags.map(entry=>entry.target_command)),availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available flag target commands: ${formatAvailable(available)}; matching extensions: ${formatAvailable(availableExtensions)}`)}if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(registration.flags),missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0)throw new Error(`Expected flags for target command "${expectedCommand}" to include ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}return registration}function assertRegisteredHook(hooks,expectation){const field=HOOK_KIND_TO_REGISTRY_FIELD[expectation.kind],candidates=hooks[field]??[],hook=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!hook){const available=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected a "${expectation.kind}" hook${extensionNameSuffix(expectation.extensionName)} to be registered. Available "${expectation.kind}" hooks: ${formatAvailable(available)}`)}return hook}function assertRegisteredSearchProvider(registrations,expectation){const expectedProvider=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.provider));if(expectedProvider.length===0)throw new Error("Expected search provider name must be a non-empty string");const candidates=registrations.search_providers.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedProvider),provider=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!provider){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected search provider "${expectedProvider}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available search providers: ${formatAvailable(available)}`)}return provider}function assertRegisteredVectorStoreAdapter(registrations,expectation){const expectedAdapter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.adapter));if(expectedAdapter.length===0)throw new Error("Expected vector store adapter name must be a non-empty string");const candidates=registrations.vector_store_adapters.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedAdapter),adapter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!adapter){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected vector store adapter "${expectedAdapter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available vector store adapters: ${formatAvailable(available)}`)}return adapter}function assertRegisteredImporter(registrations,expectation){const expectedImporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.importer));if(expectedImporter.length===0)throw new Error("Expected importer name must be a non-empty string");const candidates=registrations.importers.filter(entry=>normalizeSdkIdentifier(entry.importer)===expectedImporter),importer=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!importer){const available=sortedUnique(registrations.importers.map(entry=>entry.importer));throw new Error(`Expected importer "${expectedImporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available importers: ${formatAvailable(available)}`)}return importer}function assertRegisteredExporter(registrations,expectation){const expectedExporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.exporter));if(expectedExporter.length===0)throw new Error("Expected exporter name must be a non-empty string");const candidates=registrations.exporters.filter(entry=>normalizeSdkIdentifier(entry.exporter)===expectedExporter),exporter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!exporter){const available=sortedUnique(registrations.exporters.map(entry=>entry.exporter));throw new Error(`Expected exporter "${expectedExporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available exporters: ${formatAvailable(available)}`)}return exporter}function assertRegisteredItemField(registrations,expectation){const expectedField=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.field));if(expectedField.length===0)throw new Error("Expected item field name must be a non-empty string");const match=registrations.item_fields.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,field:registration.fields.find(field=>normalizeSdkIdentifier(field.name)===expectedField)})).filter(entry=>entry.field!==void 0).find(entry=>expectation.type===void 0||entry.field.type===expectation.type);if(!match){const available=sortedUnique(registrations.item_fields.flatMap(entry=>entry.fields.map(field=>`${field.name}:${field.type}`)));throw new Error(`Expected item field "${expectedField}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item fields: ${formatAvailable(available)}`)}return match}function assertRegisteredItemType(registrations,expectation){const expectedType=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.itemType));if(expectedType.length===0)throw new Error("Expected item type name must be a non-empty string");const match=registrations.item_types.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,itemType:registration.types.find(itemType=>normalizeSdkIdentifier(itemType.name)===expectedType)})).filter(entry=>entry.itemType!==void 0).find(entry=>expectation.folder===void 0||entry.itemType.folder===expectation.folder);if(!match){const available=sortedUnique(registrations.item_types.flatMap(entry=>entry.types.map(itemType=>`${itemType.name}:${itemType.folder}`)));throw new Error(`Expected item type "${expectedType}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item types: ${formatAvailable(available)}`)}return match}function assertRegisteredProfile(registrations,expectation){const expectedProfile=normalizeSdkProfileMatchKey(registeredExpectationName(expectation,expectation.profile));if(expectedProfile.length===0)throw new Error("Expected profile name must be a non-empty string");const match=registrations.profiles.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).find(entry=>normalizeSdkProfileMatchKey(entry.profile.name)===expectedProfile);if(!match){const available=sortedUnique(registrations.profiles.map(entry=>entry.profile.name));throw new Error(`Expected profile "${expectedProfile}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available profiles: ${formatAvailable(available)}`)}return{registration:match,profile:match.profile}}function assertRegisteredCommandOverride(commands,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const candidates=commands.overrides.filter(entry=>entry.command===expectedCommand),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(commands.overrides.map(entry=>entry.command));throw new Error(`Expected command override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available command overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredParserOverride(parsers,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const candidates=parsers.overrides.filter(entry=>entry.command===expectedCommand),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(parsers.overrides.map(entry=>entry.command));throw new Error(`Expected parser override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available parser overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredPreflightOverride(preflight,expectation={}){const override=expectation.extensionName?preflight.overrides.find(entry=>entry.name===expectation.extensionName):preflight.overrides[0];if(!override){const available=sortedUnique(preflight.overrides.map(entry=>entry.name));throw new Error(`Expected a preflight override${extensionNameSuffix(expectation.extensionName)} to be registered. Available preflight overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredRendererOverride(renderers,expectation){const expectedFormat=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.format));if(expectedFormat.length===0)throw new Error("Expected renderer format must be a non-empty string");const candidates=renderers.overrides.filter(entry=>entry.format===expectedFormat),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(renderers.overrides.map(entry=>entry.format));throw new Error(`Expected renderer override "${expectedFormat}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available renderer overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredServiceOverride(services,expectation){const expectedService=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.service));if(expectedService.length===0)throw new Error("Expected service name must be a non-empty string");const candidates=services.overrides.filter(entry=>normalizeSdkIdentifier(entry.service)===expectedService),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(services.overrides.map(entry=>entry.service));throw new Error(`Expected service override "${expectedService}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available service overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredMigration(registrations,expectation){const expectedMigration=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.migration));if(expectedMigration.length===0)throw new Error("Expected migration id must be a non-empty string");const candidates=registrations.migrations.filter(entry=>(expectation.extensionName===void 0||entry.name===expectation.extensionName)&&typeof entry.definition.id=="string"&&normalizeSdkIdentifier(entry.definition.id)===expectedMigration),match=candidates.find(entry=>expectation.mandatory===void 0||(entry.definition.mandatory??!1)===expectation.mandatory);if(match)return match;const idMatch=candidates[0];if(idMatch!==void 0)throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to have mandatory=${expectation.mandatory}, but it is mandatory=${idMatch.definition.mandatory??!1}.`);const available=sortedUnique(registrations.migrations.map(entry=>`${typeof entry.definition.id=="string"&&entry.definition.id.trim().length>0?entry.definition.id.trim():"(unnamed)"}:${entry.definition.mandatory===!0}`));throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available migrations: ${formatAvailable(available)}`)}function assertExtensionCapabilityUsage(activation,expectation){const toKnownCapabilitySet=(capabilities,field)=>{const known=new Set;for(const capability of capabilities){const normalized=normalizeKnownExtensionCapability(capability);if(normalized===null)throw new Error(`Expected ${field} capability "${capability}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`);known.add(normalized)}return known},declared=[...toKnownCapabilitySet(expectation.declared,"declared")].sort((left,right)=>left.localeCompare(right)),allowUnused=toKnownCapabilitySet(expectation.allowUnused??[],"allowUnused"),used=collectUsedExtensionCapabilities(activation,{extensionName:expectation.extensionName}),usedSet=new Set(used),unused=declared.filter(capability=>!usedSet.has(capability)&&!allowUnused.has(capability));if(unused.length>0){const scopeSuffix=extensionNameSuffix(expectation.extensionName);throw new Error(`Expected every declared capability${scopeSuffix} to be exercised, but [${unused.join(", ")}] ${unused.length===1?"is":"are"} declared yet never registered against. Remove ${unused.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared,used,unused}}function assertExtensionBlueprint(blueprint,options={}){const result=lintExtensionBlueprint(blueprint,options);if(!result.ok){const errors=result.findings.filter(finding=>finding.severity==="error");throw new Error(`Extension blueprint failed preflight with ${errors.length} ${errors.length===1?"error":"errors"}:
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]="dbbb4176-3bf3-57b0-877f-f413dd5dcc52")}catch{}})();import{activateExtensions,deactivateExtensions,runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride}from"../core/extensions/loader.js";import{createDefaultExtensionGovernancePolicy}from"../core/extensions/extension-types.js";import{getMigrationRuntimeDefinition,resolveRegisteredSearchProvider,resolveRegisteredVectorStoreAdapter}from"../core/extensions/runtime-registrations.js";import{collectUsedExtensionCapabilities}from"../core/extensions/capability-usage.js";import{normalizeKnownExtensionCapability}from"../core/extensions/extension-capability-aliases.js";import{checkExtensionManifestCompatibility,describeExtensionBlueprint,lintExtensionBlueprint,preflightExtension}from"./compose.js";import{describeExtensionActivation}from"../core/extensions/activation-summary.js";import{lintProjectProfile}from"../core/profile/profile-lint.js";import{renderExtensionSurfaceMarkdown}from"../core/extensions/activation-summary-markdown.js";import{asPropertyRecord,resolveActivatablePropertyRecord}from"../core/shared/primitives.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{collectExtensionFlagDefinitionsForCommand,normalizeDirectExtensionCommandOptions}from"./extension/command-options.js";import{resolveDirectExtensionOptionPolicy}from"./extension/native-command-options.js";import{formatOutput,projectPrintedResult}from"../core/output/output.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{resolvePortableWorkspaceContext,runWithIsolatedExtensionRuntime,setActiveCommandContext,setActiveExtensionCommands,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices}from"../core/extensions/index.js";import{PmClient}from"./runtime.js";import{decode,encode}from"@toon-format/toon";const ACTIVATED_COMMAND_FLAG_REGISTRATIONS=Symbol.for("pm.sdk.testing.activatedFlagRegistrations");function readActivatedFlagRegistrations(commands){return commands[ACTIVATED_COMMAND_FLAG_REGISTRATIONS]}const ACTIVATED_COMMAND_SERVICES=Symbol.for("pm.sdk.testing.activatedServices"),ACTIVATED_COMMAND_RENDERERS=Symbol.for("pm.sdk.testing.activatedRenderers");function readActivatedRenderers(commands){return commands[ACTIVATED_COMMAND_RENDERERS]}function readActivatedServices(commands){return commands[ACTIVATED_COMMAND_SERVICES]}async function admitRegisteredReadOutputResult(registrations,commands,context,outcome){if(registrations===void 0||!outcome.handled||[...registrations.commands].reverse().find(entry=>entry.command===context.command)?.read_output===void 0)return outcome;const exitCode=process.exitCode;let omittedForBudget=!1;return await runWithIsolatedExtensionRuntime(async()=>{setActiveExtensionCommands(commands),setActiveExtensionServices(readActivatedServices(commands)??null),setActiveExtensionRenderers(readActivatedRenderers(commands)??null),setActiveExtensionRegistrations(registrations),setActiveCommandContext({command:context.command,args:context.args,options:context.options,global:context.global,pm_root:context.pm_root});const global2=context.global;process.exitCode=0;try{formatOutput(projectPrintedResult(outcome.result,global2),{...global2,command:context.command,commandArgs:context.args,commandOptions:context.options,pmRoot:context.pm_root}),omittedForBudget=process.exitCode===EXIT_CODE.USAGE}finally{process.exitCode=exitCode}}),omittedForBudget&&refuseOmittedForBudget(context.command),outcome}function refuseOmittedForBudget(command){throw new PmCliError(`Read output for extension command '${command}' does not fit the requested output budget; native delivery omits the result and exits 2.`,EXIT_CODE.USAGE,{code:"output_budget_exceeded",required:"Raise outputBudget, or return fewer or smaller rows so the delivered output fits.",why:"The delivered output, including any output_format or renderer string, answers to the caller's output budget, and an infeasible budget omits the result natively.",nextSteps:["Re-run with a larger outputBudget, or without one, to inspect the full result."]})}function registeredExpectationName(expectation,legacyValue){return expectation.name??legacyValue??""}const HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"},RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function normalizeSdkIdentifier(value){return value.trim().toLowerCase()}function normalizeSdkProfileMatchKey(value){return normalizeSdkIdentifier(value).replaceAll("-","_")}function extensionNameSuffix(extensionName){return extensionName?` from extension "${extensionName}"`:""}function sortedUnique(values){return[...new Set(values)].sort((left,right)=>left.localeCompare(right))}function normalizeSdkCommandName(command){if(typeof command!="string")throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.');return command.trim().toLowerCase().split(/\s+/).filter(part=>part.length>0).join(" ")}function formatAvailable(values){return values.length>0?values.join(", "):"(none)"}function assertStringSetIncludes(actual,expected,label){const actualValues=new Set(actual??[]),missing=sortedUnique(expected.filter(value=>!actualValues.has(value)));if(missing.length>0)throw new Error(`Expected package manifest ${label} to include ${missing.join(", ")}; available: ${formatAvailable(sortedUnique(actual??[]))}`)}function collectFlagLabels(flags){const labels=new Set;for(const flag of flags)typeof flag.long=="string"&&flag.long.trim().length>0&&labels.add(flag.long.trim()),typeof flag.short=="string"&&flag.short.trim().length>0&&labels.add(flag.short.trim());return labels}function readTestExtensionManifest(module){const moduleRecord=asPropertyRecord(module);if(!moduleRecord)return{};const manifest=asPropertyRecord(moduleRecord.manifest);if(manifest)return manifest;const defaultExport=asPropertyRecord(moduleRecord.default);return asPropertyRecord(defaultExport?.manifest)||(defaultExport&&typeof moduleRecord.default!="function"&&("name"in defaultExport||"capabilities"in defaultExport)?defaultExport:typeof module!="function"&&("name"in moduleRecord||"capabilities"in moduleRecord)?moduleRecord:{})}function resolveTestExtensionName(manifest,explicitName){return explicitName??(typeof manifest.name=="string"&&manifest.name.trim().length>0?manifest.name.trim():"test-extension")}function readTestExtensionCapabilities(manifest,options){return Array.isArray(options.capabilities)?[...options.capabilities]:Array.isArray(manifest.capabilities)?manifest.capabilities.filter(capability=>typeof capability=="string"):[]}function buildSingleExtensionLoadResult(module,manifest,identity){return{disabled_by_flag:!1,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:identity.policy,failed:[],loaded:[{layer:identity.layer,directory:"",manifest_path:"",name:identity.name,version:typeof manifest.version=="string"?manifest.version:"0.0.0",entry:typeof manifest.entry=="string"?manifest.entry:"./index.js",priority:typeof manifest.priority=="number"?manifest.priority:0,entry_path:"",capabilities:identity.capabilities,manifest_version:typeof manifest.manifest_version=="number"?manifest.manifest_version:void 0,pm_min_version:typeof manifest.pm_min_version=="string"?manifest.pm_min_version:void 0,pm_max_version:typeof manifest.pm_max_version=="string"?manifest.pm_max_version:void 0,engines:manifest.engines,trusted:manifest.trusted,provenance:manifest.provenance,sandbox_profile:manifest.sandbox_profile,permissions:manifest.permissions,activation:manifest.activation,module}]}}async function activateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module),activation=await activateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,options),policy:options.policy??createDefaultExtensionGovernancePolicy()}));return Object.defineProperty(activation.commands,ACTIVATED_COMMAND_FLAG_REGISTRATIONS,{value:activation.registrations,enumerable:!1}),Object.defineProperty(activation.commands,ACTIVATED_COMMAND_SERVICES,{value:activation.services,enumerable:!1}),Object.defineProperty(activation.commands,ACTIVATED_COMMAND_RENDERERS,{value:activation.renderers,enumerable:!1}),activation}async function deactivateExtensionForTest(module,options={}){const manifest=readTestExtensionManifest(module);return deactivateExtensions(buildSingleExtensionLoadResult(module,manifest,{name:resolveTestExtensionName(manifest,options.name),layer:options.layer??"project",capabilities:readTestExtensionCapabilities(manifest,{}),policy:createDefaultExtensionGovernancePolicy()}),options.activation,options.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:options.deactivateTimeoutMs})}async function runRegisteredCommandForTest(commands,options){const command=normalizeSdkCommandName(options.command);if(command.length===0)throw new Error("Expected command name must be a non-empty string");if(!commands.handlers.some(entry=>entry.command===command)){const available=sortedUnique(commands.handlers.map(entry=>entry.command));throw new Error(`Expected a registered command handler for "${command}" to invoke. Available command handlers: ${formatAvailable(available)}`)}if(options.sdk!==void 0&&options.sdkFactory!==void 0)throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both");const pmRoot=options.pmRoot??"",global2={json:!0,quiet:!0,noPager:!0,...options.global},sdk=options.sdk??options.sdkFactory?.({pmRoot,global:global2})??(pmRoot.length>0?createExtensionCommandSdk(pmRoot,new PmClient({pmRoot}),void 0,command):void 0),registrations=readActivatedFlagRegistrations(commands),handlerOptions=options.options?{...options.options}:{},context={command,args:options.args?[...options.args]:[],options:registrations===void 0?handlerOptions:normalizeDirectExtensionCommandOptions(handlerOptions,collectExtensionFlagDefinitionsForCommand(registrations,command),command,resolveDirectExtensionOptionPolicy(command)),global:global2,pm_root:pmRoot,...resolvePortableWorkspaceContext(pmRoot.length>0?pmRoot:void 0),...sdk===void 0?{}:{sdk}},outcome=await runCommandHandler(commands,context);return await admitRegisteredReadOutputResult(registrations,commands,context,outcome)}async function runRegisteredMutationGuardForTest(hooks,options){if((hooks.beforeMutation?.length??0)===0)throw new Error("Expected a registered before_mutation hook to invoke");const{actor,author,dry_run:dryRun,compensation,...context}=options.context,{resolveMutationActor}=await import("../core/extensions/mutation-actor.js"),overrides=await runBeforeMutationHooks(hooks,{...context,actor:actor??resolveMutationActor(author??"unknown"),dry_run:dryRun===!0,...compensation===void 0||dryRun===!0?{}:{compensation}});return compensation===void 0?void 0:overrides}async function runRegisteredHookForTest(hooks,options){const kind=options.kind;if(kind==="before_mutation")throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.");if((hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[kind]]?.length??0)===0){const populatedKinds=sortedUnique(Object.keys(RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD).filter(candidateKind=>(hooks[RUNNABLE_HOOK_KIND_TO_REGISTRY_FIELD[candidateKind]]?.length??0)>0));throw new Error(`Expected a registered "${kind}" hook to invoke. Hook kinds with registrations: ${formatAvailable(populatedKinds)}`)}switch(options.kind){case"before_command":return runBeforeCommandHooks(hooks,options.context);case"after_command":return runAfterCommandHooks(hooks,options.context);case"on_read":return runOnReadHooks(hooks,options.context);case"on_write":return runOnWriteHooks(hooks,options.context);case"on_index":return runOnIndexHooks(hooks,options.context)}}async function runRegisteredParserOverrideForTest(parsers,context){const command=normalizeSdkCommandName(context.command);if(!parsers.overrides.some(entry=>entry.command===command))throw new Error(`Expected a registered parser override for command "${command}" to invoke. Available parser override commands: ${formatAvailable(sortedUnique(parsers.overrides.map(entry=>entry.command)))}`);return runParserOverride(parsers,context)}async function runRegisteredPreflightOverrideForTest(preflight,context){if(preflight.overrides.length===0)throw new Error("Expected a registered preflight override to invoke, but none are registered.");return runPreflightOverride(preflight,context)}async function runRegisteredCommandOverrideForTest(commands,context){const command=normalizeSdkCommandName(context.command);if(!commands.overrides.some(entry=>entry.command===command))throw new Error(`Expected a registered command override for command "${command}" to invoke. Available command override commands: ${formatAvailable(sortedUnique(commands.overrides.map(entry=>entry.command)))}`);return runCommandOverride(commands,context)}async function runRegisteredRendererOverrideForTest(renderers,context){if(!renderers.overrides.some(entry=>entry.format===context.format))throw new Error(`Expected a registered renderer override for format "${context.format}" to invoke. Available renderer override formats: ${formatAvailable(sortedUnique(renderers.overrides.map(entry=>entry.format)))}`);return runRendererOverride(renderers,context)}async function runRegisteredServiceOverrideForTest(services,context){if(!services.overrides.some(entry=>entry.service===context.service))throw new Error(`Expected a registered service override for service "${context.service}" to invoke. Available service override services: ${formatAvailable(sortedUnique(services.overrides.map(entry=>entry.service)))}`);return runServiceOverride(services,context)}const SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function runRegisteredSearchProviderForTest(registrations,options){const registration=resolveRegisteredSearchProvider(registrations,options.provider);if(!registration){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected a registered search provider "${options.provider}" to invoke. Available search providers: ${formatAvailable(available)}`)}const runtimeDefinition=registration.runtime_definition,operationFn=SEARCH_PROVIDER_OPERATION_DEFINITION_KEYS[options.operation].map(key=>runtimeDefinition[key]).find(value=>typeof value=="function");if(typeof operationFn!="function")throw new Error(`Registered search provider "${options.provider}" does not implement the "${options.operation}" operation.`);return await operationFn(options.context)}async function runRegisteredVectorStoreAdapterForTest(registrations,options){const registration=resolveRegisteredVectorStoreAdapter(registrations,options.adapter);if(!registration){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected a registered vector store adapter "${options.adapter}" to invoke. Available vector store adapters: ${formatAvailable(available)}`)}const operationFn=registration.runtime_definition[options.operation];if(typeof operationFn!="function")throw new Error(`Registered vector store adapter "${options.adapter}" does not implement the "${options.operation}" operation.`);return await operationFn(options.context)}async function runRegisteredMigrationForTest(registrations,options){const migration=assertRegisteredMigration(registrations,{migration:options.migration,extensionName:options.extensionName}),run=getMigrationRuntimeDefinition(migration).run;if(typeof run!="function")throw new Error(`Registered migration "${options.migration}" does not implement a run function to invoke.`);const declaredStatus=migration.definition.status,context={id:migration.definition.id,command:"migration",layer:migration.layer,extension:migration.name,pm_root:options.pmRoot??"",status:(typeof declaredStatus=="string"?declaredStatus.trim().toLowerCase():"")||"pending"};return await run(context)}async function runRegisteredImporterForTest(activation,options){const importer=assertRegisteredImporter(activation.registrations,{importer:options.importer,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${importer.importer} import`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}async function runRegisteredExporterForTest(activation,options){const exporter=assertRegisteredExporter(activation.registrations,{exporter:options.exporter,extensionName:options.extensionName});return runRegisteredCommandForTest(activation.commands,{command:`${exporter.exporter} export`,args:options.args,options:options.options,global:options.global,pmRoot:options.pmRoot})}function assertExtensionDeactivated(result,expectation={}){const expectedDeactivated=expectation.deactivated??1;if(result.deactivated!==expectedDeactivated)throw new Error(`Expected ${expectedDeactivated} extension${expectedDeactivated===1?"":"s"} to deactivate cleanly, but ${result.deactivated} did.`);const expectedFailed=expectation.failed??0;if(result.failed.length!==expectedFailed){const detail=result.failed.map(failure=>`${failure.layer}:${failure.name} (${failure.error})`).join(", ");throw new Error(`Expected ${expectedFailed} teardown failure${expectedFailed===1?"":"s"}, but observed ${result.failed.length}${detail.length>0?`: ${detail}`:""}.`)}return result}function assertPackageManifest(manifest,expectation){if(expectation.packageName!==void 0&&manifest.package_name!==expectation.packageName)throw new Error(`Expected package manifest package_name to be "${expectation.packageName}"; received "${manifest.package_name??"(none)"}"`);if(expectation.aliases!==void 0&&assertStringSetIncludes(manifest.aliases,expectation.aliases,"aliases"),expectation.resources!==void 0)for(const[kind,expectedPaths]of Object.entries(expectation.resources))assertStringSetIncludes(manifest.resources[kind],expectedPaths,`pm.${kind}`);return manifest}function assertRegisteredCommandContract(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const commandCandidates=registrations.commands.filter(entry=>entry.command===expectedCommand),command=expectation.extensionName?commandCandidates.find(entry=>entry.name===expectation.extensionName):commandCandidates[0];if(!command){const available=registrations.commands.map(entry=>entry.command).sort((left,right)=>left.localeCompare(right)),extensionSuffix=expectation.extensionName?` from extension "${expectation.extensionName}"`:"";throw new Error(`Expected extension command "${expectedCommand}"${extensionSuffix} to be registered. Available commands: ${formatAvailable(available)}`)}if(expectation.action!==void 0&&command.action!==expectation.action)throw new Error(`Expected extension command "${expectedCommand}" action "${expectation.action}", received "${command.action}"`);if(expectation.arguments!==void 0){const actualArguments=(command.arguments??[]).map(argument=>argument.name),missingArguments=expectation.arguments.filter(argument=>!actualArguments.includes(argument));if(missingArguments.length>0)throw new Error(`Expected extension command "${expectedCommand}" arguments ${formatAvailable(expectation.arguments)}; missing ${formatAvailable(missingArguments)}; available ${formatAvailable(actualArguments)}`)}const flags=registrations.flags.filter(entry=>entry.target_command===expectedCommand&&(expectation.extensionName===void 0||entry.name===expectation.extensionName)).flatMap(entry=>entry.flags);if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(flags),missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0)throw new Error(`Expected extension command "${expectedCommand}" flags ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}return{command,flags}}function assertRegisteredFlags(registrations,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.targetCommand));if(expectedCommand.length===0)throw new Error("Expected target command name must be a non-empty string");const candidates=registrations.flags.filter(entry=>entry.target_command===expectedCommand);let registration;if(expectation.extensionName)registration=candidates.find(entry=>entry.name===expectation.extensionName);else if(candidates.length===1)registration=candidates[0];else if(candidates.length>1){const availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}" matched multiple extensions: ${formatAvailable(availableExtensions)}. Specify extensionName to choose one registration.`)}if(!registration){const available=sortedUnique(registrations.flags.map(entry=>entry.target_command)),availableExtensions=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected flags for target command "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available flag target commands: ${formatAvailable(available)}; matching extensions: ${formatAvailable(availableExtensions)}`)}if(expectation.flags!==void 0){const actualFlagLabels=collectFlagLabels(registration.flags),missingFlags=expectation.flags.filter(flag=>!actualFlagLabels.has(flag));if(missingFlags.length>0)throw new Error(`Expected flags for target command "${expectedCommand}" to include ${formatAvailable(expectation.flags)}; missing ${formatAvailable(missingFlags)}; available ${formatAvailable([...actualFlagLabels].sort((left,right)=>left.localeCompare(right)))}`)}return registration}function assertRegisteredHook(hooks,expectation){const field=HOOK_KIND_TO_REGISTRY_FIELD[expectation.kind],candidates=hooks[field]??[],hook=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!hook){const available=sortedUnique(candidates.map(entry=>entry.name));throw new Error(`Expected a "${expectation.kind}" hook${extensionNameSuffix(expectation.extensionName)} to be registered. Available "${expectation.kind}" hooks: ${formatAvailable(available)}`)}return hook}function assertRegisteredSearchProvider(registrations,expectation){const expectedProvider=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.provider));if(expectedProvider.length===0)throw new Error("Expected search provider name must be a non-empty string");const candidates=registrations.search_providers.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedProvider),provider=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!provider){const available=sortedUnique(registrations.search_providers.map(entry=>entry.definition.name));throw new Error(`Expected search provider "${expectedProvider}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available search providers: ${formatAvailable(available)}`)}return provider}function assertRegisteredVectorStoreAdapter(registrations,expectation){const expectedAdapter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.adapter));if(expectedAdapter.length===0)throw new Error("Expected vector store adapter name must be a non-empty string");const candidates=registrations.vector_store_adapters.filter(entry=>normalizeSdkIdentifier(entry.definition.name)===expectedAdapter),adapter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!adapter){const available=sortedUnique(registrations.vector_store_adapters.map(entry=>entry.definition.name));throw new Error(`Expected vector store adapter "${expectedAdapter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available vector store adapters: ${formatAvailable(available)}`)}return adapter}function assertRegisteredImporter(registrations,expectation){const expectedImporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.importer));if(expectedImporter.length===0)throw new Error("Expected importer name must be a non-empty string");const candidates=registrations.importers.filter(entry=>normalizeSdkIdentifier(entry.importer)===expectedImporter),importer=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!importer){const available=sortedUnique(registrations.importers.map(entry=>entry.importer));throw new Error(`Expected importer "${expectedImporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available importers: ${formatAvailable(available)}`)}return importer}function assertRegisteredExporter(registrations,expectation){const expectedExporter=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.exporter));if(expectedExporter.length===0)throw new Error("Expected exporter name must be a non-empty string");const candidates=registrations.exporters.filter(entry=>normalizeSdkIdentifier(entry.exporter)===expectedExporter),exporter=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!exporter){const available=sortedUnique(registrations.exporters.map(entry=>entry.exporter));throw new Error(`Expected exporter "${expectedExporter}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available exporters: ${formatAvailable(available)}`)}return exporter}function assertRegisteredItemField(registrations,expectation){const expectedField=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.field));if(expectedField.length===0)throw new Error("Expected item field name must be a non-empty string");const match=registrations.item_fields.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,field:registration.fields.find(field=>normalizeSdkIdentifier(field.name)===expectedField)})).filter(entry=>entry.field!==void 0).find(entry=>expectation.type===void 0||entry.field.type===expectation.type);if(!match){const available=sortedUnique(registrations.item_fields.flatMap(entry=>entry.fields.map(field=>`${field.name}:${field.type}`)));throw new Error(`Expected item field "${expectedField}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item fields: ${formatAvailable(available)}`)}return match}function assertRegisteredItemType(registrations,expectation){const expectedType=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.itemType));if(expectedType.length===0)throw new Error("Expected item type name must be a non-empty string");const match=registrations.item_types.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).map(registration=>({registration,itemType:registration.types.find(itemType=>normalizeSdkIdentifier(itemType.name)===expectedType)})).filter(entry=>entry.itemType!==void 0).find(entry=>expectation.folder===void 0||entry.itemType.folder===expectation.folder);if(!match){const available=sortedUnique(registrations.item_types.flatMap(entry=>entry.types.map(itemType=>`${itemType.name}:${itemType.folder}`)));throw new Error(`Expected item type "${expectedType}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available item types: ${formatAvailable(available)}`)}return match}function assertRegisteredProfile(registrations,expectation){const expectedProfile=normalizeSdkProfileMatchKey(registeredExpectationName(expectation,expectation.profile));if(expectedProfile.length===0)throw new Error("Expected profile name must be a non-empty string");const match=registrations.profiles.filter(entry=>expectation.extensionName===void 0||entry.name===expectation.extensionName).find(entry=>normalizeSdkProfileMatchKey(entry.profile.name)===expectedProfile);if(!match){const available=sortedUnique(registrations.profiles.map(entry=>entry.profile.name));throw new Error(`Expected profile "${expectedProfile}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available profiles: ${formatAvailable(available)}`)}return{registration:match,profile:match.profile}}function assertRegisteredCommandOverride(commands,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const candidates=commands.overrides.filter(entry=>entry.command===expectedCommand),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(commands.overrides.map(entry=>entry.command));throw new Error(`Expected command override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available command overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredParserOverride(parsers,expectation){const expectedCommand=normalizeSdkCommandName(registeredExpectationName(expectation,expectation.command));if(expectedCommand.length===0)throw new Error("Expected command name must be a non-empty string");const candidates=parsers.overrides.filter(entry=>entry.command===expectedCommand),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(parsers.overrides.map(entry=>entry.command));throw new Error(`Expected parser override "${expectedCommand}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available parser overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredPreflightOverride(preflight,expectation={}){const override=expectation.extensionName?preflight.overrides.find(entry=>entry.name===expectation.extensionName):preflight.overrides[0];if(!override){const available=sortedUnique(preflight.overrides.map(entry=>entry.name));throw new Error(`Expected a preflight override${extensionNameSuffix(expectation.extensionName)} to be registered. Available preflight overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredRendererOverride(renderers,expectation){const expectedFormat=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.format));if(expectedFormat.length===0)throw new Error("Expected renderer format must be a non-empty string");const candidates=renderers.overrides.filter(entry=>entry.format===expectedFormat),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(renderers.overrides.map(entry=>entry.format));throw new Error(`Expected renderer override "${expectedFormat}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available renderer overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredServiceOverride(services,expectation){const expectedService=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.service));if(expectedService.length===0)throw new Error("Expected service name must be a non-empty string");const candidates=services.overrides.filter(entry=>normalizeSdkIdentifier(entry.service)===expectedService),override=expectation.extensionName?candidates.find(entry=>entry.name===expectation.extensionName):candidates[0];if(!override){const available=sortedUnique(services.overrides.map(entry=>entry.service));throw new Error(`Expected service override "${expectedService}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available service overrides: ${formatAvailable(available)}`)}return override}function assertRegisteredMigration(registrations,expectation){const expectedMigration=normalizeSdkIdentifier(registeredExpectationName(expectation,expectation.migration));if(expectedMigration.length===0)throw new Error("Expected migration id must be a non-empty string");const candidates=registrations.migrations.filter(entry=>(expectation.extensionName===void 0||entry.name===expectation.extensionName)&&typeof entry.definition.id=="string"&&normalizeSdkIdentifier(entry.definition.id)===expectedMigration),match=candidates.find(entry=>expectation.mandatory===void 0||(entry.definition.mandatory??!1)===expectation.mandatory);if(match)return match;const idMatch=candidates[0];if(idMatch!==void 0)throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to have mandatory=${expectation.mandatory}, but it is mandatory=${idMatch.definition.mandatory??!1}.`);const available=sortedUnique(registrations.migrations.map(entry=>`${typeof entry.definition.id=="string"&&entry.definition.id.trim().length>0?entry.definition.id.trim():"(unnamed)"}:${entry.definition.mandatory===!0}`));throw new Error(`Expected migration "${expectedMigration}"${extensionNameSuffix(expectation.extensionName)} to be registered. Available migrations: ${formatAvailable(available)}`)}function assertExtensionCapabilityUsage(activation,expectation){const toKnownCapabilitySet=(capabilities,field)=>{const known=new Set;for(const capability of capabilities){const normalized=normalizeKnownExtensionCapability(capability);if(normalized===null)throw new Error(`Expected ${field} capability "${capability}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`);known.add(normalized)}return known},declared=[...toKnownCapabilitySet(expectation.declared,"declared")].sort((left,right)=>left.localeCompare(right)),allowUnused=toKnownCapabilitySet(expectation.allowUnused??[],"allowUnused"),used=collectUsedExtensionCapabilities(activation,{extensionName:expectation.extensionName}),usedSet=new Set(used),unused=declared.filter(capability=>!usedSet.has(capability)&&!allowUnused.has(capability));if(unused.length>0){const scopeSuffix=extensionNameSuffix(expectation.extensionName);throw new Error(`Expected every declared capability${scopeSuffix} to be exercised, but [${unused.join(", ")}] ${unused.length===1?"is":"are"} declared yet never registered against. Remove ${unused.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared,used,unused}}function assertExtensionBlueprint(blueprint,options={}){const result=lintExtensionBlueprint(blueprint,options);if(!result.ok){const errors=result.findings.filter(finding=>finding.severity==="error");throw new Error(`Extension blueprint failed preflight with ${errors.length} ${errors.length===1?"error":"errors"}:
2
2
  `+errors.map(finding=>` - [${finding.code}] ${finding.message}`).join(`
3
3
  `))}return result}function assertProjectProfile(profile,options={}){const report=lintProjectProfile(profile),blocking=report.findings.filter(finding=>finding.severity==="error"||options.strict===!0&&finding.severity==="warning");if(blocking.length>0)throw new Error(`Project profile "${report.profile}" failed lint with ${blocking.length} ${blocking.length===1?"issue":"issues"}:
4
4
  `+blocking.map(finding=>` - ${finding.severity} [${finding.code}] ${finding.message}`).join(`
5
5
  `));return report}function assertExtensionManifestMatchesBlueprint(manifest,blueprint){const declaredCapabilities=Array.isArray(manifest.capabilities)?manifest.capabilities:[],result=lintExtensionBlueprint(blueprint,{declaredCapabilities}),declared=result.declared,declaredSet=new Set(declared),usedSet=new Set(result.used),missing=result.used.filter(capability=>!declaredSet.has(capability)),unused=declared.filter(capability=>!usedSet.has(capability));if(missing.length>0||unused.length>0){const parts=[];throw missing.length>0&&parts.push(`missing [${missing.join(", ")}] (the blueprint registers ${missing.length===1?"a surface":"surfaces"} requiring ${missing.length===1?"it":"them"}; activation throws extension_capability_missing)`),unused.length>0&&parts.push(`unused [${unused.join(", ")}] (declared but no surface exercises ${unused.length===1?"it":"them"}; drop for least privilege)`),new Error(`Manifest capabilities do not match the blueprint: ${parts.join("; ")}. Set capabilities to synthesizeExtensionManifest(blueprint, identity).capabilities to stay in sync.`)}return{used:result.used,declared,missing,unused,findings:result.findings}}function assertExtensionManifestCompatible(manifest,target){const result=checkExtensionManifestCompatibility(manifest,target),blocking=result.findings.filter(finding=>finding.severity==="error");if(blocking.length>0)throw new Error(`Extension manifest is not compatible with pm ${result.pmVersion}: ${blocking.map(finding=>finding.message).join("; ")}`);return result}function assertExtensionPreflight(blueprint,options={}){const report=preflightExtension(blueprint,options);if(!report.ok){const errors=report.findings.filter(finding=>finding.severity==="error");throw new Error(`Extension failed preflight with ${errors.length} ${errors.length===1?"error":"errors"}:
6
6
  `+errors.map(finding=>` - [${finding.source}:${finding.code}] ${finding.message}`).join(`
7
- `))}return report}function assertTestModuleHasActivateExport(module){if(!resolveActivatablePropertyRecord(module))throw new Error("createExtensionTestHarness received a module with no activate export. Pass the extension module (with an activate(api) function on the module or its default export) as the first argument, and options second.")}async function createExtensionTestHarness(module,options={}){assertTestModuleHasActivateExport(module);const manifest=readTestExtensionManifest(module),name=resolveTestExtensionName(manifest,options.name),layer=options.layer??"project",activation=await activateExtensionForTest(module,options);if(activation.failed.length>0){const detail=activation.failed.map(failure=>{const missingCapability=failure.trace?.missing_capability,reason=missingCapability?`${failure.error}; missing capability "${missingCapability}"`:failure.error;return`${failure.layer}:${failure.name} (${reason})`}).join(", ");throw new Error(`createExtensionTestHarness could not activate the extension cleanly: ${detail}. Declare the required capability in the manifest (or pass it via options.capabilities), or use activateExtensionForTest directly to inspect a failed activation.`)}return{module,name,layer,activation,activationSummary(describeOptions){return describeExtensionActivation(activation,describeOptions)},renderMarkdown(markdownOptions={}){const{extensionName,...renderOptions}=markdownOptions??{};return renderExtensionSurfaceMarkdown(describeExtensionActivation(activation,{extensionName}),renderOptions)},assertCommandContract(expectation){return assertRegisteredCommandContract(activation.registrations,expectation)},assertFlags(expectation){return assertRegisteredFlags(activation.registrations,expectation)},assertItemField(expectation){return assertRegisteredItemField(activation.registrations,expectation)},assertItemType(expectation){return assertRegisteredItemType(activation.registrations,expectation)},assertProfile(expectation){return assertRegisteredProfile(activation.registrations,expectation)},assertHook(expectation){return assertRegisteredHook(activation.hooks,expectation)},assertCommandOverride(expectation){return assertRegisteredCommandOverride(activation.commands,expectation)},assertParserOverride(expectation){return assertRegisteredParserOverride(activation.parsers,expectation)},assertPreflightOverride(expectation){return assertRegisteredPreflightOverride(activation.preflight,expectation)},assertRendererOverride(expectation){return assertRegisteredRendererOverride(activation.renderers,expectation)},assertServiceOverride(expectation){return assertRegisteredServiceOverride(activation.services,expectation)},assertSearchProvider(expectation){return assertRegisteredSearchProvider(activation.registrations,expectation)},assertVectorStoreAdapter(expectation){return assertRegisteredVectorStoreAdapter(activation.registrations,expectation)},assertImporter(expectation){return assertRegisteredImporter(activation.registrations,expectation)},assertExporter(expectation){return assertRegisteredExporter(activation.registrations,expectation)},assertMigration(expectation){return assertRegisteredMigration(activation.registrations,expectation)},assertCapabilityUsage(expectation){return assertExtensionCapabilityUsage(activation,expectation)},runCommand(runOptions){return runRegisteredCommandForTest(activation.commands,runOptions)},runHook(runOptions){return runRegisteredHookForTest(activation.hooks,runOptions)},runMutationGuard(runOptions){return runRegisteredMutationGuardForTest(activation.hooks,runOptions)},runCommandOverride(context){return runRegisteredCommandOverrideForTest(activation.commands,context)},runParserOverride(context){return runRegisteredParserOverrideForTest(activation.parsers,context)},runPreflightOverride(context){return runRegisteredPreflightOverrideForTest(activation.preflight,context)},runRendererOverride(context){return runRegisteredRendererOverrideForTest(activation.renderers,context)},runServiceOverride(context){return runRegisteredServiceOverrideForTest(activation.services,context)},runSearchProvider(runOptions){return runRegisteredSearchProviderForTest(activation.registrations,runOptions)},runVectorStoreAdapter(runOptions){return runRegisteredVectorStoreAdapterForTest(activation.registrations,runOptions)},runMigration(runOptions){return runRegisteredMigrationForTest(activation.registrations,runOptions)},runImporter(runOptions){return runRegisteredImporterForTest(activation,runOptions)},runExporter(runOptions){return runRegisteredExporterForTest(activation,runOptions)},deactivate(deactivateOptions={}){return deactivateExtensionForTest(module,{name,layer,activation,deactivateTimeoutMs:deactivateOptions.deactivateTimeoutMs})}}}export{activateExtensionForTest,assertExtensionBlueprint,assertExtensionCapabilityUsage,assertExtensionDeactivated,assertExtensionManifestCompatible,assertExtensionManifestMatchesBlueprint,assertExtensionPreflight,assertPackageManifest,assertProjectProfile,assertRegisteredCommandContract,assertRegisteredCommandOverride,assertRegisteredExporter,assertRegisteredFlags,assertRegisteredHook,assertRegisteredImporter,assertRegisteredItemField,assertRegisteredItemType,assertRegisteredMigration,assertRegisteredParserOverride,assertRegisteredPreflightOverride,assertRegisteredProfile,assertRegisteredRendererOverride,assertRegisteredSearchProvider,assertRegisteredServiceOverride,assertRegisteredVectorStoreAdapter,createExtensionTestHarness,deactivateExtensionForTest,decode as decodeToon,describeExtensionActivation,describeExtensionBlueprint,encode as encodeToon,lintExtensionBlueprint,renderExtensionSurfaceMarkdown,runRegisteredCommandForTest,runRegisteredCommandOverrideForTest,runRegisteredExporterForTest,runRegisteredHookForTest,runRegisteredImporterForTest,runRegisteredMigrationForTest,runRegisteredMutationGuardForTest,runRegisteredParserOverrideForTest,runRegisteredPreflightOverrideForTest,runRegisteredRendererOverrideForTest,runRegisteredSearchProviderForTest,runRegisteredServiceOverrideForTest,runRegisteredVectorStoreAdapterForTest};
7
+ `))}return report}function assertTestModuleHasActivateExport(module){if(!resolveActivatablePropertyRecord(module))throw new Error("createExtensionTestHarness received a module with no activate export. Pass the extension module (with an activate(api) function on the module or its default export) as the first argument, and options second.")}async function createExtensionTestHarness(module,options={}){assertTestModuleHasActivateExport(module);const manifest=readTestExtensionManifest(module),name=resolveTestExtensionName(manifest,options.name),layer=options.layer??"project",activation=await activateExtensionForTest(module,options);if(activation.failed.length>0){const detail=activation.failed.map(failure=>{const missingCapability=failure.trace?.missing_capability,reason=missingCapability?`${failure.error}; missing capability "${missingCapability}"`:failure.error;return`${failure.layer}:${failure.name} (${reason})`}).join(", ");throw new Error(`createExtensionTestHarness could not activate the extension cleanly: ${detail}. Declare the required capability in the manifest (or pass it via options.capabilities), or use activateExtensionForTest directly to inspect a failed activation.`)}return{module,name,layer,activation,activationSummary(describeOptions){return describeExtensionActivation(activation,describeOptions)},renderMarkdown(markdownOptions={}){const{extensionName,...renderOptions}=markdownOptions??{};return renderExtensionSurfaceMarkdown(describeExtensionActivation(activation,{extensionName}),renderOptions)},assertCommandContract(expectation){return assertRegisteredCommandContract(activation.registrations,expectation)},assertFlags(expectation){return assertRegisteredFlags(activation.registrations,expectation)},assertItemField(expectation){return assertRegisteredItemField(activation.registrations,expectation)},assertItemType(expectation){return assertRegisteredItemType(activation.registrations,expectation)},assertProfile(expectation){return assertRegisteredProfile(activation.registrations,expectation)},assertHook(expectation){return assertRegisteredHook(activation.hooks,expectation)},assertCommandOverride(expectation){return assertRegisteredCommandOverride(activation.commands,expectation)},assertParserOverride(expectation){return assertRegisteredParserOverride(activation.parsers,expectation)},assertPreflightOverride(expectation){return assertRegisteredPreflightOverride(activation.preflight,expectation)},assertRendererOverride(expectation){return assertRegisteredRendererOverride(activation.renderers,expectation)},assertServiceOverride(expectation){return assertRegisteredServiceOverride(activation.services,expectation)},assertSearchProvider(expectation){return assertRegisteredSearchProvider(activation.registrations,expectation)},assertVectorStoreAdapter(expectation){return assertRegisteredVectorStoreAdapter(activation.registrations,expectation)},assertImporter(expectation){return assertRegisteredImporter(activation.registrations,expectation)},assertExporter(expectation){return assertRegisteredExporter(activation.registrations,expectation)},assertMigration(expectation){return assertRegisteredMigration(activation.registrations,expectation)},assertCapabilityUsage(expectation){return assertExtensionCapabilityUsage(activation,expectation)},runCommand(runOptions){return runRegisteredCommandForTest(activation.commands,runOptions)},runHook(runOptions){return runRegisteredHookForTest(activation.hooks,runOptions)},runMutationGuard:(runOptions=>runRegisteredMutationGuardForTest(activation.hooks,runOptions)),runCommandOverride(context){return runRegisteredCommandOverrideForTest(activation.commands,context)},runParserOverride(context){return runRegisteredParserOverrideForTest(activation.parsers,context)},runPreflightOverride(context){return runRegisteredPreflightOverrideForTest(activation.preflight,context)},runRendererOverride(context){return runRegisteredRendererOverrideForTest(activation.renderers,context)},runServiceOverride(context){return runRegisteredServiceOverrideForTest(activation.services,context)},runSearchProvider(runOptions){return runRegisteredSearchProviderForTest(activation.registrations,runOptions)},runVectorStoreAdapter(runOptions){return runRegisteredVectorStoreAdapterForTest(activation.registrations,runOptions)},runMigration(runOptions){return runRegisteredMigrationForTest(activation.registrations,runOptions)},runImporter(runOptions){return runRegisteredImporterForTest(activation,runOptions)},runExporter(runOptions){return runRegisteredExporterForTest(activation,runOptions)},deactivate(deactivateOptions={}){return deactivateExtensionForTest(module,{name,layer,activation,deactivateTimeoutMs:deactivateOptions.deactivateTimeoutMs})}}}export{activateExtensionForTest,assertExtensionBlueprint,assertExtensionCapabilityUsage,assertExtensionDeactivated,assertExtensionManifestCompatible,assertExtensionManifestMatchesBlueprint,assertExtensionPreflight,assertPackageManifest,assertProjectProfile,assertRegisteredCommandContract,assertRegisteredCommandOverride,assertRegisteredExporter,assertRegisteredFlags,assertRegisteredHook,assertRegisteredImporter,assertRegisteredItemField,assertRegisteredItemType,assertRegisteredMigration,assertRegisteredParserOverride,assertRegisteredPreflightOverride,assertRegisteredProfile,assertRegisteredRendererOverride,assertRegisteredSearchProvider,assertRegisteredServiceOverride,assertRegisteredVectorStoreAdapter,createExtensionTestHarness,deactivateExtensionForTest,decode as decodeToon,describeExtensionActivation,describeExtensionBlueprint,encode as encodeToon,lintExtensionBlueprint,renderExtensionSurfaceMarkdown,runRegisteredCommandForTest,runRegisteredCommandOverrideForTest,runRegisteredExporterForTest,runRegisteredHookForTest,runRegisteredImporterForTest,runRegisteredMigrationForTest,runRegisteredMutationGuardForTest,runRegisteredParserOverrideForTest,runRegisteredPreflightOverrideForTest,runRegisteredRendererOverrideForTest,runRegisteredSearchProviderForTest,runRegisteredServiceOverrideForTest,runRegisteredVectorStoreAdapterForTest};
8
8
  //# sourceMappingURL=testing.js.map
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="24a18484-0b8b-55d7-aa23-08a23b8d78ce")}catch{}})();import{mkdir,readFile}from"node:fs/promises";import path from"node:path";import{createHash}from"node:crypto";import{appendWorkspaceAuditEvent,getWorkspaceHistoryPath,WORKSPACE_HISTORY_ID}from"../core/history/workspace-history.js";import{readHistoryEntries}from"./history-read.js";import{acquireLock}from"../core/lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../core/fs/fs-utils.js";import{nowIso}from"../core/shared/time.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";class WorkspaceTransactionInterruptedError extends Error{constructor(message="Workspace transaction interrupted"){super(message),this.name="WorkspaceTransactionInterruptedError"}}const WORKSPACE_TRANSACTION_LOCK_ID="sdk-workspace-transaction",TRANSACTION_ID_PATTERN=/^[a-zA-Z0-9._-]+$/,DEFAULT_LOCK_TTL_SECONDS=30,DEFAULT_LOCK_WAIT_MS=3e3;function requiredIdentifier(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized||!TRANSACTION_ID_PATTERN.test(normalized))throw new TypeError(`${label} must match [a-zA-Z0-9._-]+`);return normalized}function requiredText(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized)throw new TypeError(`${label} must be non-empty`);return normalized}function validateWorkspaceTransactionIdentity(options){return{pmRoot:requiredText(options.pmRoot,"Transaction pmRoot"),transactionId:requiredIdentifier(options.transactionId,"Transaction id"),author:requiredText(options.author,"Transaction author")}}function positiveInteger(value,fallback,label){const resolved=value??fallback;if(!Number.isInteger(resolved)||resolved<=0)throw new TypeError(`${label} must be a positive integer`);return resolved}function journalPath(pmRoot,transactionId){return path.join(pmRoot,"transactions","sdk",`${transactionId}.json`)}async function writeJournal(pmRoot,journal){journal.updatedAt=nowIso();const target=journalPath(pmRoot,journal.transactionId);await mkdir(path.dirname(target),{recursive:!0}),await writeFileAtomic(target,`${JSON.stringify(journal,null,2)}
2
- `)}function hasValidJournalMetadata(journal){return Number.isInteger(journal.attempt)&&typeof journal.author=="string"&&typeof journal.createdAt=="string"&&typeof journal.updatedAt=="string"&&hasValidAbandonment(journal)}function hasValidAbandonment(journal){const retirement=journal.abandonment;return retirement===void 0?journal.schemaVersion===1&&journal.status!=="abandoned":journal.schemaVersion!==2||retirement===null||typeof retirement!="object"||journal.status==="committed"?!1:typeof retirement.reason=="string"&&retirement.reason.trim().length>0&&typeof retirement.author=="string"&&retirement.author.trim().length>0&&(retirement.supersededBy===void 0||typeof retirement.supersededBy=="string"&&TRANSACTION_ID_PATTERN.test(retirement.supersededBy)&&retirement.supersededBy!==journal.transactionId)}function createResultMap(source){return Object.assign(Object.create(null),source)}function cloneJournalValue(value,label){try{const serialized=JSON.stringify(value,(_key,nestedValue)=>{if(typeof nestedValue=="number"&&!Number.isFinite(nestedValue))throw new TypeError(`${label} contains a non-finite number`);if(nestedValue===void 0||typeof nestedValue=="function"||typeof nestedValue=="symbol")throw new TypeError(`${label} contains a non-JSON value`);return nestedValue});return JSON.parse(serialized)}catch(error){throw new TypeError(`${label} must be JSON serializable`,{cause:error})}}function cloneOptionalJournalValue(value,label){return value===void 0?void 0:cloneJournalValue(value,label)}function setJournalEntry(target,stepId,value,label){const cloned=cloneOptionalJournalValue(value,label);cloned===void 0?delete target[stepId]:target[stepId]=cloned}function isJournalMap(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function hasUniqueKnownStepIds(value,stepIds){return Array.isArray(value)&&new Set(value).size===value.length&&value.every(stepId=>typeof stepId=="string"&&stepIds.includes(stepId))}function hasValidJournalLifecycle(journal,stepIds){if(!hasUniqueKnownStepIds(journal.startedStepIds,stepIds)||!hasUniqueKnownStepIds(journal.completedStepIds,stepIds)||!isJournalMap(journal.results)||!isJournalMap(journal.compensationData))return!1;const startedStepIds=journal.startedStepIds,started=new Set(startedStepIds),completedStepIds=journal.completedStepIds,completed=new Set(completedStepIds);return Object.keys(journal.compensationData).some(stepId=>!started.has(stepId))||Object.keys(journal.results).some(stepId=>!completed.has(stepId))?!1:journal.status==="committed"?stepIds.every(stepId=>completed.has(stepId)):!["compensated","abandoned"].includes(journal.status??"")||completed.size===0&&started.size===0}function invalidJournal(transactionId,detail){return new PmCliError(`Workspace transaction ${transactionId} journal is invalid (${detail})`,EXIT_CODE.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function journalPlanMismatch(transactionId){return new PmCliError(`Workspace transaction ${transactionId} journal does not match the supplied plan`,EXIT_CODE.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function matchesJournalSteps(journal,recorded,requested){return requested===void 0||journal.abandonment!==void 0||journal.status==="compensated"||recorded.length===requested.length&&recorded.every((id,index)=>id===requested[index])}function parseJournal(raw,transactionId,stepIds){let parsed;try{parsed=JSON.parse(raw)}catch{throw invalidJournal(transactionId,"invalid JSON")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw invalidJournal(transactionId,"expected an object");const journal=parsed;if(!((journal.schemaVersion===1||journal.schemaVersion===2)&&journal.transactionId===transactionId))throw invalidJournal(transactionId,"schema version or transaction id does not match the journal file");const recordedStepIds=journal.stepIds;if(!Array.isArray(recordedStepIds)||!hasUniqueKnownStepIds(recordedStepIds,recordedStepIds)||!hasValidJournalLifecycle(journal,recordedStepIds)||!hasValidJournalMetadata(journal)||typeof journal.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(journal.status))throw invalidJournal(transactionId,"invalid lifecycle, metadata, status or step ids");if(!matchesJournalSteps(journal,recordedStepIds,stepIds))throw journalPlanMismatch(transactionId);return{...journal,results:createResultMap(journal.results),compensationData:createResultMap(journal.compensationData)}}async function prepareJournalForApply(options,transactionId,author,stepIds,existing){let journal=existing;const recovered=journal!==void 0;if(journal?.status==="compensating"&&await compensateAppliedSteps(options,journal),journal===void 0||journal.status==="compensated"){const timestamp=nowIso();journal={schemaVersion:1,transactionId,author,status:"applying",attempt:(journal?.attempt??0)+1,createdAt:journal?.createdAt??timestamp,updatedAt:timestamp,stepIds,startedStepIds:[],completedStepIds:[],results:createResultMap(),compensationData:createResultMap(),...options.recoveryData===void 0?{}:{recoveryData:cloneJournalValue(options.recoveryData,"Transaction recovery data")}},await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"prepared")}return{journal,recovered}}async function applyPreparedTransaction(options,journal,recovered){try{await discoverAppliedSteps(journal,options.steps),await writeJournal(options.pmRoot,journal);const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of options.steps){if(completed.has(step.id))continue;const inspection=await step.inspect();let result=cloneOptionalJournalValue(inspection.result,`Step ${step.id} result`);if(inspection.state!=="applied"){const compensationData=await step.prepareCompensation?.();setJournalEntry(journal.compensationData,step.id,compensationData,`Step ${step.id} compensation data`),started.add(step.id),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),await writeJournal(options.pmRoot,journal);const appliedResult=await step.apply();result=cloneOptionalJournalValue(appliedResult,`Step ${step.id} result`)}await emitTransition(options,journal,"step_applied",step.id),completed.add(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),setJournalEntry(journal.results,step.id,result,`Step ${step.id} result`),await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_recorded",step.id)}return await emitTransition(options,journal,"committing"),journal.status="committed",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"committed"),{transactionId:journal.transactionId,status:"committed",recovered,results:createResultMap(journal.results)}}catch(error){if(error instanceof WorkspaceTransactionInterruptedError||journal.status==="committed")throw error;try{await compensateAppliedSteps(options,journal)}catch(compensationError){throw new AggregateError([error,compensationError],`Workspace transaction failed and compensation failed: ${String(compensationError)}`,{cause:compensationError})}throw error}}async function loadJournal(pmRoot,transactionId,stepIds){try{return parseJournal(await readFile(journalPath(pmRoot,transactionId),"utf8"),transactionId,stepIds)}catch(error){if(error!==null&&typeof error=="object"&&"code"in error&&isFileMissingError(error))return;throw error}}async function emitTransition(options,journal,transition,stepId){await options.onTransition?.({transactionId:journal.transactionId,attempt:journal.attempt,transition,...stepId===void 0?{}:{stepId}})}async function discoverAppliedSteps(journal,steps){const completed=new Set,results=createResultMap();for(const step of steps){const inspection=await step.inspect();inspection.state==="applied"&&(completed.add(step.id),setJournalEntry(results,step.id,inspection.result,`Step ${step.id} result`))}journal.results=results,journal.completedStepIds=steps.map(step=>step.id).filter(stepId=>completed.has(stepId))}async function compensateAppliedSteps(options,journal){journal.status="compensating",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensating");const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of[...options.steps].reverse()){if(!started.has(step.id)&&!completed.has(step.id))continue;let shouldCompensate;try{const state=(await step.inspect()).state;shouldCompensate=started.has(step.id)&&(state==="applied"||state==="pending"&&step.compensatePending===!0)}catch{shouldCompensate=started.has(step.id)}shouldCompensate&&(await emitTransition(options,journal,"step_compensating",step.id),await step.compensate(journal.compensationData[step.id])),completed.delete(step.id),started.delete(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),delete journal.results[step.id],delete journal.compensationData[step.id],await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_compensated",step.id)}journal.status="compensated",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensated")}async function commitWorkspaceTransaction(options){const{pmRoot,transactionId,author}=validateWorkspaceTransactionIdentity(options),lockTtlSeconds=positiveInteger(options.lockTtlSeconds,DEFAULT_LOCK_TTL_SECONDS,"Transaction lock TTL"),lockWaitMs=positiveInteger(options.lockWaitMs,DEFAULT_LOCK_WAIT_MS,"Transaction lock wait"),steps=[...options.steps];if(steps.length===0)throw new TypeError("Workspace transaction requires at least one step");const stepIds=steps.map(step=>{const stepId=requiredIdentifier(step.id,"Transaction step id");if(stepId!==step.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return stepId});if(new Set(stepIds).size!==stepIds.length)throw new TypeError("Workspace transaction step ids must be unique");const stableOptions={...options,pmRoot,transactionId,author,steps,lockTtlSeconds,lockWaitMs},release=await acquireLock(pmRoot,WORKSPACE_TRANSACTION_LOCK_ID,lockTtlSeconds,author,!1,!1,lockWaitMs);try{const existing=await loadJournal(pmRoot,transactionId,stepIds);if(existing?.status==="abandoned"||existing?.abandonment!==void 0)throw retiredTransaction(existing);const recovered=existing!==void 0;if(existing?.status==="committed")return{transactionId,status:"committed",recovered:!0,results:createResultMap(existing.results)};const prepared=await prepareJournalForApply(stableOptions,transactionId,author,stepIds,existing);return await applyPreparedTransaction(stableOptions,prepared.journal,recovered||prepared.recovered)}finally{await release()}}function retiredTransaction(journal){const pending=journal.status!=="abandoned",supersededBy=journal.abandonment.supersededBy,retry=supersededBy===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(journal.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(supersededBy)} to finish retirement of ${JSON.stringify(journal.transactionId)}.`;return new PmCliError(pending?`Transaction ${journal.transactionId} retirement is incomplete`:`Transaction ${journal.transactionId} has been abandoned`,EXIT_CODE.CONFLICT,{code:"transaction_abandoned",required:pending?retry:"Use a new transactionId for the replacement plan.",why:pending?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...pending?{retirement:{state:"pending",superseded_by:supersededBy??null},nextSteps:[retry]}:{}})}async function readWorkspaceTransaction(pmRoot,transactionId){const identity=validateWorkspaceTransactionIdentity({pmRoot,transactionId,author:"reader"});return loadJournal(identity.pmRoot,identity.transactionId)}function workspaceTransactionPlanDigest(journal){return createHash("sha256").update(JSON.stringify(journal.stepIds)).digest("hex")}async function abandonWorkspaceTransaction(options){const identity=validateWorkspaceTransactionIdentity(options),reason=requiredText(options.reason,"Abandonment reason"),supersededBy=options.supersededBy===void 0?void 0:requiredIdentifier(options.supersededBy,"Replacement transaction id");if(supersededBy===identity.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");const lockTtlSeconds=positiveInteger(options.lockTtlSeconds,DEFAULT_LOCK_TTL_SECONDS,"Transaction lock TTL"),lockWaitMs=positiveInteger(options.lockWaitMs,DEFAULT_LOCK_WAIT_MS,"Transaction lock wait"),release=await acquireLock(identity.pmRoot,WORKSPACE_TRANSACTION_LOCK_ID,lockTtlSeconds,identity.author,!1,!1,lockWaitMs);try{const journal=await loadJournal(identity.pmRoot,identity.transactionId);if(journal===void 0)throw new PmCliError(`Transaction ${identity.transactionId} was not found`,EXIT_CODE.NOT_FOUND);if(journal.status==="committed")throw new PmCliError(`Transaction ${identity.transactionId} is committed and cannot be abandoned`,EXIT_CODE.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(journal.abandonment!==void 0&&journal.abandonment.supersededBy!==supersededBy)throw retiredTransaction(journal);if(journal.status==="abandoned")return journal;const steps=options.resolveSteps(structuredClone(journal));if(JSON.stringify(steps.map(step=>step.id))!==JSON.stringify(journal.stepIds))throw journalPlanMismatch(identity.transactionId);if(journal.abandonment===void 0){if(supersededBy!==void 0&&await loadJournal(identity.pmRoot,supersededBy)!==void 0)throw new PmCliError(`Replacement transaction ${supersededBy} already exists`,EXIT_CODE.CONFLICT);journal.schemaVersion=2,journal.abandonment={reason,author:identity.author,...supersededBy===void 0?{}:{supersededBy}},await writeJournal(identity.pmRoot,journal)}return journal.status!=="compensated"&&await compensateAppliedSteps({...options,...identity,steps},journal),await auditTransactionAbandonment(journal,identity.pmRoot,lockTtlSeconds,lockWaitMs),journal.status="abandoned",await writeJournal(identity.pmRoot,journal),journal}finally{await release()}}async function auditTransactionAbandonment(journal,pmRoot,lockTtlSeconds,lockWaitMs){const planDigest=workspaceTransactionPlanDigest(journal);if((await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID)).some(entry=>entry.op==="transaction_abandon"&&entry.context?.transaction_id===journal.transactionId&&entry.context?.attempt===journal.attempt&&entry.context?.plan_digest===planDigest))return;const abandonment=journal.abandonment;await appendWorkspaceAuditEvent({pmRoot,author:abandonment.author,lockTtlSeconds,lockWaitMs,op:"transaction_abandon",message:abandonment.reason,context:{transaction_id:journal.transactionId,attempt:journal.attempt,plan_digest:planDigest,...abandonment.supersededBy===void 0?{}:{superseded_by:abandonment.supersededBy}}})}export{WorkspaceTransactionInterruptedError,abandonWorkspaceTransaction,commitWorkspaceTransaction,readWorkspaceTransaction,validateWorkspaceTransactionIdentity,workspaceTransactionPlanDigest};
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]="f100554a-d0e9-54c1-9dca-7ea5b79b0dc2")}catch{}})();import{mkdir,readFile}from"node:fs/promises";import path from"node:path";import{createHash}from"node:crypto";import{appendWorkspaceAuditEvent,getWorkspaceHistoryPath,WORKSPACE_HISTORY_ID}from"../core/history/workspace-history.js";import{readHistoryEntries}from"./history-read.js";import{acquireLock}from"../core/lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../core/fs/fs-utils.js";import{nowIso}from"../core/shared/time.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{runAsCoordinatorCompensation}from"../core/store/transaction-coordinator-scope.js";class WorkspaceTransactionInterruptedError extends Error{constructor(message="Workspace transaction interrupted"){super(message),this.name="WorkspaceTransactionInterruptedError"}}const WORKSPACE_TRANSACTION_LOCK_ID="sdk-workspace-transaction",TRANSACTION_ID_PATTERN=/^[a-zA-Z0-9._-]+$/,DEFAULT_LOCK_TTL_SECONDS=30,DEFAULT_LOCK_WAIT_MS=3e3;function requiredIdentifier(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized||!TRANSACTION_ID_PATTERN.test(normalized))throw new TypeError(`${label} must match [a-zA-Z0-9._-]+`);return normalized}function requiredText(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized)throw new TypeError(`${label} must be non-empty`);return normalized}function validateWorkspaceTransactionIdentity(options){return{pmRoot:requiredText(options.pmRoot,"Transaction pmRoot"),transactionId:requiredIdentifier(options.transactionId,"Transaction id"),author:requiredText(options.author,"Transaction author")}}function positiveInteger(value,fallback,label){const resolved=value??fallback;if(!Number.isInteger(resolved)||resolved<=0)throw new TypeError(`${label} must be a positive integer`);return resolved}function journalPath(pmRoot,transactionId){return path.join(pmRoot,"transactions","sdk",`${transactionId}.json`)}async function writeJournal(pmRoot,journal){journal.updatedAt=nowIso();const target=journalPath(pmRoot,journal.transactionId);await mkdir(path.dirname(target),{recursive:!0}),await writeFileAtomic(target,`${JSON.stringify(journal,null,2)}
2
+ `)}function hasValidJournalMetadata(journal){return Number.isInteger(journal.attempt)&&typeof journal.author=="string"&&typeof journal.createdAt=="string"&&typeof journal.updatedAt=="string"&&hasValidAbandonment(journal)}function hasValidAbandonment(journal){const retirement=journal.abandonment;return retirement===void 0?journal.schemaVersion===1&&journal.status!=="abandoned":journal.schemaVersion!==2||retirement===null||typeof retirement!="object"||journal.status==="committed"?!1:typeof retirement.reason=="string"&&retirement.reason.trim().length>0&&typeof retirement.author=="string"&&retirement.author.trim().length>0&&(retirement.supersededBy===void 0||typeof retirement.supersededBy=="string"&&TRANSACTION_ID_PATTERN.test(retirement.supersededBy)&&retirement.supersededBy!==journal.transactionId)}function createResultMap(source){return Object.assign(Object.create(null),source)}function cloneJournalValue(value,label){try{const serialized=JSON.stringify(value,(_key,nestedValue)=>{if(typeof nestedValue=="number"&&!Number.isFinite(nestedValue))throw new TypeError(`${label} contains a non-finite number`);if(nestedValue===void 0||typeof nestedValue=="function"||typeof nestedValue=="symbol")throw new TypeError(`${label} contains a non-JSON value`);return nestedValue});return JSON.parse(serialized)}catch(error){throw new TypeError(`${label} must be JSON serializable`,{cause:error})}}function cloneOptionalJournalValue(value,label){return value===void 0?void 0:cloneJournalValue(value,label)}function setJournalEntry(target,stepId,value,label){const cloned=cloneOptionalJournalValue(value,label);cloned===void 0?delete target[stepId]:target[stepId]=cloned}function isJournalMap(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function hasUniqueKnownStepIds(value,stepIds){return Array.isArray(value)&&new Set(value).size===value.length&&value.every(stepId=>typeof stepId=="string"&&stepIds.includes(stepId))}function hasValidJournalLifecycle(journal,stepIds){if(!hasUniqueKnownStepIds(journal.startedStepIds,stepIds)||!hasUniqueKnownStepIds(journal.completedStepIds,stepIds)||!isJournalMap(journal.results)||!isJournalMap(journal.compensationData))return!1;const startedStepIds=journal.startedStepIds,started=new Set(startedStepIds),completedStepIds=journal.completedStepIds,completed=new Set(completedStepIds);return Object.keys(journal.compensationData).some(stepId=>!started.has(stepId))||Object.keys(journal.results).some(stepId=>!completed.has(stepId))?!1:journal.status==="committed"?stepIds.every(stepId=>completed.has(stepId)):!["compensated","abandoned"].includes(journal.status??"")||completed.size===0&&started.size===0}function invalidJournal(transactionId,detail){return new PmCliError(`Workspace transaction ${transactionId} journal is invalid (${detail})`,EXIT_CODE.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function journalPlanMismatch(transactionId){return new PmCliError(`Workspace transaction ${transactionId} journal does not match the supplied plan`,EXIT_CODE.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function matchesJournalSteps(journal,recorded,requested){return requested===void 0||journal.abandonment!==void 0||journal.status==="compensated"||recorded.length===requested.length&&recorded.every((id,index)=>id===requested[index])}function parseJournal(raw,transactionId,stepIds){let parsed;try{parsed=JSON.parse(raw)}catch{throw invalidJournal(transactionId,"invalid JSON")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw invalidJournal(transactionId,"expected an object");const journal=parsed;if(!((journal.schemaVersion===1||journal.schemaVersion===2)&&journal.transactionId===transactionId))throw invalidJournal(transactionId,"schema version or transaction id does not match the journal file");const recordedStepIds=journal.stepIds;if(!Array.isArray(recordedStepIds)||!hasUniqueKnownStepIds(recordedStepIds,recordedStepIds)||!hasValidJournalLifecycle(journal,recordedStepIds)||!hasValidJournalMetadata(journal)||typeof journal.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(journal.status))throw invalidJournal(transactionId,"invalid lifecycle, metadata, status or step ids");if(!matchesJournalSteps(journal,recordedStepIds,stepIds))throw journalPlanMismatch(transactionId);return{...journal,results:createResultMap(journal.results),compensationData:createResultMap(journal.compensationData)}}async function prepareJournalForApply(options,transactionId,author,stepIds,existing){let journal=existing;const recovered=journal!==void 0;if(journal?.status==="compensating"&&await compensateAppliedSteps(options,journal),journal===void 0||journal.status==="compensated"){const timestamp=nowIso();journal={schemaVersion:1,transactionId,author,status:"applying",attempt:(journal?.attempt??0)+1,createdAt:journal?.createdAt??timestamp,updatedAt:timestamp,stepIds,startedStepIds:[],completedStepIds:[],results:createResultMap(),compensationData:createResultMap(),...options.recoveryData===void 0?{}:{recoveryData:cloneJournalValue(options.recoveryData,"Transaction recovery data")}},await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"prepared")}return{journal,recovered}}async function applyPreparedTransaction(options,journal,recovered){try{await discoverAppliedSteps(journal,options.steps),await writeJournal(options.pmRoot,journal);const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of options.steps){if(completed.has(step.id))continue;const inspection=await step.inspect();let result=cloneOptionalJournalValue(inspection.result,`Step ${step.id} result`);if(inspection.state!=="applied"){const compensationData=await step.prepareCompensation?.();setJournalEntry(journal.compensationData,step.id,compensationData,`Step ${step.id} compensation data`),started.add(step.id),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),await writeJournal(options.pmRoot,journal);const appliedResult=await step.apply();result=cloneOptionalJournalValue(appliedResult,`Step ${step.id} result`)}await emitTransition(options,journal,"step_applied",step.id),completed.add(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),setJournalEntry(journal.results,step.id,result,`Step ${step.id} result`),await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_recorded",step.id)}return await emitTransition(options,journal,"committing"),journal.status="committed",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"committed"),{transactionId:journal.transactionId,status:"committed",recovered,results:createResultMap(journal.results)}}catch(error){if(error instanceof WorkspaceTransactionInterruptedError||journal.status==="committed")throw error;try{await compensateAppliedSteps(options,journal)}catch(compensationError){throw new AggregateError([error,compensationError],`Workspace transaction failed and compensation failed: ${String(compensationError)}`,{cause:compensationError})}throw error}}async function loadJournal(pmRoot,transactionId,stepIds){try{return parseJournal(await readFile(journalPath(pmRoot,transactionId),"utf8"),transactionId,stepIds)}catch(error){if(error!==null&&typeof error=="object"&&"code"in error&&isFileMissingError(error))return;throw error}}async function emitTransition(options,journal,transition,stepId){await options.onTransition?.({transactionId:journal.transactionId,attempt:journal.attempt,transition,...stepId===void 0?{}:{stepId}})}async function discoverAppliedSteps(journal,steps){const completed=new Set,results=createResultMap();for(const step of steps){const inspection=await step.inspect();inspection.state==="applied"&&(completed.add(step.id),setJournalEntry(results,step.id,inspection.result,`Step ${step.id} result`))}journal.results=results,journal.completedStepIds=steps.map(step=>step.id).filter(stepId=>completed.has(stepId))}async function compensateAppliedSteps(options,journal){journal.status="compensating",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensating");const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of[...options.steps].reverse()){if(!started.has(step.id)&&!completed.has(step.id))continue;let shouldCompensate;try{const state=(await step.inspect()).state;shouldCompensate=started.has(step.id)&&(state==="applied"||state==="pending"&&step.compensatePending===!0)}catch{shouldCompensate=started.has(step.id)}shouldCompensate&&(await emitTransition(options,journal,"step_compensating",step.id),await runAsCoordinatorCompensation({pmRoot:options.pmRoot,transactionId:journal.transactionId,step},()=>step.compensate(journal.compensationData[step.id]))),completed.delete(step.id),started.delete(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),delete journal.results[step.id],delete journal.compensationData[step.id],await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_compensated",step.id)}journal.status="compensated",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensated")}async function commitWorkspaceTransaction(options){const{pmRoot,transactionId,author}=validateWorkspaceTransactionIdentity(options),lockTtlSeconds=positiveInteger(options.lockTtlSeconds,DEFAULT_LOCK_TTL_SECONDS,"Transaction lock TTL"),lockWaitMs=positiveInteger(options.lockWaitMs,DEFAULT_LOCK_WAIT_MS,"Transaction lock wait"),steps=[...options.steps];if(steps.length===0)throw new TypeError("Workspace transaction requires at least one step");const stepIds=steps.map(step=>{const stepId=requiredIdentifier(step.id,"Transaction step id");if(stepId!==step.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return stepId});if(new Set(stepIds).size!==stepIds.length)throw new TypeError("Workspace transaction step ids must be unique");const stableOptions={...options,pmRoot,transactionId,author,steps,lockTtlSeconds,lockWaitMs},release=await acquireLock(pmRoot,WORKSPACE_TRANSACTION_LOCK_ID,lockTtlSeconds,author,!1,!1,lockWaitMs);try{const existing=await loadJournal(pmRoot,transactionId,stepIds);if(existing?.status==="abandoned"||existing?.abandonment!==void 0)throw retiredTransaction(existing);const recovered=existing!==void 0;if(existing?.status==="committed")return{transactionId,status:"committed",recovered:!0,results:createResultMap(existing.results)};const prepared=await prepareJournalForApply(stableOptions,transactionId,author,stepIds,existing);return await applyPreparedTransaction(stableOptions,prepared.journal,recovered||prepared.recovered)}finally{await release()}}function retiredTransaction(journal){const pending=journal.status!=="abandoned",supersededBy=journal.abandonment.supersededBy,retry=supersededBy===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(journal.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(supersededBy)} to finish retirement of ${JSON.stringify(journal.transactionId)}.`;return new PmCliError(pending?`Transaction ${journal.transactionId} retirement is incomplete`:`Transaction ${journal.transactionId} has been abandoned`,EXIT_CODE.CONFLICT,{code:"transaction_abandoned",required:pending?retry:"Use a new transactionId for the replacement plan.",why:pending?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...pending?{retirement:{state:"pending",superseded_by:supersededBy??null},nextSteps:[retry]}:{}})}async function readWorkspaceTransaction(pmRoot,transactionId){const identity=validateWorkspaceTransactionIdentity({pmRoot,transactionId,author:"reader"});return loadJournal(identity.pmRoot,identity.transactionId)}function workspaceTransactionPlanDigest(journal){return createHash("sha256").update(JSON.stringify(journal.stepIds)).digest("hex")}async function abandonWorkspaceTransaction(options){const identity=validateWorkspaceTransactionIdentity(options),reason=requiredText(options.reason,"Abandonment reason"),supersededBy=options.supersededBy===void 0?void 0:requiredIdentifier(options.supersededBy,"Replacement transaction id");if(supersededBy===identity.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");const lockTtlSeconds=positiveInteger(options.lockTtlSeconds,DEFAULT_LOCK_TTL_SECONDS,"Transaction lock TTL"),lockWaitMs=positiveInteger(options.lockWaitMs,DEFAULT_LOCK_WAIT_MS,"Transaction lock wait"),release=await acquireLock(identity.pmRoot,WORKSPACE_TRANSACTION_LOCK_ID,lockTtlSeconds,identity.author,!1,!1,lockWaitMs);try{const journal=await loadJournal(identity.pmRoot,identity.transactionId);if(journal===void 0)throw new PmCliError(`Transaction ${identity.transactionId} was not found`,EXIT_CODE.NOT_FOUND);if(journal.status==="committed")throw new PmCliError(`Transaction ${identity.transactionId} is committed and cannot be abandoned`,EXIT_CODE.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(journal.abandonment!==void 0&&journal.abandonment.supersededBy!==supersededBy)throw retiredTransaction(journal);if(journal.status==="abandoned")return journal;const steps=options.resolveSteps(structuredClone(journal));if(JSON.stringify(steps.map(step=>step.id))!==JSON.stringify(journal.stepIds))throw journalPlanMismatch(identity.transactionId);if(journal.abandonment===void 0){if(supersededBy!==void 0&&await loadJournal(identity.pmRoot,supersededBy)!==void 0)throw new PmCliError(`Replacement transaction ${supersededBy} already exists`,EXIT_CODE.CONFLICT);journal.schemaVersion=2,journal.abandonment={reason,author:identity.author,...supersededBy===void 0?{}:{supersededBy}},await writeJournal(identity.pmRoot,journal)}return journal.status!=="compensated"&&await compensateAppliedSteps({...options,...identity,steps},journal),await auditTransactionAbandonment(journal,identity.pmRoot,lockTtlSeconds,lockWaitMs),journal.status="abandoned",await writeJournal(identity.pmRoot,journal),journal}finally{await release()}}async function auditTransactionAbandonment(journal,pmRoot,lockTtlSeconds,lockWaitMs){const planDigest=workspaceTransactionPlanDigest(journal);if((await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID)).some(entry=>entry.op==="transaction_abandon"&&entry.context?.transaction_id===journal.transactionId&&entry.context?.attempt===journal.attempt&&entry.context?.plan_digest===planDigest))return;const abandonment=journal.abandonment;await appendWorkspaceAuditEvent({pmRoot,author:abandonment.author,lockTtlSeconds,lockWaitMs,op:"transaction_abandon",message:abandonment.reason,context:{transaction_id:journal.transactionId,attempt:journal.attempt,plan_digest:planDigest,...abandonment.supersededBy===void 0?{}:{superseded_by:abandonment.supersededBy}}})}export{WorkspaceTransactionInterruptedError,abandonWorkspaceTransaction,commitWorkspaceTransaction,readWorkspaceTransaction,validateWorkspaceTransactionIdentity,workspaceTransactionPlanDigest};
3
3
  //# sourceMappingURL=workspace-transaction.js.map
@@ -317,7 +317,7 @@ Use the public SDK barrel. Do not deep-import from `src/core` or `dist/core`.
317
317
  - `api.registerRenderer("toon" | "json", renderer, ownership?)` adds format-specific renderers. Scope ownership with `commands` and/or a `resultDiscriminator`; the host checks both before invoking the renderer and falls back to native rendering for unrelated output. The legacy unscoped callback remains supported, but doctor warns because package ownership cannot be proven statically.
318
318
  - `suppressHostOutput(result?)` from `@unbrained/pm-cli/sdk` marks commands that already wrote output, preventing a second CLI payload while retaining the optional result for hooks, telemetry, and embedded hosts.
319
319
  - `api.hooks.beforeCommand(handler)`, `api.hooks.beforeMutation(handler)`, `api.hooks.afterCommand(handler)`, `api.hooks.onWrite(handler)`, `api.hooks.onRead(handler)`, and `api.hooks.onIndex(handler)` add lifecycle hooks.
320
- `beforeMutation` is a fail-closed invariant boundary inside the item lock and before item or history persistence. It receives canonical `before`/`after` snapshots, `operation`, `changed_fields`, and a host-bound read-only `sdk` with `get`/`list`. Return `{ allow: true }` (or nothing) to continue, or `{ allow: false, code, message?, remediation }` to deny with stable structured guidance. A thrown error or malformed denial blocks the write. The boundary covers create, update, close, delete, restore, annotations, and structured/bulk mutations because those surfaces share the same lifecycle primitives. The context also carries a read-only `actor` (GH-1719): `author` and `author_source` (`asserted`, `configured`, `detected` or `unknown`) exactly as the mutation's history entry records them, the ownership `principal` the claim check compares with an item's `claim_principal`, and the recorded `agent` provenance (`harness`, `model`, `model_source`, `instance`) when a harness was detected. The host resolves it from the mutation's own author on every surface (CLI, SDK, MCP); it is never a placeholder, so an unattributed write reports `author: "unknown"` with `author_source: "unknown"`. `dry_run` is `true` when the guard judges a preview that persists nothing: `previewItemMutations` and structured CLI previews evaluate the guards against the staged plan with the same actor the commit presents, and `pm delete --dry-run` evaluates them before reporting. Guards that read neither field keep working unchanged. See [SDK: actor-aware mutation guards](SDK.md#actor-aware-mutation-guards) for a claimant-only close policy.
320
+ `beforeMutation` is a fail-closed invariant boundary inside the item lock and before item or history persistence. It receives canonical `before`/`after` snapshots, `operation`, `changed_fields`, and a host-bound read-only `sdk` with `get`/`list`. Return `{ allow: true }` (or nothing) to continue, or `{ allow: false, code, message?, remediation }` to deny with stable structured guidance. A thrown error or malformed denial blocks the write. The boundary covers create, update, close, delete, restore, annotations, and structured/bulk mutations because those surfaces share the same lifecycle primitives. The context also carries a read-only `actor` (GH-1719): `author` and `author_source` (`asserted`, `configured`, `detected` or `unknown`) exactly as the mutation's history entry records them, the ownership `principal` the claim check compares with an item's `claim_principal`, and the recorded `agent` provenance (`harness`, `model`, `model_source`, `instance`) when a harness was detected. The host resolves it from the mutation's own author on every surface (CLI, SDK, MCP); it is never a placeholder, so an unattributed write reports `author: "unknown"` with `author_source: "unknown"`. `dry_run` is `true` when the guard judges a preview that persists nothing: `previewItemMutations` and structured CLI previews evaluate the guards against the staged plan with the same actor the commit presents, and `pm delete --dry-run` evaluates them before reporting. Guards that read neither field keep working unchanged. A transaction's own rollback is the one write a guard cannot refuse (pm-wb6ktl). When the transaction coordinator itself compensates a failed `commitItemMutations` batch, and the item's history proves the effects are the step's own, the context carries `compensation` (`transaction_id`, `step_id`). The host builds that field from the coordinator's scope, never from caller input. A direct helper call, a caller-supplied coordinator step, a legacy receipt, or a write that proposes the scoped id for another stored item gets no exemption. The guard still runs and can observe the rollback. A denial, failure or timeout is recorded in the rollback's history entry under `transaction_compensation.overridden` and is not enforced, so no guard can leave a batch half-applied. See [SDK: actor-aware mutation guards](SDK.md#actor-aware-mutation-guards) for a claimant-only close policy.
321
321
  `afterCommand` receives command outcome fields plus optional compact `affected` item entries for mutations, including `previous_status`, `status`, `changed_fields`, and partial `previous`/`current` item metadata snapshots.
322
322
  `onWrite` always includes `path`, `scope`, and `op`; item mutations also add optional `item_id`, `item_type`, `before`, `after`, and `changed_fields`.
323
323
  - Registered command, importer, and exporter handlers receive `context.sdk`, a host-bound service bundle containing a native-action `PmClient`, `getItemAt`, and `openRelationshipEventStore`, alongside portable workspace coordinates. The client reuses the already-active extension schema context without recursively loading extensions, so package commands and data adapters can compose core lifecycle operations safely in CLI and SDK hosts.
@@ -10,7 +10,7 @@ This note documents behavioral and output-shape changes introduced in the conser
10
10
 
11
11
  - long-flag shape normalization (`--foo_bar` / camel variants -> canonical kebab flags)
12
12
  - high-confidence typo normalization for long flags
13
- - `key=value` / `key:value` promotion into canonical `--flag value` tokens when unambiguous
13
+ - `key=value` / `key:value` promotion into canonical `--flag value` tokens when unambiguous. A `key:value` token promotes only when it contains no whitespace. The shell already grouped a token such as `"Docs: adopt X"`, so it stays text, for example a `pm create` title. A create refusal names any token it promoted and retries with `--title` ([GH-1741](https://github.com/unbraind/pm-cli/issues/1741))
14
14
  - legacy `pm extension <action>` shorthand normalization to explicit action flags
15
15
 
16
16
  Normalization runs across command families and preserves a normalization trace for diagnostics and recovery.
package/docs/SDK.md CHANGED
@@ -2160,7 +2160,36 @@ api.hooks.beforeMutation(({ operation, before, actor }) => {
2160
2160
 
2161
2161
  Hosts never supply a placeholder: an unattributed write reports
2162
2162
  `author: "unknown"` with `author_source: "unknown"`. `runRegisteredMutationGuardForTest`
2163
- resolves an omitted test `actor` from the context's `author` the same way. Preview cost is proportional to the tracker data
2163
+ resolves an omitted test `actor` from the context's `author` the same way.
2164
+
2165
+ #### Transaction rollbacks
2166
+
2167
+ A guard that denies `close`, `delete` or `restore` must not wedge a refused
2168
+ batch half-applied (pm-wb6ktl). When a later step of `commitItemMutations` is
2169
+ refused, the coordinator compensates the steps it applied. It closes or deletes
2170
+ the items it created and restores the items it updated. The exemption needs
2171
+ three proofs. The coordinator itself must be compensating that step, and the
2172
+ step must be one the SDK built from the batch plan for that item and operation,
2173
+ never a step a caller supplied to `commitWorkspaceTransaction`. The item's immutable history must prove the effects are the step's own:
2174
+ a create whose whole history belongs to the transaction, or a restore receipt
2175
+ bound to the history prefix the journal captured. Finally, the ownership check
2176
+ must have held against the locked item stored under that id. Only that write
2177
+ carries `compensation: { transaction_id, step_id }` in the guard context, which
2178
+ the host builds from an allowlist, so a caller cannot supply the field.
2179
+ Guards still judge it. A denial, a thrown error or a timeout is recorded instead
2180
+ of refusing the rollback, and so is an unsatisfied workflow-policy refusal. The
2181
+ rollback's history entry lists each one under
2182
+ `context.transaction_compensation.overridden`, for example
2183
+ `{ source: "mutation_guard", guard: "project:claimant-close", code: "close_requires_claimant" }`.
2184
+ The batch then reports the original refusal. All of the following are judged
2185
+ normally: a write to another item, a write that proposes the scoped id for a
2186
+ different stored item, another operation, an ordinary close that reuses the
2187
+ compensation history message, a direct call of a compensation helper, a
2188
+ caller-supplied coordinator step that calls one, and a legacy receipt identified
2189
+ by its message alone. Pass `compensation` to `runRegisteredMutationGuardForTest` (or
2190
+ `harness.runMutationGuard`) to exercise a guard's rollback branch: it then
2191
+ resolves the recorded overrides instead of refusing, while an ordinary context
2192
+ still resolves `undefined`. As on a host, a dry-run context is never exempted. Preview cost is proportional to the tracker data
2164
2193
  staged, rather than unrelated root-layout project content.
2165
2194
 
2166
2195
  `itemDocumentToMutationOptions` is the companion full-document adapter. It
@@ -4269,8 +4298,16 @@ deferrals as curation work, and strict close refuses the item with
4269
4298
  `close_validation_deferred_fields` until every deferred field has a value.
4270
4299
  Package import adapters (`commitImportedItem`) now run the tracker's
4271
4300
  `beforeMutation` guards as operation `import`, with the importer's actor. A
4272
- guard denial propagates as a refusal; only a held item lock returns the
4273
- skippable `conflictWarning`.
4301
+ guard denial propagates as a refusal. Only a held item lock, or an id that a
4302
+ concurrent importer committed under the lock after the caller's own existence
4303
+ check, returns the skippable `conflictWarning`. The adapter holds its lock as a
4304
+ lease and fences the item write and history append with it (pm-0m64xk). With
4305
+ pm's native file locks, if policies or guards outlast `locks.ttl_seconds` and
4306
+ another writer takes the lock over, the import refuses with `lock_lost` and
4307
+ writes nothing, so the other writer's item is never overwritten. `create` and
4308
+ `pm copy` fence their writes the same way. An extension that handles
4309
+ `lock_acquire` owns its lock lifecycle: its leases commit unfenced, so it must
4310
+ supply its own stale-writer protection.
4274
4311
 
4275
4312
  By default the auto-created command only has a handler. Pass an optional third
4276
4313
  `ImportExportRegistrationOptions` argument to make it a first-class command with a
@@ -96,6 +96,29 @@ does not claim a completed append. This disclosure is tracked by
96
96
  Accepted mutations attach bounded policy decisions to their normal
97
97
  history event. Diagnostics contain policy ids and missing field paths, without
98
98
  copying reviewed content into errors.
99
+
100
+ Every item writer evaluates the policies before it persists anything: create,
101
+ update, close, delete, restore, package imports (operation `import`) and
102
+ `pm copy`. A copy is judged with operation `create`, so a policy that refuses a
103
+ creation also refuses copying an existing item into that shape, and the copy's
104
+ history event carries the same decisions a create records
105
+ ([pm-womkyw](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-womkyw.toon),
106
+ a repository-only tracker record excluded from npm).
107
+
108
+ A transaction's own rollback is the one write a refusal cannot stop. When
109
+ `commitItemMutations` compensates a failed batch, it closes or deletes the
110
+ items it created and restores the items it updated. It does so only while the
111
+ coordinator itself compensates a step the SDK built from the batch plan, after the item's immutable history
112
+ proves those effects are the step's own, and only for the locked item stored
113
+ under that id. The policies
114
+ still evaluate that rollback, and its history event records their decisions. An
115
+ unsatisfied refusal is listed under `transaction_compensation.overridden` and is
116
+ not enforced. Otherwise a policy that refuses closing, deleting or restoring
117
+ would leave the batch half-applied. A write to any other item, any other
118
+ operation, a compensation helper called directly, or a caller-supplied
119
+ coordinator step is judged normally
120
+ ([pm-wb6ktl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wb6ktl.toon),
121
+ a repository-only tracker record excluded from npm).
99
122
  If the mandatory refusal audit cannot be appended, the mutation instead raises
100
123
  `workflow_policy_audit_failed` and preserves the original failure in the SDK
101
124
  error's `cause`. Item data remains unchanged; resolve the workspace history lock
package/marketplace.json CHANGED
@@ -1 +1 @@
1
- {"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.11.16","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","description":"Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.","version":"2026.11.16","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
1
+ {"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.11.17","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","description":"Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.","version":"2026.11.17","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "2.12.0";
1
+ export declare const VERSION = "2.12.1";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -3,5 +3,5 @@
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
5
  // this is autogenerated file, see scripts/version-update.js
6
- export const VERSION = '2.12.0';
6
+ export const VERSION = '2.12.1';
7
7
  //# sourceMappingURL=version.js.map
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "2.12.0";
1
+ export declare const VERSION = "2.12.1";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -3,5 +3,5 @@
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
5
  // this is autogenerated file, see scripts/version-update.js
6
- export const VERSION = '2.12.0';
6
+ export const VERSION = '2.12.1';
7
7
  //# sourceMappingURL=version.js.map
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "2.12.0";
1
+ export declare const VERSION = "2.12.1";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -6,5 +6,5 @@
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.VERSION = void 0;
8
8
  // this is autogenerated file, see scripts/version-update.js
9
- exports.VERSION = '2.12.0';
9
+ exports.VERSION = '2.12.1';
10
10
  //# sourceMappingURL=version.js.map
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentelemetry/core",
3
- "version": "2.12.0",
3
+ "version": "2.12.1",
4
4
  "description": "OpenTelemetry Core provides constants and utilities shared by all OpenTelemetry SDK packages.",
5
5
  "main": "build/src/index.js",
6
6
  "module": "build/esm/index.js",
@@ -91,5 +91,5 @@
91
91
  },
92
92
  "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-core",
93
93
  "sideEffects": false,
94
- "gitHead": "92b844e8aa7d9655e4b3560154e912c4c1ced64d"
94
+ "gitHead": "8795a06d2c025d5dc454d85cec785849844cc5d9"
95
95
  }
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" />
2
2
  import * as child_process from 'child_process';
3
3
  export declare const execAsync: typeof child_process.exec.__promisify__;
4
+ export declare const execFileAsync: typeof child_process.execFile.__promisify__;
4
5
  //# sourceMappingURL=execAsync.d.ts.map
@@ -5,4 +5,5 @@
5
5
  import * as child_process from 'child_process';
6
6
  import * as util from 'util';
7
7
  export const execAsync = util.promisify(child_process.exec);
8
+ export const execFileAsync = util.promisify(child_process.execFile);
8
9
  //# sourceMappingURL=execAsync.js.map