@unbrained/pm-cli 2026.11.14 → 2026.11.16

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 (281) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +1 -1
  3. package/dist/cli/error-guidance.js +2 -2
  4. package/dist/cli/extension-command-help.js +2 -2
  5. package/dist/cli/help-content.js +2 -2
  6. package/dist/cli/register-operations.js +1 -1
  7. package/dist/cli-bundle/bundle-manifest.json +1 -1
  8. package/dist/cli-bundle/chunks/{chunk-UJMQP2HP.js → chunk-2D26HRXB.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-EXO4PM5J.js → chunk-2WNORBVN.js} +86 -71
  10. package/dist/cli-bundle/chunks/chunk-4I7YG3VZ.js +3 -0
  11. package/dist/cli-bundle/chunks/chunk-4WIVCOA7.js +2 -0
  12. package/dist/cli-bundle/chunks/chunk-A3WCP4TU.js +6 -0
  13. package/dist/cli-bundle/chunks/chunk-AB5S6TWE.js +124 -0
  14. package/dist/cli-bundle/chunks/chunk-BV7J3LRH.js +114 -0
  15. package/dist/cli-bundle/chunks/{chunk-AXTUB74T.js → chunk-DZWRNL6R.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-E4BQRZF2.js +10 -0
  17. package/dist/cli-bundle/chunks/chunk-ERD2RYWM.js +31 -0
  18. package/dist/cli-bundle/chunks/chunk-F7P42FL5.js +9 -0
  19. package/dist/cli-bundle/chunks/{chunk-547OEGDR.js → chunk-FZ4XWWLO.js} +25 -25
  20. package/dist/cli-bundle/chunks/{chunk-65SBMIK6.js → chunk-I3T2FVUA.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-IGEBFNWE.js +2 -0
  22. package/dist/cli-bundle/chunks/chunk-IYICNCK2.js +2 -0
  23. package/dist/cli-bundle/chunks/chunk-J257NZRD.js +20 -0
  24. package/dist/cli-bundle/chunks/chunk-JD3XWF66.js +3 -0
  25. package/dist/cli-bundle/chunks/chunk-JLHD7OQ2.js +2 -0
  26. package/dist/cli-bundle/chunks/{chunk-V2OAXGHK.js → chunk-KGOGLKL2.js} +2 -2
  27. package/dist/cli-bundle/chunks/chunk-LC4DJVXR.js +2 -0
  28. package/dist/cli-bundle/chunks/chunk-NHNM3GIP.js +3 -0
  29. package/dist/cli-bundle/chunks/{chunk-RSAN2YUU.js → chunk-NYN5OR2T.js} +2 -2
  30. package/dist/cli-bundle/chunks/chunk-OFZQEQ6X.js +2 -0
  31. package/dist/cli-bundle/chunks/chunk-QGL5IAP4.js +8 -0
  32. package/dist/cli-bundle/chunks/chunk-R24NZ2TB.js +8 -0
  33. package/dist/cli-bundle/chunks/chunk-VJLZHOTP.js +2 -0
  34. package/dist/cli-bundle/chunks/chunk-VO2HSB5F.js +2 -0
  35. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-I6RQGD6Y.js → indexed-receipt-blobs-HNLN6UXH.js} +2 -2
  36. package/dist/cli-bundle/chunks/item-revision-PSOL5I4H.js +2 -0
  37. package/dist/cli-bundle/chunks/item-transaction-55QTCU2M.js +2 -0
  38. package/dist/cli-bundle/chunks/mutation-actor-BDBBH3ZS.js +2 -0
  39. package/dist/cli-bundle/chunks/mutation-admission-WUN7JYVJ.js +2 -0
  40. package/dist/cli-bundle/chunks/{register-list-query-MCNOV6ML.js → register-list-query-AESCVO6H.js} +2 -2
  41. package/dist/cli-bundle/chunks/{register-mutation-KYXLYHOK.js → register-mutation-SKCEP5QU.js} +3 -3
  42. package/dist/cli-bundle/chunks/register-operations-ZT4OYCF3.js +2 -0
  43. package/dist/cli-bundle/chunks/register-setup-JVWNS2TY.js +2 -0
  44. package/dist/cli-bundle/chunks/{settlement-hook-JHXLUBEN.js → settlement-hook-MVVVUIVZ.js} +2 -2
  45. package/dist/cli-bundle/chunks/stage-RMU3JAWM.js +2 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-3WVMEA2A.js +6 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-5UVJOAUP.js +91 -0
  48. package/dist/cli-bundle/focused-chunks/chunk-5WQ3LNUK.js +78 -0
  49. package/dist/cli-bundle/focused-chunks/chunk-6E4X7MQA.js +26 -0
  50. package/dist/cli-bundle/focused-chunks/{chunk-IDAYTYNN.js → chunk-7SEPCQV2.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-EXCVUBAE.js → chunk-7XHE335U.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-BEHIMEV2.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-CZFZCSOX.js +2 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-TA4EGVE6.js → chunk-DFBHW7HP.js} +3 -3
  55. package/dist/cli-bundle/focused-chunks/chunk-DZMP3VYQ.js +26 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-HHMMIHZP.js +2 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-HPC2M6JD.js +6 -0
  58. package/dist/cli-bundle/focused-chunks/{chunk-EAYRYXA6.js → chunk-HR5FEUUL.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/chunk-J7ESCE7M.js +24 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-KRNF3WTC.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/chunk-KWZLY35A.js +2 -0
  62. package/dist/cli-bundle/focused-chunks/chunk-M4IA4LC6.js +8 -0
  63. package/dist/cli-bundle/focused-chunks/{chunk-3SUKWYR2.js → chunk-NASE6JC2.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/chunk-ONM2R32I.js +65 -0
  65. package/dist/cli-bundle/focused-chunks/chunk-PDXSMSO5.js +3 -0
  66. package/dist/cli-bundle/focused-chunks/chunk-PEL4SQXV.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/chunk-QJ647CQE.js +2 -0
  68. package/dist/cli-bundle/focused-chunks/chunk-SFATIM77.js +12 -0
  69. package/dist/cli-bundle/focused-chunks/{chunk-EH7JKGDH.js → chunk-UBBTBNUY.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/chunk-ZCN35TCK.js +2 -0
  71. package/dist/cli-bundle/focused-chunks/chunk-ZSQ2FT22.js +44 -0
  72. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-7XGVHYAO.js → indexed-receipt-blobs-ADMQXF3N.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/item-revision-GNKYO6GZ.js +2 -0
  74. package/dist/cli-bundle/focused-chunks/item-transaction-AUUQHR5Z.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/mutation-actor-OBRD7HFZ.js +2 -0
  76. package/dist/cli-bundle/focused-chunks/mutation-admission-6TX3EOJX.js +2 -0
  77. package/dist/cli-bundle/focused-chunks/{settlement-hook-H56537UV.js → settlement-hook-5U2M75BY.js} +2 -2
  78. package/dist/cli-bundle/focused-chunks/stage-LERF2YJU.js +2 -0
  79. package/dist/cli-bundle/main.js +10 -10
  80. package/dist/cli-bundle/sdk-authoring.js +1 -1
  81. package/dist/cli-bundle/sdk-contracts.js +3 -3
  82. package/dist/cli-bundle/sdk-core.js +1 -1
  83. package/dist/cli-bundle/sdk-governance.js +1 -1
  84. package/dist/cli-bundle/sdk-graph.js +1 -1
  85. package/dist/cli-bundle/sdk-merge.js +57 -57
  86. package/dist/cli-bundle/sdk-query.js +1 -1
  87. package/dist/cli-bundle/sdk-runtime.js +1 -1
  88. package/dist/cli-bundle/sdk-testing.js +1 -1
  89. package/dist/cli-bundle/sdk.js +11 -11
  90. package/dist/core/diagnostics/remediation.js +1 -1
  91. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  92. package/dist/core/extensions/extension-types.d.ts +30 -0
  93. package/dist/core/extensions/extension-types.js +1 -1
  94. package/dist/core/extensions/index.d.ts +21 -1
  95. package/dist/core/extensions/index.js +1 -1
  96. package/dist/core/extensions/mutation-actor-snapshot.js +2 -0
  97. package/dist/core/extensions/mutation-actor.js +2 -0
  98. package/dist/core/item/deferred-fields.js +2 -0
  99. package/dist/core/item/item-format-version.d.ts +8 -7
  100. package/dist/core/item/item-format-version.js +1 -1
  101. package/dist/core/item/item-format.js +2 -2
  102. package/dist/core/output/mutation-projection.js +1 -1
  103. package/dist/core/output/output.d.ts +7 -0
  104. package/dist/core/output/output.js +3 -3
  105. package/dist/core/schema/runtime-field-values.d.ts +4 -0
  106. package/dist/core/schema/runtime-field-values.js +1 -1
  107. package/dist/core/shared/errors.d.ts +22 -0
  108. package/dist/core/shared/errors.js +1 -1
  109. package/dist/core/shared/item-metadata-contract.js +1 -1
  110. package/dist/core/store/item-store.d.ts +15 -4
  111. package/dist/core/store/item-store.js +1 -1
  112. package/dist/core/telemetry/policy.d.ts +21 -2
  113. package/dist/core/telemetry/policy.js +1 -1
  114. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  115. package/dist/sdk/authoring.d.ts +1 -1
  116. package/dist/sdk/authoring.js +1 -1
  117. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  118. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  119. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  120. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  121. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -1
  122. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  123. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +1 -1
  124. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  125. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  126. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  127. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  128. package/dist/sdk/completion/bash.js +1 -1
  129. package/dist/sdk/completion/fish.js +4 -1
  130. package/dist/sdk/completion/zsh.js +14 -2
  131. package/dist/sdk/extension/command-options.d.ts +23 -4
  132. package/dist/sdk/extension/command-options.js +1 -1
  133. package/dist/sdk/extension/native-command-options.js +2 -0
  134. package/dist/sdk/flag-invocation-contracts.js +1 -1
  135. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  136. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  137. package/dist/sdk/governance/health.js +2 -2
  138. package/dist/sdk/governance/in-progress-work-health.d.ts +49 -0
  139. package/dist/sdk/governance/in-progress-work-health.js +2 -0
  140. package/dist/sdk/governance/lifecycle-dependency-cycles.d.ts +12 -0
  141. package/dist/sdk/governance/lifecycle-dependency-cycles.js +2 -0
  142. package/dist/sdk/governance/stale-work.d.ts +143 -2
  143. package/dist/sdk/governance/stale-work.js +1 -1
  144. package/dist/sdk/governance/validate-deferred-fields.js +2 -0
  145. package/dist/sdk/governance/validate.d.ts +2 -2
  146. package/dist/sdk/governance/validate.js +1 -1
  147. package/dist/sdk/governance.d.ts +1 -1
  148. package/dist/sdk/governance.js +1 -1
  149. package/dist/sdk/history-compact.js +1 -1
  150. package/dist/sdk/index.d.ts +1 -1
  151. package/dist/sdk/index.js +1 -1
  152. package/dist/sdk/item-transaction.d.ts +2 -2
  153. package/dist/sdk/item-transaction.js +1 -1
  154. package/dist/sdk/lifecycle/claim.d.ts +46 -3
  155. package/dist/sdk/lifecycle/claim.js +1 -1
  156. package/dist/sdk/lifecycle/close.js +1 -1
  157. package/dist/sdk/lifecycle/copy.js +1 -1
  158. package/dist/sdk/lifecycle/create-deferrals.js +2 -0
  159. package/dist/sdk/lifecycle/create.d.ts +6 -2
  160. package/dist/sdk/lifecycle/create.js +1 -1
  161. package/dist/sdk/lifecycle/restore.js +1 -1
  162. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +7 -1
  163. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  164. package/dist/sdk/lifecycle/task-composition.js +1 -1
  165. package/dist/sdk/merge/three-way.d.ts +1 -1
  166. package/dist/sdk/merge/three-way.js +2 -2
  167. package/dist/sdk/ownership-source.d.ts +32 -0
  168. package/dist/sdk/ownership-source.js +1 -1
  169. package/dist/sdk/package-import-adapters.d.ts +9 -1
  170. package/dist/sdk/package-import-adapters.js +1 -1
  171. package/dist/sdk/public-surface.json +1 -1
  172. package/dist/sdk/query/complete-list.d.ts +14 -5
  173. package/dist/sdk/query/complete-list.js +1 -1
  174. package/dist/sdk/query/context.d.ts +5 -1
  175. package/dist/sdk/query/context.js +2 -2
  176. package/dist/sdk/query/list.js +1 -1
  177. package/dist/sdk/query/next.d.ts +19 -3
  178. package/dist/sdk/query/next.js +1 -1
  179. package/dist/sdk/query/projection-contracts.d.ts +6 -0
  180. package/dist/sdk/query/projection-contracts.js +1 -1
  181. package/dist/sdk/read-output/extension.js +1 -1
  182. package/dist/sdk/runtime-input.d.ts +6 -2
  183. package/dist/sdk/runtime-input.js +1 -1
  184. package/dist/sdk/runtime-primitives.d.ts +2 -2
  185. package/dist/sdk/runtime-primitives.js +1 -1
  186. package/dist/sdk/runtime.d.ts +2 -2
  187. package/dist/sdk/runtime.js +1 -1
  188. package/dist/sdk/structured-mutations.js +1 -1
  189. package/dist/sdk/testing.d.ts +15 -2
  190. package/dist/sdk/testing.js +1 -1
  191. package/dist/types.d.ts +8 -0
  192. package/dist/types.js +1 -1
  193. package/docs/AGENT_GUIDE.md +2 -0
  194. package/docs/COMMANDS.md +31 -0
  195. package/docs/CONFIGURATION.md +20 -7
  196. package/docs/EXTENSIONS.md +1 -1
  197. package/docs/LIFECYCLE_COMMANDS.md +8 -1
  198. package/docs/MUTATION_INTEGRITY.md +79 -1
  199. package/docs/SDK.md +139 -5
  200. package/docs/generated/FLAG_LEXICON_BUDGETS.md +3 -3
  201. package/marketplace.json +1 -1
  202. package/node_modules/commander/Readme.md +6 -32
  203. package/node_modules/commander/index.js +1 -1
  204. package/node_modules/commander/lib/command.js +22 -9
  205. package/node_modules/commander/lib/help.js +6 -2
  206. package/node_modules/commander/lib/option.js +1 -1
  207. package/node_modules/commander/package.json +2 -1
  208. package/node_modules/commander/typings/index.d.ts +6 -3
  209. package/node_modules/semver/classes/range.js +2 -2
  210. package/node_modules/semver/internal/constants.js +30 -0
  211. package/node_modules/semver/internal/trim-comparator-whitespace.js +438 -0
  212. package/node_modules/semver/package.json +1 -1
  213. package/package.json +8 -5
  214. package/packages/pm-beads/package.json +1 -1
  215. package/packages/pm-calendar/extensions/calendar/command-definitions.ts +2 -0
  216. package/packages/pm-calendar/package.json +1 -1
  217. package/packages/pm-command-kit/package.json +1 -1
  218. package/packages/pm-digital-twin/package.json +1 -1
  219. package/packages/pm-governance-audit/package.json +1 -1
  220. package/packages/pm-guide-shell/package.json +1 -1
  221. package/packages/pm-kanban/package.json +1 -1
  222. package/packages/pm-lifecycle-hooks/package.json +1 -1
  223. package/packages/pm-linked-test-adapters/package.json +1 -1
  224. package/packages/pm-search-advanced/package.json +1 -1
  225. package/packages/pm-templates/package.json +1 -1
  226. package/packages/pm-todos/extensions/todos/runtime.ts +3 -0
  227. package/packages/pm-todos/package.json +1 -1
  228. package/packages/pm-vcs/package.json +1 -1
  229. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  230. package/plugins/pm-claude/package.json +1 -1
  231. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  232. package/plugins/pm-codex/package.json +1 -1
  233. package/plugins/pm-codex/plugin.json +1 -1
  234. package/runtime-dependencies.json +1 -1
  235. package/dist/cli-bundle/chunks/chunk-25BUKX4W.js +0 -2
  236. package/dist/cli-bundle/chunks/chunk-27FG6ROB.js +0 -2
  237. package/dist/cli-bundle/chunks/chunk-5TGFB34A.js +0 -2
  238. package/dist/cli-bundle/chunks/chunk-BHH65KLL.js +0 -2
  239. package/dist/cli-bundle/chunks/chunk-C7M54YV6.js +0 -122
  240. package/dist/cli-bundle/chunks/chunk-DMWL3K4A.js +0 -20
  241. package/dist/cli-bundle/chunks/chunk-DVN7CD5B.js +0 -2
  242. package/dist/cli-bundle/chunks/chunk-DZ7CWUVM.js +0 -8
  243. package/dist/cli-bundle/chunks/chunk-FRCNYOTG.js +0 -9
  244. package/dist/cli-bundle/chunks/chunk-HXECILIE.js +0 -31
  245. package/dist/cli-bundle/chunks/chunk-IDFRGH4X.js +0 -3
  246. package/dist/cli-bundle/chunks/chunk-JSTBYDLL.js +0 -3
  247. package/dist/cli-bundle/chunks/chunk-MELSYAFE.js +0 -124
  248. package/dist/cli-bundle/chunks/chunk-O4ZLEN4T.js +0 -3
  249. package/dist/cli-bundle/chunks/chunk-OTM6PXZQ.js +0 -8
  250. package/dist/cli-bundle/chunks/chunk-PC5DGK3C.js +0 -6
  251. package/dist/cli-bundle/chunks/chunk-PF3V443A.js +0 -2
  252. package/dist/cli-bundle/chunks/chunk-U2HVJVA5.js +0 -2
  253. package/dist/cli-bundle/chunks/chunk-VERRDW3Q.js +0 -2
  254. package/dist/cli-bundle/chunks/item-revision-VGIHIWZM.js +0 -2
  255. package/dist/cli-bundle/chunks/item-transaction-6OB6BGTD.js +0 -2
  256. package/dist/cli-bundle/chunks/mutation-admission-LL6SGQYU.js +0 -2
  257. package/dist/cli-bundle/chunks/register-operations-6RQF6IAE.js +0 -2
  258. package/dist/cli-bundle/chunks/register-setup-XGPOFFD3.js +0 -2
  259. package/dist/cli-bundle/chunks/stage-ZS7WNUD4.js +0 -2
  260. package/dist/cli-bundle/focused-chunks/chunk-2A4JCFMI.js +0 -2
  261. package/dist/cli-bundle/focused-chunks/chunk-2T6MQ7NP.js +0 -3
  262. package/dist/cli-bundle/focused-chunks/chunk-32QYILXW.js +0 -82
  263. package/dist/cli-bundle/focused-chunks/chunk-4WOF3Q6R.js +0 -2
  264. package/dist/cli-bundle/focused-chunks/chunk-5IQPFV4Y.js +0 -2
  265. package/dist/cli-bundle/focused-chunks/chunk-6C7NBJ7A.js +0 -26
  266. package/dist/cli-bundle/focused-chunks/chunk-7KNF6RCV.js +0 -12
  267. package/dist/cli-bundle/focused-chunks/chunk-FNLOLNPQ.js +0 -2
  268. package/dist/cli-bundle/focused-chunks/chunk-G6ERMFJ5.js +0 -3
  269. package/dist/cli-bundle/focused-chunks/chunk-HRLGC3P7.js +0 -28
  270. package/dist/cli-bundle/focused-chunks/chunk-I7A5VP5E.js +0 -65
  271. package/dist/cli-bundle/focused-chunks/chunk-JHC3X43E.js +0 -2
  272. package/dist/cli-bundle/focused-chunks/chunk-MKYNDWT3.js +0 -91
  273. package/dist/cli-bundle/focused-chunks/chunk-RDTHL44U.js +0 -2
  274. package/dist/cli-bundle/focused-chunks/chunk-UCCLV5GJ.js +0 -8
  275. package/dist/cli-bundle/focused-chunks/chunk-W3RWCLEU.js +0 -2
  276. package/dist/cli-bundle/focused-chunks/chunk-W57DSFSU.js +0 -44
  277. package/dist/cli-bundle/focused-chunks/chunk-YNYO7PMT.js +0 -26
  278. package/dist/cli-bundle/focused-chunks/item-revision-7J7WSCPC.js +0 -2
  279. package/dist/cli-bundle/focused-chunks/item-transaction-F5YMCPRB.js +0 -2
  280. package/dist/cli-bundle/focused-chunks/mutation-admission-2NRQEAOG.js +0 -2
  281. package/dist/cli-bundle/focused-chunks/stage-2KVCKOGC.js +0 -2
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="65a4dbbe-c9a7-5092-a325-3ba73c0fc026")}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{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]}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}),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}:{};return runCommandHandler(commands,{command,args:options.args?[...options.args]:[],options:registrations===void 0?handlerOptions:normalizeDirectExtensionCommandOptions(handlerOptions,collectExtensionFlagDefinitionsForCommand(registrations,command),command),global:global2,pm_root:pmRoot,...sdk===void 0?{}:{sdk}})}async function runRegisteredMutationGuardForTest(hooks,options){if((hooks.beforeMutation?.length??0)===0)throw new Error("Expected a registered before_mutation hook to invoke");await runBeforeMutationHooks(hooks,options.context)}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]="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"}:
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(`
package/dist/types.d.ts CHANGED
@@ -601,6 +601,12 @@ fail_on_skipped_triggered?:boolean;
601
601
  measurements?:TestRunMeasurement[];
602
602
  /** Commands and effective tracker contexts bound to this recorded run. */
603
603
  executions?:ItemTestRunExecution[];}
604
+ /** One strict-required create field recorded as not known yet (GH-1713). */
605
+ export interface ItemDeferredField{
606
+ /** Canonical metadata key: deadline, assignee, acceptance_criteria or estimated_minutes. */
607
+ field:string;
608
+ /** Why the value is not known yet, for example the external system it was imported from. */
609
+ reason:string;}
604
610
  /** Documents the item metadata payload exchanged by command, SDK, and package integrations. */
605
611
  export interface ItemMetadata{
606
612
  /** Stable identifier used to reference this record across commands and storage. */
@@ -649,6 +655,8 @@ author?:string;
649
655
  estimated_minutes?:number;
650
656
  /** Value that configures or reports acceptance criteria for this contract. */
651
657
  acceptance_criteria?:string;
658
+ /** Strict-required create fields recorded as not known yet, each with its reason (GH-1713). Close validation refuses the item while any listed field lacks a value. */
659
+ deferred_fields?:ItemDeferredField[];
652
660
  /** Value that configures or reports design for this contract. */
653
661
  design?:string;
654
662
  /** Value that configures or reports external ref for this contract. */
package/dist/types.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2b5b4209-7d42-5a4f-b2a0-50c60a5d1bfe")}catch{}})();const BUILTIN_ITEM_TYPE_VALUES=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],ITEM_TYPE_VALUES=BUILTIN_ITEM_TYPE_VALUES,STATUS_VALUES=["draft","open","in_progress","blocked","closed","canceled"],RUNTIME_STATUS_ROLE_VALUES=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],RUNTIME_FIELD_TYPE_VALUES=["string","number","boolean","string_array","array","object"],RUNTIME_FIELD_COMMAND_VALUES=["create","update","update_many","list","search","calendar","context"],RUNTIME_UNKNOWN_FIELD_POLICY_VALUES=["allow","warn","reject"],DEPENDENCY_KIND_VALUES=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],SCOPE_VALUES=["project","global"],RISK_VALUES=["low","medium","high","critical"],ISSUE_SEVERITY_VALUES=["low","medium","high","critical"],CONFIDENCE_TEXT_VALUES=["low","medium","high"],ITEM_FORMAT_VALUES=["toon","json_markdown"],SPRINT_RELEASE_FORMAT_POLICY_VALUES=["warn","strict_error"],PARENT_REFERENCE_POLICY_VALUES=["warn","strict_error"],VALIDATE_METADATA_PROFILE_VALUES=["core","strict","custom"],GOVERNANCE_PRESET_VALUES=["minimal","default","strict","custom"],GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES=["none","warn","strict"],GOVERNANCE_CREATE_MODE_DEFAULT_VALUES=["progressive","strict"],GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES=["off","warn","strict"],GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES=["off","warn","strict"],GOVERNANCE_START_BLOCKER_ENFORCEMENT_VALUES=["off","warn","strict"],GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES=["off","advisory","strict"],VALIDATE_METADATA_REQUIRED_FIELD_VALUES=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"],RECURRENCE_FREQUENCY_VALUES=["daily","weekly","monthly","yearly"],RECURRENCE_WEEKDAY_VALUES=["mon","tue","wed","thu","fri","sat","sun"];function weekdayOrderIndex(value){return RECURRENCE_WEEKDAY_VALUES.indexOf(value)}const PLAN_MODE_VALUES=["draft","research","review","approved","executing","paused","completed","superseded"],PLAN_STEP_STATUS_VALUES=["pending","in_progress","completed","blocked","skipped","superseded"],PLAN_HARNESS_VALUES=["codex","claude-code","cursor","generic"],PLAN_STEP_LINK_KIND_VALUES=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],CONTEXT_DEPTH_VALUES=["brief","standard","deep","full"],CONTEXT_SECTION_VALUES=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];export{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES,DEPENDENCY_KIND_VALUES,GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES,GOVERNANCE_CREATE_MODE_DEFAULT_VALUES,GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES,GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES,GOVERNANCE_PRESET_VALUES,GOVERNANCE_START_BLOCKER_ENFORCEMENT_VALUES,GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES,ISSUE_SEVERITY_VALUES,ITEM_FORMAT_VALUES,ITEM_TYPE_VALUES,PARENT_REFERENCE_POLICY_VALUES,PLAN_HARNESS_VALUES,PLAN_MODE_VALUES,PLAN_STEP_LINK_KIND_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,RISK_VALUES,RUNTIME_FIELD_COMMAND_VALUES,RUNTIME_FIELD_TYPE_VALUES,RUNTIME_STATUS_ROLE_VALUES,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES,SCOPE_VALUES,SPRINT_RELEASE_FORMAT_POLICY_VALUES,STATUS_VALUES,VALIDATE_METADATA_PROFILE_VALUES,VALIDATE_METADATA_REQUIRED_FIELD_VALUES,weekdayOrderIndex};
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]="467196ad-a2fc-5048-bc06-a1d027fb0ae2")}catch{}})();const BUILTIN_ITEM_TYPE_VALUES=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],ITEM_TYPE_VALUES=BUILTIN_ITEM_TYPE_VALUES,STATUS_VALUES=["draft","open","in_progress","blocked","closed","canceled"],RUNTIME_STATUS_ROLE_VALUES=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],RUNTIME_FIELD_TYPE_VALUES=["string","number","boolean","string_array","array","object"],RUNTIME_FIELD_COMMAND_VALUES=["create","update","update_many","list","search","calendar","context"],RUNTIME_UNKNOWN_FIELD_POLICY_VALUES=["allow","warn","reject"],DEPENDENCY_KIND_VALUES=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],SCOPE_VALUES=["project","global"],RISK_VALUES=["low","medium","high","critical"],ISSUE_SEVERITY_VALUES=["low","medium","high","critical"],CONFIDENCE_TEXT_VALUES=["low","medium","high"],ITEM_FORMAT_VALUES=["toon","json_markdown"],SPRINT_RELEASE_FORMAT_POLICY_VALUES=["warn","strict_error"],PARENT_REFERENCE_POLICY_VALUES=["warn","strict_error"],VALIDATE_METADATA_PROFILE_VALUES=["core","strict","custom"],GOVERNANCE_PRESET_VALUES=["minimal","default","strict","custom"],GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES=["none","warn","strict"],GOVERNANCE_CREATE_MODE_DEFAULT_VALUES=["progressive","strict"],GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES=["off","warn","strict"],GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES=["off","warn","strict"],GOVERNANCE_START_BLOCKER_ENFORCEMENT_VALUES=["off","warn","strict"],GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES=["off","advisory","strict"],VALIDATE_METADATA_REQUIRED_FIELD_VALUES=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"],RECURRENCE_FREQUENCY_VALUES=["daily","weekly","monthly","yearly"],RECURRENCE_WEEKDAY_VALUES=["mon","tue","wed","thu","fri","sat","sun"];function weekdayOrderIndex(value){return RECURRENCE_WEEKDAY_VALUES.indexOf(value)}const PLAN_MODE_VALUES=["draft","research","review","approved","executing","paused","completed","superseded"],PLAN_STEP_STATUS_VALUES=["pending","in_progress","completed","blocked","skipped","superseded"],PLAN_HARNESS_VALUES=["codex","claude-code","cursor","generic"],PLAN_STEP_LINK_KIND_VALUES=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],CONTEXT_DEPTH_VALUES=["brief","standard","deep","full"],CONTEXT_SECTION_VALUES=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];export{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES,DEPENDENCY_KIND_VALUES,GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES,GOVERNANCE_CREATE_MODE_DEFAULT_VALUES,GOVERNANCE_DUPLICATE_DETECTION_MODE_VALUES,GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES,GOVERNANCE_PRESET_VALUES,GOVERNANCE_START_BLOCKER_ENFORCEMENT_VALUES,GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES,ISSUE_SEVERITY_VALUES,ITEM_FORMAT_VALUES,ITEM_TYPE_VALUES,PARENT_REFERENCE_POLICY_VALUES,PLAN_HARNESS_VALUES,PLAN_MODE_VALUES,PLAN_STEP_LINK_KIND_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,RISK_VALUES,RUNTIME_FIELD_COMMAND_VALUES,RUNTIME_FIELD_TYPE_VALUES,RUNTIME_STATUS_ROLE_VALUES,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES,SCOPE_VALUES,SPRINT_RELEASE_FORMAT_POLICY_VALUES,STATUS_VALUES,VALIDATE_METADATA_PROFILE_VALUES,VALIDATE_METADATA_REQUIRED_FIELD_VALUES,weekdayOrderIndex};
2
2
  //# sourceMappingURL=types.js.map
@@ -194,6 +194,8 @@ Use the canonical [guide topic map](README.md#guide-topic-map) when local in-CLI
194
194
  - Claim before heavy edits.
195
195
  - `pm claim <id>` is an atomic test-and-set. A non-terminal item already held by a different principal refuses with `already_claimed_by` and names the holder in typed fields (`claimed_by`, `claim_source`, `claimed_at`); the same principal re-claiming is a no-op.
196
196
  - Pass `--if-available` to treat a held item as a skip (`skipped: true`, exit 0) instead of a failure, for example when several agents pull from one queue. The terminal check runs first, so a terminal item still refuses without `--force` even when `--if-available` is set.
197
+ - The refusal also carries `claim_activity`: the holder's `claim_age_hours`, `last_activity_at` (the newer of the item's `updated_at` and its latest substantive history entry: a restore writes an older `updated_at` and counts, a compaction baseline counts with the newest work it pruned, and maintenance such as the `history-compact` audit entry does not), `idle_hours`, and the `stale_policy` it was judged against (`mutation_guard.stale_in_progress_hours`, default 72, with `stale` and `eligible_at`). `pm next` reports `claimed_at`, `idle_hours` and `stale` on each `held_by_others` row.
198
+ - Pass `--takeover-stale` to take over a claim whose holder has recorded nothing for at least that threshold. An active or too-recent claim refuses with `stale_claim_takeover_refused`, writes nothing, and names when it becomes eligible. The decision is made under the item lock, which serializes it with the holder's mutations: a renewal recorded before the takeover takes the lock is seen and refuses the takeover, and one that arrives after it lands on the new holder's claim. A history stream that exists but cannot be read is never judged stale: the refusal is still `stale_claim_takeover_refused`, with `claim_activity.history_unreadable: true` as its evidence. The takeover anchors on the holder's own claim record, so it also refuses when that record is missing or was folded into a compaction baseline, or when a salvage, repair, redaction, merge reconcile or workspace restore after the claim discarded or rewrote records (`claim_activity.unproven_activity`). The holder can release such an item, or a coordinated `--force` can take it. A permitted takeover records `previous_holder`, `new_holder`, `last_activity_at`, `idle_hours`, `threshold_hours` and the policy in the claim history entry's `context.stale_claim_takeover`, and returns the same receipt as `takeover`. Combined with `--if-available`, an active claim is skipped instead of refused. It cannot be combined with `--force` or `--next`.
197
199
  - Use `--force` only for a coordinated takeover of another owner's claim; it is also required to claim terminal items, and to override stale locks when the `governance.force_required_for_stale_lock` policy is enabled (the `minimal` and custom governance presets can disable it). Never force a takeover without explicit approval.
198
200
  - Release when pausing, handing off, or after close.
199
201
 
package/docs/COMMANDS.md CHANGED
@@ -171,6 +171,28 @@ pm next --parent pm-epic01 # scope readiness to one epic's subtree
171
171
  pm next --ready-only --limit 3 --json # tightest agent-loop projection
172
172
  ```
173
173
 
174
+ Each `held_by_others` row reports the holder's `claimed_at`, `idle_hours` and
175
+ `stale` (idle at least `mutation_guard.stale_in_progress_hours`), reading one
176
+ history stream per returned row only; the exact `last_activity_at` is in a
177
+ refused claim's `claim_activity`. A stale row can be taken with
178
+ `pm claim <id> --takeover-stale`; an active one is refused with
179
+ `stale_claim_takeover_refused` and nothing is written. Unattended in-progress
180
+ work is swept with the existing list grammar:
181
+
182
+ ```bash
183
+ pm list --status in_progress --assignee-filter unassigned # unowned
184
+ pm list --status in_progress --updated-before -72h # idle, owned or not
185
+ pm list --status in_progress --assignee-filter unassigned --updated-before -72h # stale
186
+ ```
187
+
188
+ `pm health` prints these sweeps (with the configured status id and threshold)
189
+ as the remedies of its `in_progress_unowned`, `in_progress_idle` and
190
+ `stale_in_progress_items` advisories, and `pm context` counts
191
+ `in_progress_unowned` and `in_progress_idle` next to `in_progress`. The sweeps
192
+ select by `updated_at`, so they are candidate lists: an item restored within
193
+ the window keeps an older `updated_at` but recent history, and only
194
+ `--takeover-stale` applies the full activity clock.
195
+
174
196
  `pm next` has two budgets with different scopes. `--token-budget <n>` bounds
175
197
  only the selection (`recommended` plus `ready`) and reports it under
176
198
  `truncation.ready_budget`; `filters.token_budget` echoes that request and is
@@ -576,6 +598,15 @@ pm create \
576
598
  --message "Create restore replay issue"
577
599
  ```
578
600
 
601
+ When a strict-required value is genuinely not known yet, as with a record mirrored from another tracker, defer it instead of inventing one ([pm-gh1713](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-gh1713.toon)). `--defer <field>` (repeatable, comma lists accepted) names `deadline`, `assignee`, `acceptance-criteria`/`ac` or `estimate`, and `--defer-reason` is required with it:
602
+
603
+ ```bash
604
+ pm create "Imported issue" --type Issue --description "Mirrored from GitHub" --create-mode strict \
605
+ --defer deadline --defer assignee,ac --defer estimate --defer-reason "Imported from GitHub issue 42" ...
606
+ ```
607
+
608
+ The deferral satisfies strict create and is stored as typed `deferred_fields` metadata (item format 4), so the create history entry records it. A later write that supplies a deferred value (`pm update <id> --deadline 2026-12-31`, or a claim for `assignee`) resolves that entry in the same history entry. `pm validate --check-metadata` lists the remaining deferrals as curation work (`validate_metadata_deferred_fields:<items>`), and `pm health` reports them informationally under the integrity check's `curation` details. Close validation never lets a deferral finish work: `--validate-close strict` (the strict preset default) refuses with `close_validation_deferred_fields` and a runnable `pm update` recovery, and `warn` closes with a `close_validation_deferred_fields:<id>:<fields>` warning. Deferring a field you also set or unset in the same create is refused as `create_deferral_conflict`, and a deferral overrides a template's default for that field. SDK and MCP callers pass `defer: ["deadline", ...]` and `deferReason`.
609
+
579
610
  For long markdown bodies (multi-paragraph specs with code blocks or tables), load the body from a file with `--body-file <path>` on both `pm create` and `pm update` instead of escaping a huge inline `--body` string or issuing a second `pm append`:
580
611
 
581
612
  ```bash
@@ -104,7 +104,7 @@ If the existing `settings.json` is valid JSON but fails schema validation (for e
104
104
  | `author_default` | configured mutation author before automatic harness detection |
105
105
  | `mutation_guard.require_attributed_author` | reject mutations whose effective author remains `unknown` (default `false`) |
106
106
  | `mutation_guard.secret_guard` | credential-shaped content policy: `off`, `advise`, or `block` (default `advise`) |
107
- | `mutation_guard.stale_in_progress_hours` | age threshold for unclaimed in-progress work surfaced by `pm health` (integer >= 1, default `72`) |
107
+ | `mutation_guard.stale_in_progress_hours` | inactivity threshold for stale work: `pm health` advisories, `pm context` idle counts and `pm claim --takeover-stale` (integer >= 1, default `72`) |
108
108
  | `item_format` | item storage format (`toon` writes; legacy markdown is read/migrate only) |
109
109
  | `output.default_format` | default renderer, usually `toon` |
110
110
  | `locks.ttl_seconds` | stale lock threshold |
@@ -294,7 +294,7 @@ When enabled, these environment variables tune runtime behaviour. All boolean kn
294
294
  |---|---|---|
295
295
  | `PM_TELEMETRY_DISABLED` | boolean | Hard-disable all telemetry for this process, ignoring settings. |
296
296
  | `DO_NOT_TRACK` | boolean | Hard-disable event capture, identity creation, flush workers, endpoint probes, and Sentry, regardless of persisted preferences. |
297
- | `PM_TELEMETRY_SEND_TEST_EVENTS` | boolean | Explicitly allow inferred test events. Hard opt-outs still take precedence. |
297
+ | `PM_TELEMETRY_SEND_TEST_EVENTS` | boolean | Explicitly allow inferred test events, labelled `test`. Hard opt-outs still take precedence. |
298
298
  | `PM_TELEMETRY_READ_SAMPLE_RATE` | number greater than `0` and at most `1` | Override automatic successful-read sampling; `1`, empty, or invalid values retain every invocation. Omit for automatic frequency bounding. |
299
299
  | `PM_NO_TELEMETRY` | boolean | Alias for `PM_TELEMETRY_DISABLED` (honoured by the same checks). |
300
300
  | `PM_TELEMETRY_OTEL_DISABLED` | boolean | Disable only OTLP trace-span export; the event queue still flushes. |
@@ -351,17 +351,30 @@ Interaction rules:
351
351
 
352
352
  Test environments inferred from `VITEST`, `VITEST_WORKER_ID`, `NODE_TEST_CONTEXT`
353
353
  (native `node --test` children), or `NODE_ENV=test` suppress telemetry and Sentry
354
- before identity creation. A valid explicit `PM_TELEMETRY_SOURCE_CONTEXT`,
355
- including `test`, or `PM_TELEMETRY_SEND_TEST_EVENTS=1` permits intentional test
356
- delivery, so a test that only wants the label must also set
357
- `PM_TELEMETRY_DISABLED=1`. Point such tests at a local collector: set
354
+ before identity creation. `bun test` exports no runner-specific variable (there is
355
+ no `BUN_TEST`). It sets `NODE_ENV=test` unless `NODE_ENV` is already set, so Bun is
356
+ covered by the `NODE_ENV` signal. Only an explicit test opt-in permits intentional test
357
+ delivery: `PM_TELEMETRY_SOURCE_CONTEXT=test` or `PM_TELEMETRY_SEND_TEST_EVENTS=1`.
358
+ Either way the events are labelled `test`. A test that only wants the label must
359
+ also set `PM_TELEMETRY_DISABLED=1`.
360
+
361
+ Any other source context is ignored inside a test runner. That includes an
362
+ `automation`, `user` or `dogfood` value a harness or release script exported to
363
+ attribute its own tracker writes. The context labels whoever exported it, and
364
+ does not re-enable telemetry for the test children that inherit it (GH-1735). Point such tests at a local collector: set
358
365
  `PM_TELEMETRY_ENDPOINT` for events, `SENTRY_DSN` for errors, and
359
366
  `OTEL_EXPORTER_OTLP_*` for spans. Inferred tests use inline telemetry flushing even
360
367
  after an opt in, so CLI delivery settles before process exit and disposable-root
361
368
  cleanup. SDK telemetry completion also awaits inline delivery before returning.
362
369
  Neither setting overrides a hard opt-out. `pm telemetry status` exposes effective `enabled`, persisted
363
370
  `configured_enabled`, and `env_overrides` so an empty queue is distinguishable
364
- from disabled delivery.
371
+ from disabled delivery. `env_overrides.decided_by` names the environment input
372
+ that settled consent, or is null when settings decide. It can be a hard opt-out
373
+ (`env:DO_NOT_TRACK`, `env:PM_TELEMETRY_DISABLED`, `env:PM_NO_TELEMETRY`, or an
374
+ invalid `env:PM_TELEMETRY_ENDPOINT`), the test-runner signal that suppressed
375
+ delivery (`env:VITEST`, `env:VITEST_WORKER_ID`, `env:NODE_TEST_CONTEXT`,
376
+ `env:NODE_ENV`), or the test opt-in that allowed it
377
+ (`env:PM_TELEMETRY_SOURCE_CONTEXT`, `env:PM_TELEMETRY_SEND_TEST_EVENTS`).
365
378
 
366
379
  SDK consumers that previously used `TelemetryStatusSummary.enabled` to display the saved preference should read `configured_enabled` instead. Use `enabled` to determine whether this process permits delivery.
367
380
 
@@ -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.
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.
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.
@@ -48,7 +48,14 @@ is refused with `missing_required_argument`, and `claim <id> --next` with
48
48
  `ambiguous_option_combination`; their next steps never tell the caller to pass
49
49
  a flag that is already present. `claim <id> --start --next` (or
50
50
  `--if-available`) is refused by the explicit-start composition with
51
- `invalid_argument_value`, whose recovery names the flags to remove. `release --pause` moves work to the configured
51
+ `invalid_argument_value`, whose recovery names the flags to remove.
52
+ `claim <id> --start --takeover-stale` (and the `start-task` alias) takes over
53
+ an idle claim before starting it, under the same stale-work policy as plain
54
+ `claim --takeover-stale`. `--takeover-stale` with `--force` is refused with
55
+ `ambiguous_option_combination` on every form, as is plain
56
+ `claim --takeover-stale --next`. The start forms refuse `--next` before any
57
+ claim runs: `claim --start` with `invalid_argument_value`, and `start-task`,
58
+ which has no `--next`, with `unknown_option`. `release --pause` moves work to the configured
52
59
  open status, then releases ownership. `close --release-assignment` records the
53
60
  close and its inline evidence, then releases ownership.
54
61
 
@@ -36,7 +36,71 @@ Defaults preserve author compatibility while providing secret advice:
36
36
  |---|---|---|
37
37
  | `mutation_guard.require_attributed_author` | `false` | When enabled, reject an effective author of `unknown`. |
38
38
  | `mutation_guard.secret_guard` | `advise` | `off`, stderr/structured `advise`, or pre-write `block`. |
39
- | `mutation_guard.stale_in_progress_hours` | `72` | Age threshold for unclaimed active work in `pm health`. |
39
+ | `mutation_guard.stale_in_progress_hours` | `72` | Inactivity threshold for stale work: `pm health` advisories, `pm context` idle counts, and `pm claim --takeover-stale`. |
40
+
41
+ One activity clock serves every stale-work consumer: the newer of an item's
42
+ `updated_at` and its latest substantive history entry. Ordinary mutations
43
+ advance both; `pm restore` writes the historical document, with its older
44
+ `updated_at`, and appends a new entry, so the stream counts too. Maintenance
45
+ entries (`history-compact`, `history-repair`, `history-redact`) preserve the
46
+ record without working on the item and do not count. A compaction baseline
47
+ stands for its pruned prefix and records that prefix's newest substantive
48
+ time as `context.history_compaction.last_activity_at`, so repeated
49
+ compaction never renews an abandoned claim. A baseline written before that
50
+ field existed carries only its own timestamp, the last pruned entry's time,
51
+ which does not bound the pruned work because history keeps caller-supplied
52
+ timestamps without an ordering check. Advisory reads approximate its activity
53
+ with that timestamp.
54
+
55
+ A takeover trusts no summary or rewrite. It anchors on the holder's own claim
56
+ record: the newest original entry that set the current assignee, or a claim
57
+ that moved only `claim_principal` (another session of the same principal took
58
+ the item). Records
59
+ before it cannot be the holder's work, so a compacted, salvaged or legacy
60
+ prefix never matters. The takeover refuses (`claim_activity.unproven_activity`)
61
+ in these cases:
62
+
63
+ | Reason | Cause |
64
+ |---|---|
65
+ | `claim_record_unavailable` | No original record sets the holder: the history is silent, missing, or folded the claim into a compaction baseline. |
66
+ | `discarded_history_tail` | A `history-repair --salvage-tail` after the claim discarded a record whose time is unknown. |
67
+ | `rewritten_history` | A `history-repair`, `history-redact` or merge reconcile after the claim rewrote records, or `reanchor_evidence` on the claim or a later record shows a changed patch (a merge rebase leaves no audit entry). |
68
+ | `workspace_restored` | A workspace snapshot restore at or after the claim may have replaced the holder's later work. Also when a salvage, repair, redaction or merge reconcile of the workspace stream is dated at or after the claim, when a compacted workspace stream's baseline cannot bound its pruned records before the claim, or when the workspace stream cannot be read to rule a restore out. |
69
+
70
+ The holder can release such an item; a new claim starts a provable record.
71
+ Restore precedence uses wall-clock time and assumes the restoring host's clock
72
+ does not run behind the holder's. Ordering restores by a durable generation
73
+ instead is tracked as pm-8su89a. A restore that activates while a takeover is
74
+ between its reads and its commit is not yet fenced; that gap affects every
75
+ item writer and is tracked as pm-vgk0nj. Rewrite detection also trusts the
76
+ history merge driver to keep provenance: its dedup identity omits `context`,
77
+ `event_class` and `reanchor_evidence`, so two records that match on everything
78
+ else collapse into one. That is tracked as pm-0574of. A
79
+ stream any of whose records lacks a parseable timestamp, or holds a baseline
80
+ with a malformed receipt, is unreadable for a takeover, and `history-compact`
81
+ refuses to prune such a record (it would launder the damage into a judgeable
82
+ stream). A takeover refuses when
83
+ the stream exists but cannot be read (`claim_activity.history_unreadable`),
84
+ because recent work may hide behind it. A threshold too large for the Date range reports
85
+ `eligible_at: null` rather than failing. `pm health` reports three advisories
86
+ in the storage check, none of which fails the verdict:
87
+
88
+ | Warning | Population | Remedy printed by `pm health` |
89
+ |---|---|---|
90
+ | `in_progress_unowned:<n>` | in-progress items with no assignee (so no live claim) | `pm list --status <in_progress> --assignee-filter unassigned` |
91
+ | `in_progress_idle:<n>` | in-progress items idle past the threshold, owned or not | `pm list --status <in_progress> --updated-before -<hours>h` |
92
+ | `stale_in_progress_items:<n>` | both: unowned and idle | `pm list --status <in_progress> --assignee-filter unassigned --updated-before -<hours>h` |
93
+
94
+ The storage check's `details.in_progress_work` lists up to 25 ids per group
95
+ with each group's sweep, plus the per-item recoveries `pm claim <id>` (unowned
96
+ work), `pm claim <id> --takeover-stale` (another holder's idle claim) and
97
+ `pm update <id> --status <open>`. Sweeps and recoveries carry `--pm-path` when
98
+ the diagnosed tracker was selected explicitly or through `PM_PATH`. A sweep is a candidate list by metadata
99
+ time: it can include an item whose history is newer than its `updated_at`
100
+ (for example after a restore), which the advisory does not count;
101
+ `pm claim <id> --takeover-stale` re-judges each one under the item lock. `pm context` reports `in_progress_unowned`
102
+ and `in_progress_idle` next to `in_progress` in its summary when they are
103
+ non-zero, so unattended work is not read as active work.
40
104
 
41
105
  A blocking secret policy may be bypassed only by an explicit `--force` on a
42
106
  force-capable mutation. The warning records that an override occurred while
@@ -49,7 +113,9 @@ Package hosts can apply the exact runtime policy before dispatch:
49
113
  ```ts
50
114
  import {
51
115
  evaluateMutationGuard,
116
+ inspectInProgressWork,
52
117
  inspectStaleInProgressItems,
118
+ resolveRuntimeStatusRegistry,
53
119
  scanMutationSecrets,
54
120
  } from "@unbrained/pm-cli/sdk";
55
121
 
@@ -65,8 +131,20 @@ const stale = inspectStaleInProgressItems(items, {
65
131
  projectSettings.schema.workflow.in_progress_status ?? "in_progress",
66
132
  threshold_hours: projectSettings.mutation_guard.stale_in_progress_hours,
67
133
  });
134
+ // Unowned, idle and stale groups from one pass; scanInProgressWork(pmRoot, ...)
135
+ // also reads history, but only for items whose metadata already looks idle.
136
+ // The registry resolves stored status aliases, as the in-progress counters do.
137
+ const work = inspectInProgressWork(items, {
138
+ status_registry: resolveRuntimeStatusRegistry(projectSettings.schema),
139
+ threshold_hours: projectSettings.mutation_guard.stale_in_progress_hours,
140
+ });
68
141
  ```
69
142
 
143
+ `resolveItemOwnershipActivity(pmRoot, id, holder, { updated_at, threshold_hours })`
144
+ returns the same claim evidence a refused `pm claim` reports, and
145
+ `buildInProgressSweepCommands(status, hours)` returns the exact list sweeps
146
+ `pm health` prints.
147
+
70
148
  `evaluateMutationGuard` returns stable warning codes, redacted findings, and
71
149
  whether a blocking policy was explicitly overridden. `scanMutationSecrets` is
72
150
  available separately for package-specific preflight UIs. Cyclic inputs are