@unbrained/pm-cli 2026.10.15 → 2026.10.18

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 (275) hide show
  1. package/.agents/skills/pm-developer/references/COMMAND_PLAYBOOK.md +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/AGENTS.md +1 -0
  4. package/CHANGELOG.md +45 -0
  5. package/dist/cli/extension-command-options.d.ts +3 -1
  6. package/dist/cli/extension-command-options.js +1 -1
  7. package/dist/cli/help-content.js +2 -2
  8. package/dist/cli/register-list-query.js +2 -2
  9. package/dist/cli/register-mutation.js +2 -2
  10. package/dist/cli/register-operations.js +1 -1
  11. package/dist/cli/register-structured-mutation.d.ts +0 -5
  12. package/dist/cli/register-structured-mutation.js +1 -1
  13. package/dist/cli/runtime/invocation-options.js +1 -1
  14. package/dist/cli-bundle/bundle-manifest.json +1 -1
  15. package/dist/cli-bundle/chunks/{chunk-7VHINXZP.js → chunk-4GA4MUTE.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-RJ5N44WY.js → chunk-4V6ONLI6.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-LNKLQYBG.js → chunk-6VZKYJW7.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-7PATQWTH.js +20 -0
  19. package/dist/cli-bundle/chunks/chunk-7WIEAGDS.js +2 -0
  20. package/dist/cli-bundle/chunks/{chunk-52EZH2QQ.js → chunk-AETP4JEM.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-WBBW3WQX.js → chunk-FIJOSX2C.js} +28 -28
  22. package/dist/cli-bundle/chunks/chunk-LUKVNL72.js +2 -0
  23. package/dist/cli-bundle/chunks/{chunk-NC3QVGDD.js → chunk-OJ77ZQN3.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-PYRREEUB.js +30 -0
  25. package/dist/cli-bundle/chunks/chunk-RHQJ6VWC.js +237 -0
  26. package/dist/cli-bundle/chunks/{chunk-N56CAQBU.js → chunk-RNABUEFB.js} +52 -52
  27. package/dist/cli-bundle/chunks/chunk-TO6CIV4C.js +2 -0
  28. package/dist/cli-bundle/chunks/{chunk-JGKTOBVB.js → chunk-ZZED447K.js} +4 -4
  29. package/dist/cli-bundle/chunks/{register-list-query-FKKFQ66D.js → register-list-query-PUCVYYBD.js} +7 -7
  30. package/dist/cli-bundle/chunks/register-mutation-GGGVBXD5.js +20 -0
  31. package/dist/cli-bundle/chunks/{register-operations-GEQ2H7PS.js → register-operations-NRZ6Q4QE.js} +2 -2
  32. package/dist/cli-bundle/chunks/{register-setup-PSJTQBBO.js → register-setup-MV3P3YSF.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-2MPQUMTF.js +2 -0
  34. package/dist/cli-bundle/focused-chunks/{chunk-H3P77KVU.js → chunk-5UKCSZWT.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-4KQFMOM7.js → chunk-A4ZHHTEX.js} +5 -5
  36. package/dist/cli-bundle/focused-chunks/{chunk-5OO54BIV.js → chunk-B4YLP5ZB.js} +3 -3
  37. package/dist/cli-bundle/focused-chunks/chunk-BFEMT5U3.js +20 -0
  38. package/dist/cli-bundle/focused-chunks/{chunk-THYQR3ON.js → chunk-FW7CSSKL.js} +61 -61
  39. package/dist/cli-bundle/focused-chunks/{chunk-3RNUMVK4.js → chunk-HYPRPSYD.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-FQKPOZKS.js → chunk-IRVL4UXR.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-Q4VNCTR2.js → chunk-L55KQ2KT.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-52I2SNKJ.js → chunk-MASIOFPG.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-RJ3EIHDU.js +26 -0
  44. package/dist/cli-bundle/focused-chunks/chunk-SEL4Z2OO.js +167 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-TYLG5VEB.js → chunk-TB7F4FCR.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-KIIFVULU.js → chunk-TZUIBG3P.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-N6FUKTZS.js → chunk-Z7YIFCNE.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-5KRACGBK.js → chunk-ZDBS2DCT.js} +3 -3
  49. package/dist/cli-bundle/main.js +27 -27
  50. package/dist/cli-bundle/sdk-authoring.js +1 -1
  51. package/dist/cli-bundle/sdk-contracts.js +2 -2
  52. package/dist/cli-bundle/sdk-core.js +23 -23
  53. package/dist/cli-bundle/sdk-governance.js +1 -1
  54. package/dist/cli-bundle/sdk-graph.js +1 -1
  55. package/dist/cli-bundle/sdk-merge.js +55 -54
  56. package/dist/cli-bundle/sdk-query.js +1 -1
  57. package/dist/cli-bundle/sdk-runtime.js +1 -1
  58. package/dist/cli-bundle/sdk-testing.js +1 -1
  59. package/dist/cli-bundle/sdk.js +7 -7
  60. package/dist/core/extensions/extension-types.d.ts +15 -0
  61. package/dist/core/extensions/extension-types.js +1 -1
  62. package/dist/core/extensions/flag-value-types.d.ts +16 -0
  63. package/dist/core/extensions/flag-value-types.js +1 -1
  64. package/dist/core/extensions/registration-contracts.js +1 -1
  65. package/dist/core/history/event-index.d.ts +8 -1
  66. package/dist/core/history/event-index.js +19 -18
  67. package/dist/core/item/item-format.js +3 -3
  68. package/dist/core/lock/lock.d.ts +8 -1
  69. package/dist/core/lock/lock.js +3 -3
  70. package/dist/core/output/mutation-projection.d.ts +0 -21
  71. package/dist/core/output/mutation-projection.js +1 -1
  72. package/dist/core/output/output.js +2 -2
  73. package/dist/core/schema/type-workflows.d.ts +1 -1
  74. package/dist/core/schema/type-workflows.js +1 -1
  75. package/dist/core/shared/text-normalization.d.ts +2 -0
  76. package/dist/core/shared/text-normalization.js +1 -1
  77. package/dist/core/store/item-mutation-precondition.d.ts +11 -0
  78. package/dist/core/store/item-mutation-precondition.js +2 -0
  79. package/dist/core/store/item-store.js +1 -1
  80. package/dist/core/store/paths.js +1 -1
  81. package/dist/core/telemetry/policy.d.ts +2 -0
  82. package/dist/core/telemetry/policy.js +1 -1
  83. package/dist/core/telemetry/runtime.d.ts +5 -3
  84. package/dist/core/telemetry/runtime.js +3 -3
  85. package/dist/mcp/server.js +1 -1
  86. package/dist/mcp/tool-definitions.js +1 -1
  87. package/dist/sdk/cli-contracts/agent-output-contracts.js +1 -1
  88. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  89. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  90. package/dist/sdk/cli-contracts/registration-helpers.d.ts +1 -1
  91. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  92. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  93. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  94. package/dist/sdk/context-intent-contracts.js +1 -1
  95. package/dist/sdk/core.d.ts +2 -1
  96. package/dist/sdk/core.js +1 -1
  97. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  98. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  99. package/dist/sdk/governance/health/projection.d.ts +37 -0
  100. package/dist/sdk/governance/health/projection.js +2 -0
  101. package/dist/sdk/governance/health.d.ts +7 -18
  102. package/dist/sdk/governance/health.js +2 -2
  103. package/dist/sdk/guide-topics.js +1 -1
  104. package/dist/sdk/index.d.ts +2 -1
  105. package/dist/sdk/index.js +1 -1
  106. package/dist/sdk/item-transaction.d.ts +72 -9
  107. package/dist/sdk/item-transaction.js +1 -1
  108. package/dist/sdk/lifecycle/claim.d.ts +15 -1
  109. package/dist/sdk/lifecycle/claim.js +1 -1
  110. package/dist/sdk/lifecycle/close.d.ts +2 -8
  111. package/dist/sdk/lifecycle/close.js +1 -1
  112. package/dist/sdk/lifecycle/core-item-fields.d.ts +6 -0
  113. package/dist/sdk/lifecycle/core-item-fields.js +2 -0
  114. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  115. package/dist/sdk/lifecycle/mutation-option-validation.d.ts +2 -0
  116. package/dist/sdk/lifecycle/mutation-option-validation.js +2 -0
  117. package/dist/sdk/lifecycle/release-handoff.d.ts +12 -0
  118. package/dist/sdk/lifecycle/release-handoff.js +2 -0
  119. package/dist/sdk/lifecycle/structured-mutation-plan.d.ts +33 -0
  120. package/dist/sdk/lifecycle/structured-mutation-plan.js +2 -0
  121. package/dist/sdk/lifecycle/task-composition.d.ts +2 -2
  122. package/dist/sdk/lifecycle/task-composition.js +1 -1
  123. package/dist/sdk/lifecycle/update.d.ts +3 -11
  124. package/dist/sdk/lifecycle/update.js +1 -1
  125. package/dist/sdk/lifecycle/workflow-transition.d.ts +13 -0
  126. package/dist/sdk/lifecycle/workflow-transition.js +2 -0
  127. package/dist/sdk/lifecycle-policy.d.ts +12 -2
  128. package/dist/sdk/lifecycle-policy.js +1 -1
  129. package/dist/sdk/mutation-events.js +1 -1
  130. package/dist/sdk/public-surface.json +1 -1
  131. package/dist/sdk/query/list.d.ts +2 -0
  132. package/dist/sdk/query/list.js +1 -1
  133. package/dist/sdk/read-output-budget.js +1 -1
  134. package/dist/sdk/runtime-input.js +1 -1
  135. package/dist/sdk/runtime-primitives.d.ts +1 -1
  136. package/dist/sdk/runtime-primitives.js +1 -1
  137. package/dist/sdk/runtime.d.ts +8 -8
  138. package/dist/sdk/runtime.js +1 -1
  139. package/dist/sdk/structured-mutations.d.ts +52 -1
  140. package/dist/sdk/structured-mutations.js +1 -1
  141. package/dist/sdk/workspace-transaction.js +2 -2
  142. package/dist/types.d.ts +2 -2
  143. package/dist/types.js +1 -1
  144. package/docs/AGENT_GUIDE.md +33 -4
  145. package/docs/CLOSE_EVIDENCE_RECOVERY.md +16 -7
  146. package/docs/COMMANDS.md +111 -10
  147. package/docs/CONFIGURATION.md +22 -1
  148. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +22 -3
  149. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +5 -1
  150. package/docs/EXTENSIONS.md +1 -1
  151. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +10 -0
  152. package/docs/RELEASING.md +8 -1
  153. package/docs/SDK.md +114 -2
  154. package/docs/SDK_CONTEXT_COORDINATION.md +71 -7
  155. package/docs/SDK_STORAGE_LIFECYCLE.md +24 -2
  156. package/docs/TESTING.md +23 -0
  157. package/docs/examples/ci/github-actions-pm-extension-gate.yml +1 -1
  158. package/docs/examples/ci/gitlab-ci-pm-extension-gate.yml +1 -1
  159. package/docs/examples/ci/jenkins-pm-extension-gate.Jenkinsfile +1 -1
  160. package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
  161. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +16 -3
  162. package/marketplace.json +1 -1
  163. package/node_modules/@opentelemetry/core/package.json +2 -1
  164. package/node_modules/@opentelemetry/instrumentation/package.json +2 -1
  165. package/node_modules/@opentelemetry/resources/package.json +2 -1
  166. package/node_modules/@opentelemetry/sdk-trace/package.json +2 -1
  167. package/node_modules/@opentelemetry/sdk-trace-base/package.json +2 -1
  168. package/node_modules/@sentry/core/build/cjs/client.js +5 -4
  169. package/node_modules/@sentry/core/build/cjs/tracing/ai/gen-ai-attributes.js +0 -4
  170. package/node_modules/@sentry/core/build/cjs/tracing/ai/utils.js +33 -23
  171. package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/index.js +7 -6
  172. package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/streaming.js +3 -1
  173. package/node_modules/@sentry/core/build/cjs/tracing/google-genai/index.js +13 -14
  174. package/node_modules/@sentry/core/build/cjs/tracing/google-genai/streaming.js +6 -1
  175. package/node_modules/@sentry/core/build/cjs/tracing/langchain/utils.js +71 -21
  176. package/node_modules/@sentry/core/build/cjs/tracing/langgraph/utils.js +23 -33
  177. package/node_modules/@sentry/core/build/cjs/tracing/openai/streaming.js +6 -0
  178. package/node_modules/@sentry/core/build/cjs/tracing/openai/utils.js +11 -0
  179. package/node_modules/@sentry/core/build/cjs/tracing/workers-ai/utils.js +1 -1
  180. package/node_modules/@sentry/core/build/cjs/utils/eventUtils.js +4 -0
  181. package/node_modules/@sentry/core/build/cjs/utils/prepareEvent.js +2 -2
  182. package/node_modules/@sentry/core/build/cjs/utils/version.js +1 -1
  183. package/node_modules/@sentry/core/build/esm/client.js +6 -5
  184. package/node_modules/@sentry/core/build/esm/package.json +1 -1
  185. package/node_modules/@sentry/core/build/esm/tracing/ai/gen-ai-attributes.js +1 -3
  186. package/node_modules/@sentry/core/build/esm/tracing/ai/utils.js +34 -24
  187. package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/index.js +8 -7
  188. package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/streaming.js +3 -1
  189. package/node_modules/@sentry/core/build/esm/tracing/google-genai/index.js +15 -16
  190. package/node_modules/@sentry/core/build/esm/tracing/google-genai/streaming.js +6 -1
  191. package/node_modules/@sentry/core/build/esm/tracing/langchain/utils.js +73 -24
  192. package/node_modules/@sentry/core/build/esm/tracing/langgraph/utils.js +24 -34
  193. package/node_modules/@sentry/core/build/esm/tracing/openai/streaming.js +6 -0
  194. package/node_modules/@sentry/core/build/esm/tracing/openai/utils.js +11 -0
  195. package/node_modules/@sentry/core/build/esm/tracing/workers-ai/utils.js +2 -2
  196. package/node_modules/@sentry/core/build/esm/utils/eventUtils.js +4 -1
  197. package/node_modules/@sentry/core/build/esm/utils/prepareEvent.js +2 -2
  198. package/node_modules/@sentry/core/build/esm/utils/version.js +1 -1
  199. package/node_modules/@sentry/core/build/types/tracing/ai/utils.d.ts +3 -7
  200. package/node_modules/@sentry/core/build/types/tracing/anthropic-ai/types.d.ts +2 -2
  201. package/node_modules/@sentry/core/build/types/tracing/langchain/types.d.ts +15 -0
  202. package/node_modules/@sentry/core/build/types/tracing/langchain/utils.d.ts +1 -0
  203. package/node_modules/@sentry/core/build/types/tracing/langgraph/utils.d.ts +2 -0
  204. package/node_modules/@sentry/core/build/types/tracing/openai/types.d.ts +2 -0
  205. package/node_modules/@sentry/core/build/types/utils/eventUtils.d.ts +2 -1
  206. package/node_modules/@sentry/core/build/types-ts3.8/tracing/ai/utils.d.ts +3 -7
  207. package/node_modules/@sentry/core/build/types-ts3.8/tracing/anthropic-ai/types.d.ts +2 -2
  208. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/types.d.ts +15 -0
  209. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/utils.d.ts +1 -0
  210. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langgraph/utils.d.ts +2 -0
  211. package/node_modules/@sentry/core/build/types-ts3.8/tracing/openai/types.d.ts +2 -0
  212. package/node_modules/@sentry/core/build/types-ts3.8/utils/eventUtils.d.ts +2 -1
  213. package/node_modules/@sentry/core/package.json +1 -1
  214. package/node_modules/@sentry/node/build/esm/package.json +1 -1
  215. package/node_modules/@sentry/node/package.json +5 -5
  216. package/node_modules/@sentry/node-core/build/cjs/integrations/anr/index.js +1 -1
  217. package/node_modules/@sentry/node-core/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  218. package/node_modules/@sentry/node-core/build/esm/integrations/anr/index.js +1 -1
  219. package/node_modules/@sentry/node-core/build/esm/integrations/anr/worker-script.js +2 -2
  220. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  221. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/worker-script.js +1 -1
  222. package/node_modules/@sentry/node-core/build/esm/package.json +1 -1
  223. package/node_modules/@sentry/node-core/package.json +10 -4
  224. package/node_modules/@sentry/opentelemetry/build/esm/package.json +1 -1
  225. package/node_modules/@sentry/opentelemetry/package.json +5 -2
  226. package/node_modules/@sentry/server-utils/build/THIRD-PARTY-LICENSES.txt +55 -55
  227. package/node_modules/@sentry/server-utils/build/esm/package.json +1 -1
  228. package/node_modules/@sentry/server-utils/package.json +2 -2
  229. package/node_modules/@toon-format/toon/README.md +10 -41
  230. package/node_modules/@toon-format/toon/dist/index.d.mts +12 -36
  231. package/node_modules/@toon-format/toon/dist/index.mjs +134 -202
  232. package/node_modules/@toon-format/toon/package.json +2 -2
  233. package/node_modules/debug/package.json +3 -0
  234. package/node_modules/fdir/package.json +3 -0
  235. package/node_modules/has-flag/index.d.ts +39 -0
  236. package/node_modules/has-flag/index.js +8 -0
  237. package/node_modules/has-flag/license +9 -0
  238. package/node_modules/has-flag/package.json +46 -0
  239. package/node_modules/has-flag/readme.md +89 -0
  240. package/node_modules/supports-color/browser.js +5 -0
  241. package/node_modules/supports-color/index.js +135 -0
  242. package/node_modules/supports-color/license +9 -0
  243. package/node_modules/supports-color/package.json +53 -0
  244. package/node_modules/supports-color/readme.md +76 -0
  245. package/package.json +5 -4
  246. package/packages/pm-beads/package.json +1 -1
  247. package/packages/pm-calendar/package.json +1 -1
  248. package/packages/pm-command-kit/package.json +1 -1
  249. package/packages/pm-digital-twin/package.json +1 -1
  250. package/packages/pm-governance-audit/package.json +1 -1
  251. package/packages/pm-guide-shell/package.json +1 -1
  252. package/packages/pm-kanban/package.json +1 -1
  253. package/packages/pm-lifecycle-hooks/package.json +1 -1
  254. package/packages/pm-linked-test-adapters/package.json +1 -1
  255. package/packages/pm-search-advanced/package.json +1 -1
  256. package/packages/pm-templates/package.json +1 -1
  257. package/packages/pm-todos/package.json +1 -1
  258. package/packages/pm-vcs/package.json +1 -1
  259. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  260. package/plugins/pm-claude/package.json +1 -1
  261. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  262. package/plugins/pm-codex/package.json +1 -1
  263. package/plugins/pm-codex/plugin.json +1 -1
  264. package/runtime-dependencies.json +1 -1
  265. package/dist/cli-bundle/chunks/chunk-7OEGNA4X.js +0 -20
  266. package/dist/cli-bundle/chunks/chunk-EMEEHV2Y.js +0 -2
  267. package/dist/cli-bundle/chunks/chunk-JSUJWIHQ.js +0 -30
  268. package/dist/cli-bundle/chunks/chunk-VIMQCFCK.js +0 -2
  269. package/dist/cli-bundle/chunks/chunk-X2H6UR26.js +0 -236
  270. package/dist/cli-bundle/chunks/register-mutation-EWMMVZJB.js +0 -20
  271. package/dist/cli-bundle/focused-chunks/chunk-5TBAVZDR.js +0 -20
  272. package/dist/cli-bundle/focused-chunks/chunk-HTA3TNC3.js +0 -26
  273. package/dist/cli-bundle/focused-chunks/chunk-JKBH7YGX.js +0 -2
  274. package/dist/cli-bundle/focused-chunks/chunk-PDYE7QDX.js +0 -166
  275. package/docs/ecosystem-review-2026-09-28.json +0 -1
package/dist/sdk/index.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]="1c706c4d-988c-5d6d-b8cc-8985ea2215d1")}catch{}})();import{isItemAlreadyExistsError}from"./errors.js";import{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,renderPmCommandVisibilityMarkdown,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"./agent-capability-contracts.js";export*from"./mcp/protocol.js";export*from"./mcp/interactions.js";export*from"./mcp/tasks.js";export*from"./mcp/subscriptions.js";export*from"./mcp/transport.js";export*from"./mcp/authorization.js";export*from"./mcp/apps.js";export*from"./mcp/skills.js";export*from"./cli-contracts/grammar-contracts.js";export*from"./agent-session-context.js";export*from"./environment/agent-environment.js";import{isErrnoError,limitAnnotationEntries,parseAnnotationTextInput,readAnnotationEntries,normalizeAnnotationTransportOptions,resolveAnnotationInput,resolveAnnotationIndex,runAnnotationCommand,wrapOwnershipConflict}from"./annotations.js";import{acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,inspectHistoryAuthorStream,parseUnknownAuthorHistoryEventCoordinates,planUnknownAuthorHistoryAcknowledgment,resolveUnknownAuthorAcknowledgmentSelector,scanHistoryAuthorAttribution}from"./author-attribution.js";import{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape}from"./corpus-shape.js";export*from"./core-governance.js";import{createPmCliProgram}from"./cli-program.js";import{runSearchRefreshWorkerEntrypoint}from"./search-refresh-worker.js";import{PM_REPRODUCIBLE_PROCESS_ENV,createReproducibleProcessRunner,resolveReproducibleProcessEnvironment,runWithReproducibleProcessEnvironment}from"./reproducibility/process.js";import{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe}from"./workspace-recipe.js";import{SNAPSHOT_SCHEMA,WORKSPACE_SNAPSHOT_ACTIONS,createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery}from"./workspace-snapshot.js";import{flushTelemetryQueue}from"./telemetry-flush.js";import{PM_HISTORY_COMMAND_ALIASES,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,findPmNamespacedCommand,resolvePmCommandOperation,resolvePmHistoryOperation}from"./cli-contracts.js";import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,stripGlobalBootstrapTokens}from"./cli-bootstrap.js";import{quoteCommandArg,quoteWindowsCommandArg,renderPmCommand}from"./command-line.js";export*from"./agent/command-recovery.js";export*from"./agent/command-suggestions.js";export*from"./agent/item-addressing.js";export*from"./agent/create-option-policy.js";import{runGc}from"./governance/gc.js";import{PM_EXACT_COVERAGE_METRICS,findCoverageDeficits}from"./governance/coverage-assurance.js";import{_testOnlyHealthCommand,runHealth}from"./governance/health.js";import{_testOnlyValidateCommand,projectValidateCounts,runValidate}from"./governance/validate.js";import{runExtension}from"./extension.js";import{inspectStaticExtensionInventory}from"./extension/static-inventory.js";import{buildExtensionInstallPlan,planExtensionDirectoryCopy}from"./extension/install-plan.js";import{resolveExtensionInstallSourceIdentity}from"./extension/source-resolution.js";import{applyStoredExtensionMigrationState,readExtensionMigrationState,resolveExtensionMigrationStatePath,runExtensionMigrateAction,runExtensionMigrations}from"./extension/migrations.js";import{findInstalledNpmPackageCandidate}from"./extension/install-sources.js";import{buildExtensionDescribeResult,renderExtensionDescribeMarkdown}from"./extension/describe.js";import{runEvent,runMeet,runRemind}from"./scheduling-shortcuts.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{isRuntimeRecord}from"./runtime-input.js";import{resolveStartTaskInProgressStatus}from"./start-task-status.js";import{auditMergeAttributeFence,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall}from"./merge/install.js";import{deriveSchemaEvolutionMigrationId,formatSchemaEvolutionMigrationHuman,planSchemaEvolutionMigration,runSchemaEvolutionMigration}from"./schema-migration.js";import{runWithActiveExtensions}from"./runtime.js";import{applyInvocationAuthorOverride}from"./invocation-author.js";import{evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,PM_MUTATION_ACTION_CONTRACTS,scanMutationSecrets}from"./mutation-guard.js";import{findSimilarItems,findDuplicateClusters,evaluateSimilarityGovernance,similarityAdvisoryWarnings,jaccardSimilarity,normalizeSimilarityText,prepareSimilarityText,scoreItemSimilarity,scorePreparedItemSimilarity,tokenizeSimilarityText}from"./similarity.js";import{inspectStaleInProgressItems,scanStaleInProgressItems}from"./governance/stale-work.js";import{describeItemOwnershipConflict}from"./ownership-source.js";import{discoverNearbyPmRoot}from"./tracker-root-discovery.js";import{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery}from"./environment/tracker-preflight.js";import{_testOnly}from"./templates.js";import{runConfig,_testOnlyConfigCommand}from"./config.js";export*from"./agent/identity-config.js";import{INIT_AGENT_GUIDANCE_MODE_VALUES,runInitAgentGuidance,_testOnly as _testOnly2}from"./init-agent-guidance.js";import{runInit,summarizeInitResult,_testOnly as _testOnly3}from"./init.js";import{PROFILE_SUBCOMMANDS,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,runProfileApply,runProfileLint,runProfileList,runProfileShow}from"./profile.js";export*from"./extension-contracts.js";import{RESERVED_ITEM_FIELD_NAMES}from"../core/extensions/item-fields.js";import{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest}from"../core/packages/manifest.js";import{ACTIVITY_FLAG_CONTRACTS,ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EVENTS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_CORE_COMMAND_NAMES,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_ITEM_ACTION_SUBCOMMANDS,PM_DEPRECATED_TOOL_ACTIONS,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTIONS,analyzePmToolActionParity,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PROFILE_FLAG_CONTRACTS,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,verifyToolOptionCliParity,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,buildPmActionToolInputSchema,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,compactFlagAliasContracts,createPmCommandOutputBudget,definePmCommandOutputBudget,estimatePmOutputTokens,inferPmOutputBudgetClass,projectPmDiagnosticOutput,projectPmDiagnosticText,analyzeSdkCliParameterCompleteness,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,hasSubcommandFlagContractsForCommand,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readStringArrayFromCommanderOptions,resolvePmPositionalActionFlagContracts,resolveSubcommandFlagContractsForCommand,resolvePmCommandOutputBudget,resolvePmDiagnosticOutputBudget,resolvePmToolCustomFieldCollision,toCompletionFlagString,withFlagAliasMetadata}from"./cli-contracts.js";export*from"./compose.js";export*from"./governance/assurance.js";export*from"./governance/assurance-action.js";export*from"./governance/assurance-runtime.js";export*from"./governance/assurance-presets.js";export*from"./governance/boundary-fixtures.js";export*from"./governance/defect-recurrence.js";export*from"./governance/merge-receipt-history.js";export*from"./compile-cache.js";export*from"./environment/project-runtime-compatibility.js";export*from"./environment/source-context.js";export*from"./environment/host-environment-errors.js";export*from"./cli-contracts/command-exit-contracts.js";export*from"./context-relevance.js";export*from"./context/recency.js";export*from"./context-intent-contracts.js";export*from"./context-intent-runtime.js";export*from"./context-signal-store.js";export*from"./workspace-memory.js";export*from"./lifecycle-completion.js";export*from"./lifecycle-policy.js";export*from"./output-projection.js";export*from"./read-output-contracts.js";export*from"./read-output-rows.js";export*from"./read-output-session.js";export*from"./output-token-accounting.js";export*from"./context-packing.js";export*from"./context-usage.js";import{classifyHistoryEvent,HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS}from"../core/history/event-classification.js";export*from"./dependency-provenance.js";export*from"./duplicates.js";export*from"./lifecycle/reopen.js";export*from"./history-compact.js";export*from"./history-read.js";export*from"../core/history/operation-contract.js";export*from"./history/maintenance.js";import{readHistorySnapshot}from"../core/history/read.js";export*from"./history-provenance.js";export*from"./mutation-events.js";export*from"./history-redact.js";import{_testOnly as _testOnly4}from"./history-redact.js";export*from"./history-repair.js";export*from"./item-children.js";export*from"./item-schedule.js";export*from"./merge/index.js";import{runDeps}from"./dependencies.js";export*from"./graph/index.js";import{runDocs}from"./docs.js";import{runFiles,runFilesDiscover,runFilesLookup}from"./files.js";import{applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths}from"./linked-artifacts.js";export*from"./pagination.js";export*from"./query/item-filter-options.js";export*from"./query/parsers.js";export*from"./output.js";export*from"./output-contracts.js";export*from"./agent/task-transcript-contracts.js";export*from"./relationship-analytics.js";export*from"./relationship-context.js";export*from"./relationship-history.js";export*from"./relationship-migration.js";export*from"./workspace-transaction.js";export*from"./workspace-transaction-gc.js";export*from"./item-transaction.js";export*from"./item-metadata-index.js";export*from"./structured-mutations.js";export*from"./runtime-primitives.js";export*from"./error-runtime.js";export*from"./error-code-catalog.js";export*from"./generated-error-code-catalog.js";export*from"./agent/refusal-reachability.js";export*from"./agent/refusal-closure-census.js";export*from"./agent/refusal-closure.js";export*from"./agent/closed-domain-contracts.js";export*from"./agent/refusal-corpus-contracts.js";import{MERGE_SUBCOMMAND_VALUES}from"./cli-contracts.js";export*from"./agent/tracker-preflight-contracts.js";export*from"./agent/subcommand-recovery.js";export*from"./flag-invocation-contracts.js";export*from"./cli-contracts/flag-lexicon-contracts.js";export*from"./relationships.js";export*from"./actionability.js";import{runCreate}from"./lifecycle/create.js";import{runPlan}from"./lifecycle/plan.js";import{runAppend}from"./lifecycle/append.js";import{isAlreadyClaimedError,runClaim,runClaimNext,runRelease}from"./lifecycle/claim.js";import{runStartTask,runPauseTask,runCloseTask}from"./lifecycle/task-composition.js";import{runCloseMany}from"./lifecycle/close-many.js";import{runUpdateMany}from"./lifecycle/update-many.js";import{runComments}from"./comments.js";import{runNotes}from"./notes.js";import{runLearnings}from"./learnings.js";import{runUpgrade}from"./governance/upgrade.js";import{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES}from"./lifecycle/plan.js";export*from"./define.js";import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,acquireLock,appendHistoryEntry,canonicalDocument,classifyItemFormatVersion,clearWorkspaceContractsCache,commitImportedItem,createHistoryEntry,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,ensureTrackerInitialized,generateItemId,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getSettingsPath,getWorkspaceContracts,isPmCliExpectedError,isTimestampLiteral,listAllItemMetadata,loadCreateTemplateOptions,locateItem,normalizeItemMetadata,normalizeItemFormatVersion,normalizeItemId,normalizeRawItemId,normalizeStatusInput,nowIso,parseTags,pathExists,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString,readSettings,readStringOption,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveItemTypeRegistry,resolveImplicitPmRoot,resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runCalendar,runCompletion,runGuide,runList,runReindex,runSearch,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,scanItemFormatVersions,selectImportAuthor,serializeItemDocument,splitFrontMatter,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,writeFileAtomic,aggregate,append,claim,claimNext,close,reopen,closeTask,comments,config,context,copy,create,deleteItem,deps,docs,duplicates,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,get,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,learnings,list,listAllComplete,next,notes,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,pauseTask,profile,profileApply,profileLint,profileList,profileShow,release,restore,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaShow,schemaShowField,schemaShowStatus,schemaRenameField,schemaRenameType,search,startTask,stats,update,upgrade,validate}from"./runtime.js";import{extensionMigrate,packageMigrate}from"./package-migrations.js";import{CONTEXT_OUTPUT_VALUES,NEXT_OUTPUT_VALUES,PM_GITIGNORE_END,PM_GITIGNORE_START,analyzeSdkActionCoverage,ensurePmGitignore,getPmGitignoreBlock,closeItem,runAggregate,runClose,runCopy,runContext,runDelete,runFocus,runGet,runNext,runRestore,runUpdate}from"./runtime.js";import{runStats}from"./stats.js";import{readImprovementLedger,recordImprovementObservation}from"./improvement-ledger.js";import{evaluateProvenanceCoverage,projectFleetAttributionAnalytics,projectProvenanceCoverageAnalytics,readHistoryAnalyticsWindow,runFleetAttributionAnalytics,runProvenanceCoverageAnalytics}from"./history-analytics.js";import{DEFAULT_EVAL_QUERIES_RELATIVE_PATH,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,parseEvalQuerySet,runEval}from"./eval.js";import{runTelemetry,TELEMETRY_SUBCOMMANDS}from"./telemetry.js";import{classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight}from"./test/execution.js";import{assertTestMeasurementRun}from"./test/prerequisites.js";import{TEST_RUN_MEASUREMENT_LIMIT,diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow}from"./test/measurements.js";import{runTestAll}from"./test/batch.js";import{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode}from"./test/parsers.js";import{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,linkedTestTrustFingerprint,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch}from"./test/trust.js";import{updateLinkedTest}from"./test/update.js";import{runStartBackgroundRun,runTestRunsWorker}from"./test/runs.js";import{BUILTIN_PROFILES,listProfiles,normalizeProfileName,PROFILE_NAMES,resolveProfile}from"../core/profile/profile-presets.js";import{planProfileApplication}from"../core/profile/profile-plan.js";import{describeProfileComposition,describeProjectProfile}from"../core/profile/profile-describe.js";import{lintProjectProfile,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS}from"../core/profile/profile-lint.js";export*from"./authoring.js";export*from"./governance.js";export*from"./mcp/discovery.js";export*from"./query.js";export*from"./testing.js";export{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,ACTIVITY_FLAG_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,BASELINE_ITEM_FORMAT_VERSION,BUILTIN_CORPUS_SHAPES,BUILTIN_ITEM_TYPE_VALUES,BUILTIN_PROFILES,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIDENCE_TEXT_VALUES,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTEXT_OUTPUT_VALUES,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,CURRENT_ITEM_FORMAT_VERSION,DEFAULT_EVAL_QUERIES_RELATIVE_PATH,DELETE_FLAG_CONTRACTS,DEPENDENCY_KIND_VALUES,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,EVENTS_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EXECUTABLE_COMMAND_ALIASES,EXIT_CODE,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_EVENT_CLASSIFICATION_VERSION,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,INIT_AGENT_GUIDANCE_MODE_VALUES,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ISSUE_SEVERITY_VALUES,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,ITEM_TYPE_VALUES,LEARNINGS_FLAG_CONTRACTS,LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MAINTENANCE_HISTORY_OPERATIONS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,MERGE_SUBCOMMAND_VALUES,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NEXT_OUTPUT_VALUES,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_CLI_EXPECTED_ERROR_NAME,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_COMMAND_ALIAS_CONTRACTS,PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_CORE_COMMAND_NAMES,PM_CORPUS_SHAPE_SCHEMA,PM_DEPRECATED_TOOL_ACTIONS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXACT_COVERAGE_METRICS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_GITIGNORE_END,PM_GITIGNORE_START,PM_HISTORY_COMMAND_ALIASES,PM_ITEM_ACTION_SUBCOMMANDS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,PM_MUTATION_ACTION_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_PACKAGE_RESOURCE_KINDS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_RELOCATED_COMMAND_ALIASES,PM_REPRODUCIBLE_PROCESS_ENV,PM_TOOL_ACTIONS,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,PM_WORKSPACE_RECIPE_SCHEMA,PROFILE_FLAG_CONTRACTS,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,PROFILE_NAMES,PROFILE_SUBCOMMANDS,PmCliError,PmClient,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESERVED_ITEM_FIELD_NAMES,RESTORE_FLAG_CONTRACTS,RISK_VALUES,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,SNAPSHOT_SCHEMA,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,STATUS_VALUES,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,SUBSTANTIVE_HISTORY_OPERATIONS,TELEMETRY_FLAG_CONTRACTS,TELEMETRY_SUBCOMMANDS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TEST_RUN_MEASUREMENT_LIMIT,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,WORKSPACE_SNAPSHOT_ACTIONS,_testOnly4 as _testOnly,_testOnlyConfigCommand,_testOnlyHealthCommand,_testOnly3 as _testOnlyInit,_testOnly2 as _testOnlyInitAgentGuidance,_testOnly as _testOnlyTemplates,_testOnlyValidateCommand,acknowledgeLinkedTests,acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,acquireLock,aggregate,analyzePmToolActionParity,analyzeSdkActionCoverage,analyzeSdkCliParameterCompleteness,append,appendHistoryEntry,applyBootstrapPagerPolicy,applyInvocationAuthorOverride,applyPathMigrations,applyStandaloneNote,applyStoredExtensionMigrationState,artifactKey,assertInitializedTracker,assertLinkedArtifactMutationIsUnambiguous,assertReadableTrackerRoot,assertTestMeasurementRun,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,auditMergeAttributeFence,buildCorpusShapeItemPlan,buildExtensionDescribeResult,buildExtensionInstallPlan,buildMergeAttributePatterns,buildPmActionToolInputSchema,buildTrackerInitializationRecovery,canonicalDocument,claim,claimNext,classifyHistoryEvent,classifyItemFormatVersion,classifyLinkedTestCommandSafety,classifyLinkedTestFailure,clearWorkspaceContractsCache,close,closeItem,closeTask,coalesceRepeatedListFlags,collectPackageExtensionDirectories,comments,commitImportedItem,compactFlagAliasContracts,config,context,copy,countFailureCategories,create,createCorpusShapeMeasurement,createExtensionCommandSdk,createHistoryEntry,createPmCliExpectedError,createPmCliProgram,createPmCommandOutputBudget,createReproducibleProcessRunner,createWorkspaceSnapshot,dedupeLinkedArtifacts,defineCorpusShape,definePmCommandOutputBudget,defineWorkspaceRecipe,deleteItem,deleteWorkspaceSnapshot,deps,deriveSchemaEvolutionMigrationId,describeItemOwnershipConflict,describeProfileComposition,describeProjectProfile,diffTestRunMeasurements,discoverNearbyPmRoot,docs,duplicates,effectiveItemFormatVersion,emptyImportedDocument,ensurePmGitignore,ensureScope,ensureTrackerInitialized,estimatePmOutputTokens,evaluateMutationGuard,evaluateProvenanceCoverage,evaluateSimilarityGovernance,executeWorkspaceRecipe,expandAddGlobEntries,extension,extensionActivate,extensionDeactivate,extensionList,extensionMigrate,extractReferencedPmItemIdsFromCommand,files,filesDiscover,filesLookup,findCoverageDeficits,findDuplicateClusters,findGitWorkspaceRoot,findInstalledNpmPackageCandidate,findPmNamespacedCommand,findSimilarItems,flushTelemetryQueue,focus,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,formatSchemaEvolutionMigrationHuman,gc,generateItemId,get,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getMutationActionContract,getPmGitignoreBlock,getSettingsPath,getWorkspaceContracts,graph,hasSubcommandFlagContractsForCommand,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,inferPmOutputBudgetClass,init,inspectHistoryAuthorStream,inspectStaleInProgressItems,inspectStaticExtensionInventory,inspectWorkspaceSnapshot,installMergeFence,isAlreadyClaimedError,isErrnoError,isItemAlreadyExistsError,isMutationAction,isPmCliExpectedError,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,isRuntimeRecord,isTimestampLiteral,jaccardSimilarity,learnings,limitAnnotationEntries,linkedTestTrustFingerprint,lintProjectProfile,list,listAliasPluralKeys,listAllComplete,listAllItemMetadata,listBuiltinCorpusShapes,listMutationActions,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,listProfiles,listWorkspaceSnapshots,loadCreateTemplateOptions,locateItem,measureCorpusShapePlan,mergeLinkedTestTwoTokenEntries,next,normalizeAnnotationTransportOptions,normalizeBootstrapInvocation,normalizeItemFormatVersion,normalizeItemId,normalizeItemMetadata,normalizeLegacyExtensionActionSyntax,normalizeLinkedPath,normalizeProfileName,normalizeRawItemId,normalizeSimilarityText,normalizeStatusInput,notes,nowIso,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageMigrate,packageReload,packageUninstall,parseAddEntries,parseAddGlobEntries,parseAnnotationTextInput,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,parseEvalQuerySet,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode,parseMigrateEntries,parseRemoveEntries,parseTags,parseTestRunMeasurements,parseUnknownAuthorHistoryEventCoordinates,pathExists,pauseTask,planExtensionDirectoryCopy,planProfileApplication,planSchemaEvolutionMigration,planUnknownAuthorHistoryAcknowledgment,planWorkspaceSnapshotRestore,prepareSimilarityText,profile,profileApply,profileLint,profileList,profileShow,projectFleetAttributionAnalytics,projectPmDiagnosticOutput,projectPmDiagnosticText,projectProvenanceCoverageAnalytics,projectValidateCounts,queryTestRunMeasurementsBelow,quoteCommandArg,quoteWindowsCommandArg,readAnnotationEntries,readBooleanOption,readCsvListOption,readExtensionMigrationState,readFileIfExists,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readHistoryAnalyticsWindow,readHistorySnapshot,readImprovementLedger,readLocatedItem,readPmPackageManifest,readRequiredString,readSettings,readStringArrayFromCommanderOptions,readStringOption,recordImprovementObservation,refreshMergeAttributeFenceIfInstalled,release,removeFileIfExists,renameArtifactsResultKey,renderCalendarMarkdown,renderCalendarToon,renderExtensionDescribeMarkdown,renderGuideMarkdown,renderPmCommand,renderPmCommandAliasMigrationHint,renderPmCommandVisibilityMarkdown,reopen,resolveAnnotationIndex,resolveAnnotationInput,resolveBuiltinCorpusShape,resolveCalendarOutputFormat,resolveExtensionInstallSourceIdentity,resolveExtensionMigrationStatePath,resolveGuideOutputFormat,resolveImplicitPmRoot,resolveItemTypeRegistry,resolveLinkedTestFailureExitCode,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch,resolveMergeInstallContext,resolvePmCommandAlias,resolvePmCommandCapabilityFamily,resolvePmCommandOperation,resolvePmCommandOutputBudget,resolvePmCommandVisibilityTier,resolvePmDiagnosticOutputBudget,resolvePmHistoryOperation,resolvePmPositionalActionFlagContracts,resolvePmRoot,resolvePmToolCustomFieldCollision,resolveProfile,resolveProjectMergeTypeFolders,resolveReproducibleProcessEnvironment,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,resolveStartTaskInProgressStatus,resolveSubcommandFlagContractsForCommand,resolveUnknownAuthorAcknowledgmentSelector,restore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runAggregate,runAnnotationCommand,runAppend,runCalendar,runClaim,runClaimNext,runClose,runCloseMany,runCloseTask,runComments,runCompletion,runConfig,runContext,runCopy,runCreate,runDelete,runDeps,runDocs,runEval,runEvent,runExtension,runExtensionMigrateAction,runExtensionMigrations,runFiles,runFilesDiscover,runFilesLookup,runFleetAttributionAnalytics,runFocus,runGc,runGet,runGuide,runHealth,runInit,runInitAgentGuidance,runLearnings,runLinkedArtifacts,runLinkedTests,runList,runMeet,runMergeInstall,runNext,runNotes,runPauseTask,runPlan,runProfileApply,runProfileLint,runProfileList,runProfileShow,runProvenanceCoverageAnalytics,runReindex,runRelease,runRemind,runRestore,runSchemaEvolutionMigration,runSearch,runSearchRefreshWorkerEntrypoint,runStartBackgroundRun,runStartTask,runStats,runTelemetry,runTemplatesList,runTemplatesSave,runTemplatesShow,runTest,runTestAll,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runTestRunsWorker,runUpdate,runUpdateMany,runUpgrade,runValidate,runWithActiveExtensions,runWithReproducibleProcessEnvironment,runWithWorkspaceRecipe,scanHistoryAuthorAttribution,scanItemFormatVersions,scanMutationSecrets,scanStaleInProgressItems,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaRenameField,schemaRenameType,schemaShow,schemaShowField,schemaShowStatus,scoreItemSimilarity,scorePreparedItemSimilarity,search,selectImportAuthor,serializeItemDocument,similarityAdvisoryWarnings,sortLinkedArtifacts,splitFrontMatter,startTask,stats,stripGlobalBootstrapTokens,summarizeContextPreflight,summarizeInitResult,toCompletionFlagString,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,tokenizeSimilarityText,update,updateLinkedTest,upgrade,validate,validateLinkedPaths,verifyToolOptionCliParity,withFlagAliasMetadata,wrapOwnershipConflict,writeFileAtomic};
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]="ca441e38-d2e2-53eb-83b8-db9b93c85cac")}catch{}})();import{isItemAlreadyExistsError}from"./errors.js";import{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,renderPmCommandVisibilityMarkdown,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"./agent-capability-contracts.js";export*from"./mcp/protocol.js";export*from"./mcp/interactions.js";export*from"./mcp/tasks.js";export*from"./mcp/subscriptions.js";export*from"./mcp/transport.js";export*from"./mcp/authorization.js";export*from"./mcp/apps.js";export*from"./mcp/skills.js";export*from"./cli-contracts/grammar-contracts.js";export*from"./agent-session-context.js";export*from"./environment/agent-environment.js";import{isErrnoError,limitAnnotationEntries,parseAnnotationTextInput,readAnnotationEntries,normalizeAnnotationTransportOptions,resolveAnnotationInput,resolveAnnotationIndex,runAnnotationCommand,wrapOwnershipConflict}from"./annotations.js";import{acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,inspectHistoryAuthorStream,parseUnknownAuthorHistoryEventCoordinates,planUnknownAuthorHistoryAcknowledgment,resolveUnknownAuthorAcknowledgmentSelector,scanHistoryAuthorAttribution}from"./author-attribution.js";import{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape}from"./corpus-shape.js";export*from"./core-governance.js";import{createPmCliProgram}from"./cli-program.js";import{runSearchRefreshWorkerEntrypoint}from"./search-refresh-worker.js";import{PM_REPRODUCIBLE_PROCESS_ENV,createReproducibleProcessRunner,resolveReproducibleProcessEnvironment,runWithReproducibleProcessEnvironment}from"./reproducibility/process.js";import{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe}from"./workspace-recipe.js";import{SNAPSHOT_SCHEMA,WORKSPACE_SNAPSHOT_ACTIONS,createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery}from"./workspace-snapshot.js";import{flushTelemetryQueue}from"./telemetry-flush.js";import{PM_HISTORY_COMMAND_ALIASES,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,findPmNamespacedCommand,resolvePmCommandOperation,resolvePmHistoryOperation}from"./cli-contracts.js";import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,stripGlobalBootstrapTokens}from"./cli-bootstrap.js";import{quoteCommandArg,quoteWindowsCommandArg,renderPmCommand}from"./command-line.js";export*from"./agent/command-recovery.js";export*from"./agent/command-suggestions.js";export*from"./agent/item-addressing.js";export*from"./agent/create-option-policy.js";import{runGc}from"./governance/gc.js";import{PM_EXACT_COVERAGE_METRICS,findCoverageDeficits}from"./governance/coverage-assurance.js";import{_testOnlyHealthCommand,runHealth}from"./governance/health.js";import{_testOnlyValidateCommand,projectValidateCounts,runValidate}from"./governance/validate.js";import{runExtension}from"./extension.js";import{inspectStaticExtensionInventory}from"./extension/static-inventory.js";import{buildExtensionInstallPlan,planExtensionDirectoryCopy}from"./extension/install-plan.js";import{resolveExtensionInstallSourceIdentity}from"./extension/source-resolution.js";import{applyStoredExtensionMigrationState,readExtensionMigrationState,resolveExtensionMigrationStatePath,runExtensionMigrateAction,runExtensionMigrations}from"./extension/migrations.js";import{findInstalledNpmPackageCandidate}from"./extension/install-sources.js";import{buildExtensionDescribeResult,renderExtensionDescribeMarkdown}from"./extension/describe.js";import{runEvent,runMeet,runRemind}from"./scheduling-shortcuts.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{isRuntimeRecord}from"./runtime-input.js";import{resolveStartTaskInProgressStatus}from"./start-task-status.js";import{auditMergeAttributeFence,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall}from"./merge/install.js";import{deriveSchemaEvolutionMigrationId,formatSchemaEvolutionMigrationHuman,planSchemaEvolutionMigration,runSchemaEvolutionMigration}from"./schema-migration.js";import{runWithActiveExtensions}from"./runtime.js";import{applyInvocationAuthorOverride}from"./invocation-author.js";import{evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,PM_MUTATION_ACTION_CONTRACTS,scanMutationSecrets}from"./mutation-guard.js";import{findSimilarItems,findDuplicateClusters,evaluateSimilarityGovernance,similarityAdvisoryWarnings,jaccardSimilarity,normalizeSimilarityText,prepareSimilarityText,scoreItemSimilarity,scorePreparedItemSimilarity,tokenizeSimilarityText}from"./similarity.js";import{inspectStaleInProgressItems,scanStaleInProgressItems}from"./governance/stale-work.js";import{describeItemOwnershipConflict}from"./ownership-source.js";import{discoverNearbyPmRoot}from"./tracker-root-discovery.js";import{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery}from"./environment/tracker-preflight.js";import{_testOnly}from"./templates.js";import{runConfig,_testOnlyConfigCommand}from"./config.js";export*from"./agent/identity-config.js";import{INIT_AGENT_GUIDANCE_MODE_VALUES,runInitAgentGuidance,_testOnly as _testOnly2}from"./init-agent-guidance.js";import{runInit,summarizeInitResult,_testOnly as _testOnly3}from"./init.js";import{PROFILE_SUBCOMMANDS,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,runProfileApply,runProfileLint,runProfileList,runProfileShow}from"./profile.js";export*from"./extension-contracts.js";import{RESERVED_ITEM_FIELD_NAMES}from"../core/extensions/item-fields.js";import{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest}from"../core/packages/manifest.js";import{ACTIVITY_FLAG_CONTRACTS,ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EVENTS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_CORE_COMMAND_NAMES,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_ITEM_ACTION_SUBCOMMANDS,PM_DEPRECATED_TOOL_ACTIONS,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTIONS,analyzePmToolActionParity,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PROFILE_FLAG_CONTRACTS,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,verifyToolOptionCliParity,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,buildPmActionToolInputSchema,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,compactFlagAliasContracts,createPmCommandOutputBudget,definePmCommandOutputBudget,estimatePmOutputTokens,inferPmOutputBudgetClass,projectPmDiagnosticOutput,projectPmDiagnosticText,analyzeSdkCliParameterCompleteness,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,hasSubcommandFlagContractsForCommand,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readStringArrayFromCommanderOptions,resolvePmPositionalActionFlagContracts,resolveSubcommandFlagContractsForCommand,resolvePmCommandOutputBudget,resolvePmDiagnosticOutputBudget,resolvePmToolCustomFieldCollision,toCompletionFlagString,withFlagAliasMetadata}from"./cli-contracts.js";export*from"./compose.js";export*from"./governance/assurance.js";export*from"./governance/assurance-action.js";export*from"./governance/assurance-runtime.js";export*from"./governance/assurance-presets.js";export*from"./governance/boundary-fixtures.js";export*from"./governance/defect-recurrence.js";export*from"./governance/merge-receipt-history.js";export*from"./compile-cache.js";export*from"./environment/project-runtime-compatibility.js";export*from"./environment/source-context.js";export*from"./environment/host-environment-errors.js";export*from"./cli-contracts/command-exit-contracts.js";export*from"./context-relevance.js";export*from"./context/recency.js";export*from"./context-intent-contracts.js";export*from"./context-intent-runtime.js";export*from"./context-signal-store.js";export*from"./workspace-memory.js";export*from"./lifecycle-completion.js";export*from"./lifecycle-policy.js";export*from"./output-projection.js";export*from"./read-output-contracts.js";export*from"./read-output-rows.js";export*from"./read-output-session.js";export*from"./output-token-accounting.js";export*from"./context-packing.js";export*from"./context-usage.js";import{classifyHistoryEvent,HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS}from"../core/history/event-classification.js";export*from"./dependency-provenance.js";export*from"./duplicates.js";export*from"./lifecycle/reopen.js";export*from"./history-compact.js";export*from"./history-read.js";export*from"../core/history/operation-contract.js";export*from"./history/maintenance.js";import{readHistorySnapshot}from"../core/history/read.js";export*from"./history-provenance.js";export*from"./mutation-events.js";export*from"./history-redact.js";import{_testOnly as _testOnly4}from"./history-redact.js";export*from"./history-repair.js";export*from"./item-children.js";export*from"./item-schedule.js";export*from"./merge/index.js";import{runDeps}from"./dependencies.js";export*from"./graph/index.js";import{runDocs}from"./docs.js";import{runFiles,runFilesDiscover,runFilesLookup}from"./files.js";import{applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths}from"./linked-artifacts.js";export*from"./pagination.js";export*from"./query/item-filter-options.js";export*from"./query/parsers.js";export*from"./output.js";export*from"./output-contracts.js";export*from"./agent/task-transcript-contracts.js";export*from"./relationship-analytics.js";export*from"./relationship-context.js";export*from"./relationship-history.js";export*from"./relationship-migration.js";export*from"./workspace-transaction.js";export*from"./workspace-transaction-gc.js";export*from"./item-transaction.js";export*from"./item-metadata-index.js";export*from"./structured-mutations.js";export*from"./lifecycle/structured-mutation-plan.js";export*from"./runtime-primitives.js";export*from"./error-runtime.js";export*from"./error-code-catalog.js";export*from"./generated-error-code-catalog.js";export*from"./agent/refusal-reachability.js";export*from"./agent/refusal-closure-census.js";export*from"./agent/refusal-closure.js";export*from"./agent/closed-domain-contracts.js";export*from"./agent/refusal-corpus-contracts.js";import{MERGE_SUBCOMMAND_VALUES}from"./cli-contracts.js";export*from"./agent/tracker-preflight-contracts.js";export*from"./agent/subcommand-recovery.js";export*from"./flag-invocation-contracts.js";export*from"./cli-contracts/flag-lexicon-contracts.js";export*from"./relationships.js";export*from"./actionability.js";import{runCreate}from"./lifecycle/create.js";import{runPlan}from"./lifecycle/plan.js";import{runAppend}from"./lifecycle/append.js";import{isAlreadyClaimedError,runClaim,runClaimNext,runRelease}from"./lifecycle/claim.js";import{runStartTask,runPauseTask,runCloseTask}from"./lifecycle/task-composition.js";import{runCloseMany}from"./lifecycle/close-many.js";import{runUpdateMany}from"./lifecycle/update-many.js";import{runComments}from"./comments.js";import{runNotes}from"./notes.js";import{runLearnings}from"./learnings.js";import{runUpgrade}from"./governance/upgrade.js";import{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES}from"./lifecycle/plan.js";export*from"./define.js";import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,acquireLock,appendHistoryEntry,canonicalDocument,classifyItemFormatVersion,clearWorkspaceContractsCache,commitImportedItem,createHistoryEntry,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,ensureTrackerInitialized,generateItemId,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getSettingsPath,getWorkspaceContracts,isPmCliExpectedError,isTimestampLiteral,listAllItemMetadata,loadCreateTemplateOptions,locateItem,normalizeItemMetadata,normalizeItemFormatVersion,normalizeItemId,normalizeRawItemId,normalizeStatusInput,nowIso,parseTags,pathExists,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString,readSettings,readStringOption,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveItemTypeRegistry,resolveImplicitPmRoot,resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runCalendar,runCompletion,runGuide,runList,runReindex,runSearch,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,scanItemFormatVersions,selectImportAuthor,serializeItemDocument,splitFrontMatter,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,writeFileAtomic,aggregate,append,claim,claimNext,close,reopen,closeTask,comments,config,context,copy,create,deleteItem,deps,docs,duplicates,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,get,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,learnings,list,listAllComplete,next,notes,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,pauseTask,profile,profileApply,profileLint,profileList,profileShow,release,restore,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaShow,schemaShowField,schemaShowStatus,schemaRenameField,schemaRenameType,search,startTask,stats,update,upgrade,validate}from"./runtime.js";import{extensionMigrate,packageMigrate}from"./package-migrations.js";import{CONTEXT_OUTPUT_VALUES,NEXT_OUTPUT_VALUES,PM_GITIGNORE_END,PM_GITIGNORE_START,analyzeSdkActionCoverage,ensurePmGitignore,getPmGitignoreBlock,closeItem,runAggregate,runClose,runCopy,runContext,runDelete,runFocus,runGet,runNext,runRestore,runUpdate}from"./runtime.js";import{runStats}from"./stats.js";import{readImprovementLedger,recordImprovementObservation}from"./improvement-ledger.js";import{evaluateProvenanceCoverage,projectFleetAttributionAnalytics,projectProvenanceCoverageAnalytics,readHistoryAnalyticsWindow,runFleetAttributionAnalytics,runProvenanceCoverageAnalytics}from"./history-analytics.js";import{DEFAULT_EVAL_QUERIES_RELATIVE_PATH,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,parseEvalQuerySet,runEval}from"./eval.js";import{runTelemetry,TELEMETRY_SUBCOMMANDS}from"./telemetry.js";import{classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight}from"./test/execution.js";import{assertTestMeasurementRun}from"./test/prerequisites.js";import{TEST_RUN_MEASUREMENT_LIMIT,diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow}from"./test/measurements.js";import{runTestAll}from"./test/batch.js";import{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode}from"./test/parsers.js";import{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,linkedTestTrustFingerprint,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch}from"./test/trust.js";import{updateLinkedTest}from"./test/update.js";import{runStartBackgroundRun,runTestRunsWorker}from"./test/runs.js";import{BUILTIN_PROFILES,listProfiles,normalizeProfileName,PROFILE_NAMES,resolveProfile}from"../core/profile/profile-presets.js";import{planProfileApplication}from"../core/profile/profile-plan.js";import{describeProfileComposition,describeProjectProfile}from"../core/profile/profile-describe.js";import{lintProjectProfile,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS}from"../core/profile/profile-lint.js";export*from"./authoring.js";export*from"./governance.js";export*from"./mcp/discovery.js";export*from"./query.js";export*from"./testing.js";export{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,ACTIVITY_FLAG_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,BASELINE_ITEM_FORMAT_VERSION,BUILTIN_CORPUS_SHAPES,BUILTIN_ITEM_TYPE_VALUES,BUILTIN_PROFILES,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIDENCE_TEXT_VALUES,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTEXT_OUTPUT_VALUES,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,CURRENT_ITEM_FORMAT_VERSION,DEFAULT_EVAL_QUERIES_RELATIVE_PATH,DELETE_FLAG_CONTRACTS,DEPENDENCY_KIND_VALUES,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,EVENTS_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EXECUTABLE_COMMAND_ALIASES,EXIT_CODE,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_EVENT_CLASSIFICATION_VERSION,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,INIT_AGENT_GUIDANCE_MODE_VALUES,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ISSUE_SEVERITY_VALUES,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,ITEM_TYPE_VALUES,LEARNINGS_FLAG_CONTRACTS,LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MAINTENANCE_HISTORY_OPERATIONS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,MERGE_SUBCOMMAND_VALUES,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NEXT_OUTPUT_VALUES,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_CLI_EXPECTED_ERROR_NAME,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_COMMAND_ALIAS_CONTRACTS,PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_CORE_COMMAND_NAMES,PM_CORPUS_SHAPE_SCHEMA,PM_DEPRECATED_TOOL_ACTIONS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXACT_COVERAGE_METRICS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_GITIGNORE_END,PM_GITIGNORE_START,PM_HISTORY_COMMAND_ALIASES,PM_ITEM_ACTION_SUBCOMMANDS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,PM_MUTATION_ACTION_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_PACKAGE_RESOURCE_KINDS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_RELOCATED_COMMAND_ALIASES,PM_REPRODUCIBLE_PROCESS_ENV,PM_TOOL_ACTIONS,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,PM_WORKSPACE_RECIPE_SCHEMA,PROFILE_FLAG_CONTRACTS,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,PROFILE_NAMES,PROFILE_SUBCOMMANDS,PmCliError,PmClient,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESERVED_ITEM_FIELD_NAMES,RESTORE_FLAG_CONTRACTS,RISK_VALUES,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,SNAPSHOT_SCHEMA,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,STATUS_VALUES,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,SUBSTANTIVE_HISTORY_OPERATIONS,TELEMETRY_FLAG_CONTRACTS,TELEMETRY_SUBCOMMANDS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TEST_RUN_MEASUREMENT_LIMIT,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,WORKSPACE_SNAPSHOT_ACTIONS,_testOnly4 as _testOnly,_testOnlyConfigCommand,_testOnlyHealthCommand,_testOnly3 as _testOnlyInit,_testOnly2 as _testOnlyInitAgentGuidance,_testOnly as _testOnlyTemplates,_testOnlyValidateCommand,acknowledgeLinkedTests,acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,acquireLock,aggregate,analyzePmToolActionParity,analyzeSdkActionCoverage,analyzeSdkCliParameterCompleteness,append,appendHistoryEntry,applyBootstrapPagerPolicy,applyInvocationAuthorOverride,applyPathMigrations,applyStandaloneNote,applyStoredExtensionMigrationState,artifactKey,assertInitializedTracker,assertLinkedArtifactMutationIsUnambiguous,assertReadableTrackerRoot,assertTestMeasurementRun,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,auditMergeAttributeFence,buildCorpusShapeItemPlan,buildExtensionDescribeResult,buildExtensionInstallPlan,buildMergeAttributePatterns,buildPmActionToolInputSchema,buildTrackerInitializationRecovery,canonicalDocument,claim,claimNext,classifyHistoryEvent,classifyItemFormatVersion,classifyLinkedTestCommandSafety,classifyLinkedTestFailure,clearWorkspaceContractsCache,close,closeItem,closeTask,coalesceRepeatedListFlags,collectPackageExtensionDirectories,comments,commitImportedItem,compactFlagAliasContracts,config,context,copy,countFailureCategories,create,createCorpusShapeMeasurement,createExtensionCommandSdk,createHistoryEntry,createPmCliExpectedError,createPmCliProgram,createPmCommandOutputBudget,createReproducibleProcessRunner,createWorkspaceSnapshot,dedupeLinkedArtifacts,defineCorpusShape,definePmCommandOutputBudget,defineWorkspaceRecipe,deleteItem,deleteWorkspaceSnapshot,deps,deriveSchemaEvolutionMigrationId,describeItemOwnershipConflict,describeProfileComposition,describeProjectProfile,diffTestRunMeasurements,discoverNearbyPmRoot,docs,duplicates,effectiveItemFormatVersion,emptyImportedDocument,ensurePmGitignore,ensureScope,ensureTrackerInitialized,estimatePmOutputTokens,evaluateMutationGuard,evaluateProvenanceCoverage,evaluateSimilarityGovernance,executeWorkspaceRecipe,expandAddGlobEntries,extension,extensionActivate,extensionDeactivate,extensionList,extensionMigrate,extractReferencedPmItemIdsFromCommand,files,filesDiscover,filesLookup,findCoverageDeficits,findDuplicateClusters,findGitWorkspaceRoot,findInstalledNpmPackageCandidate,findPmNamespacedCommand,findSimilarItems,flushTelemetryQueue,focus,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,formatSchemaEvolutionMigrationHuman,gc,generateItemId,get,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getMutationActionContract,getPmGitignoreBlock,getSettingsPath,getWorkspaceContracts,graph,hasSubcommandFlagContractsForCommand,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,inferPmOutputBudgetClass,init,inspectHistoryAuthorStream,inspectStaleInProgressItems,inspectStaticExtensionInventory,inspectWorkspaceSnapshot,installMergeFence,isAlreadyClaimedError,isErrnoError,isItemAlreadyExistsError,isMutationAction,isPmCliExpectedError,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,isRuntimeRecord,isTimestampLiteral,jaccardSimilarity,learnings,limitAnnotationEntries,linkedTestTrustFingerprint,lintProjectProfile,list,listAliasPluralKeys,listAllComplete,listAllItemMetadata,listBuiltinCorpusShapes,listMutationActions,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,listProfiles,listWorkspaceSnapshots,loadCreateTemplateOptions,locateItem,measureCorpusShapePlan,mergeLinkedTestTwoTokenEntries,next,normalizeAnnotationTransportOptions,normalizeBootstrapInvocation,normalizeItemFormatVersion,normalizeItemId,normalizeItemMetadata,normalizeLegacyExtensionActionSyntax,normalizeLinkedPath,normalizeProfileName,normalizeRawItemId,normalizeSimilarityText,normalizeStatusInput,notes,nowIso,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageMigrate,packageReload,packageUninstall,parseAddEntries,parseAddGlobEntries,parseAnnotationTextInput,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,parseEvalQuerySet,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode,parseMigrateEntries,parseRemoveEntries,parseTags,parseTestRunMeasurements,parseUnknownAuthorHistoryEventCoordinates,pathExists,pauseTask,planExtensionDirectoryCopy,planProfileApplication,planSchemaEvolutionMigration,planUnknownAuthorHistoryAcknowledgment,planWorkspaceSnapshotRestore,prepareSimilarityText,profile,profileApply,profileLint,profileList,profileShow,projectFleetAttributionAnalytics,projectPmDiagnosticOutput,projectPmDiagnosticText,projectProvenanceCoverageAnalytics,projectValidateCounts,queryTestRunMeasurementsBelow,quoteCommandArg,quoteWindowsCommandArg,readAnnotationEntries,readBooleanOption,readCsvListOption,readExtensionMigrationState,readFileIfExists,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readHistoryAnalyticsWindow,readHistorySnapshot,readImprovementLedger,readLocatedItem,readPmPackageManifest,readRequiredString,readSettings,readStringArrayFromCommanderOptions,readStringOption,recordImprovementObservation,refreshMergeAttributeFenceIfInstalled,release,removeFileIfExists,renameArtifactsResultKey,renderCalendarMarkdown,renderCalendarToon,renderExtensionDescribeMarkdown,renderGuideMarkdown,renderPmCommand,renderPmCommandAliasMigrationHint,renderPmCommandVisibilityMarkdown,reopen,resolveAnnotationIndex,resolveAnnotationInput,resolveBuiltinCorpusShape,resolveCalendarOutputFormat,resolveExtensionInstallSourceIdentity,resolveExtensionMigrationStatePath,resolveGuideOutputFormat,resolveImplicitPmRoot,resolveItemTypeRegistry,resolveLinkedTestFailureExitCode,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch,resolveMergeInstallContext,resolvePmCommandAlias,resolvePmCommandCapabilityFamily,resolvePmCommandOperation,resolvePmCommandOutputBudget,resolvePmCommandVisibilityTier,resolvePmDiagnosticOutputBudget,resolvePmHistoryOperation,resolvePmPositionalActionFlagContracts,resolvePmRoot,resolvePmToolCustomFieldCollision,resolveProfile,resolveProjectMergeTypeFolders,resolveReproducibleProcessEnvironment,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,resolveStartTaskInProgressStatus,resolveSubcommandFlagContractsForCommand,resolveUnknownAuthorAcknowledgmentSelector,restore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runAggregate,runAnnotationCommand,runAppend,runCalendar,runClaim,runClaimNext,runClose,runCloseMany,runCloseTask,runComments,runCompletion,runConfig,runContext,runCopy,runCreate,runDelete,runDeps,runDocs,runEval,runEvent,runExtension,runExtensionMigrateAction,runExtensionMigrations,runFiles,runFilesDiscover,runFilesLookup,runFleetAttributionAnalytics,runFocus,runGc,runGet,runGuide,runHealth,runInit,runInitAgentGuidance,runLearnings,runLinkedArtifacts,runLinkedTests,runList,runMeet,runMergeInstall,runNext,runNotes,runPauseTask,runPlan,runProfileApply,runProfileLint,runProfileList,runProfileShow,runProvenanceCoverageAnalytics,runReindex,runRelease,runRemind,runRestore,runSchemaEvolutionMigration,runSearch,runSearchRefreshWorkerEntrypoint,runStartBackgroundRun,runStartTask,runStats,runTelemetry,runTemplatesList,runTemplatesSave,runTemplatesShow,runTest,runTestAll,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runTestRunsWorker,runUpdate,runUpdateMany,runUpgrade,runValidate,runWithActiveExtensions,runWithReproducibleProcessEnvironment,runWithWorkspaceRecipe,scanHistoryAuthorAttribution,scanItemFormatVersions,scanMutationSecrets,scanStaleInProgressItems,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaRenameField,schemaRenameType,schemaShow,schemaShowField,schemaShowStatus,scoreItemSimilarity,scorePreparedItemSimilarity,search,selectImportAuthor,serializeItemDocument,similarityAdvisoryWarnings,sortLinkedArtifacts,splitFrontMatter,startTask,stats,stripGlobalBootstrapTokens,summarizeContextPreflight,summarizeInitResult,toCompletionFlagString,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,tokenizeSimilarityText,update,updateLinkedTest,upgrade,validate,validateLinkedPaths,verifyToolOptionCliParity,withFlagAliasMetadata,wrapOwnershipConflict,writeFileAtomic};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,9 +1,12 @@
1
+ import { loadRuntimeSchemaFromOptionalFiles } from "../core/schema/runtime-schema.js";
2
+ import type { ItemTypeDefinition,PmSettings } from "../types/index.js";
3
+ import { type ItemMutationUpsertCandidate } from "./structured-mutations.js";
1
4
  import { type PmClientFullMutationOptions } from "./runtime.js";
2
5
  import { type CommitWorkspaceTransactionOptions,type WorkspaceTransactionJsonValue,type WorkspaceTransactionStep } from "./workspace-transaction.js";
3
6
  /**
4
7
  * One atomic item creation inside a bulk mutation batch. The explicit `id`
5
- * doubles as the idempotency key: recovery treats an existing item with this id
6
- * as the already-applied result, so ids must be stable and transaction-owned.
8
+ * doubles as the idempotency key: recovery adopts an existing item unless it
9
+ * remains closed after compensation. IDs must be stable and transaction-owned.
7
10
  */
8
11
  export interface BulkItemCreateMutation {
9
12
  /** Discriminates the creation operation. */
@@ -12,6 +15,54 @@ op:"create";
12
15
  id:string;
13
16
  /** Creation options forwarded to the public `create` runtime primitive. */
14
17
  options:PmClientFullMutationOptions;
18
+ /**
19
+ * Keyed-upsert guard re-checked under the writer lock. The planner resolves
20
+ * upsert matches before the lock, so a create row keeps the key it was
21
+ * planned against; the commit refuses with `upsert_key_conflict` when another
22
+ * writer created an item with the same key value after planning.
23
+ */
24
+ unique?:BulkItemUniqueKey;
25
+ }
26
+ /** Unique-key guard carried by a create row planned under keyed upsert. */
27
+ export interface BulkItemUniqueKey {
28
+ /** Item field (core or declared custom metadata key) the upsert planner matched on. */
29
+ key:string;
30
+ /** The row's own value for that field, compared on canonical content. */
31
+ value:unknown;
32
+ }
33
+ /** Schema facts a transaction needs, hydrated the same way whether or not the host scoped settings reads to configuration only. */
34
+ export interface TransactionSchemaContext {
35
+ /** Runtime schema with statuses, fields, and workflows merged from their files. */
36
+ schema:PmSettings["schema"];
37
+ /** Custom item types declared in the types file, when the settings read skipped hydration. */
38
+ typeDefinitionsFromFile:ItemTypeDefinition[];
39
+ }
40
+ /**
41
+ * Resolve the runtime schema for planning or guarding a transaction. A preview
42
+ * host may scope settings reads to inline configuration only (no schema
43
+ * hydration, no scaffolding), in which case declared custom fields and types
44
+ * live solely in their schema files; load them through the guarded reader so
45
+ * no symlink, special file, or out-of-root path is ever opened in place.
46
+ */
47
+ export declare function resolveTransactionSchema(pmRoot:string,settings:PmSettings):Promise<TransactionSchemaContext>;
48
+ /** Collect every existing item that carries a value for the upsert key, covering core and declared custom keys across custom-type folders. */
49
+ export declare function listUpsertKeyCandidates(pmRoot:string,settings:PmSettings,schemaContext:TransactionSchemaContext,key:string):Promise<ItemMutationUpsertCandidate[]>;
50
+ /** Per-transaction index of existing upsert-key values, scanned lazily under the writer lock. */
51
+ interface UniqueKeyIndex {
52
+ /** Existing item ids per canonical key value. */
53
+ lookup(key:string):Promise<Map<string,string[]>>;
54
+ /** Advance cached scans from the created item's metadata without another project scan. */
55
+ recordCreate(item:Readonly<Record<string,unknown>>):Promise<void>;
56
+ /** Drop cached scans after a step may have changed existing key values. */
57
+ invalidate():void;
58
+ }
59
+ /** Shared configuration for every step a bulk mutation batch builds. */
60
+ interface BulkMutationStepConfig {
61
+ pmRoot:string;
62
+ author:string;
63
+ transactionId:string;
64
+ createCompensation:"close" | "delete";
65
+ uniqueIndex:UniqueKeyIndex;
15
66
  }
16
67
  /** One atomic item update inside a bulk mutation batch. */
17
68
  export interface BulkItemUpdateMutation {
@@ -21,6 +72,13 @@ op:"update";
21
72
  id:string;
22
73
  /** Update options forwarded to the public `update` runtime primitive. */
23
74
  options:PmClientFullMutationOptions;
75
+ /**
76
+ * Keyed-upsert selection re-checked under the target item lock. The planner
77
+ * chose this target by key value before the lock; the commit checks the
78
+ * locked document and refuses with `upsert_match_changed` when the value was changed or
79
+ * removed after planning, so the update never lands on a mismatched item.
80
+ */
81
+ match?:BulkItemUniqueKey;
24
82
  }
25
83
  /** One atomic item closure inside a bulk mutation batch. */
26
84
  export interface BulkItemCloseMutation {
@@ -57,7 +115,8 @@ mutations:readonly BulkItemMutation[];
57
115
  /**
58
116
  * Compensation strategy for created items: `close` (default) preserves the
59
117
  * item and its history with an explanatory close reason, `delete` removes
60
- * the item document (its history stream is retained by `pm delete`).
118
+ * the item document (its history stream is retained by `pm delete`). A retry
119
+ * refuses a still-closed compensated creation until explicitly reopened.
61
120
  */
62
121
  createCompensation?:"close" | "delete";
63
122
  /** Lock lifetime in seconds; size this above the longest expected attempt. */
@@ -112,12 +171,7 @@ author:string;
112
171
  transactionId:string;
113
172
  },itemId:string,stepId:string,data:WorkspaceTransactionJsonValue | undefined):Promise<void>;
114
173
  /** Build the workspace-transaction step for one item creation. */
115
- declare function buildCreateStep(config:{
116
- pmRoot:string;
117
- author:string;
118
- transactionId:string;
119
- createCompensation:"close" | "delete";
120
- },mutation:BulkItemCreateMutation,stepId:string):WorkspaceTransactionStep;
174
+ declare function buildCreateStep(config:BulkMutationStepConfig,mutation:BulkItemCreateMutation,stepId:string):WorkspaceTransactionStep;
121
175
  /** Evidence and explicit limits of a non-writing semantic transaction preview. */
122
176
  export interface ItemMutationPreviewValidation {
123
177
  /** True when the coordinator executed staged validation; false for an already committed journal replay. */
@@ -127,6 +181,15 @@ state:"staged_snapshot" | "replayed_committed_plan";
127
181
  /** Preview leaves current commit state and executable extension effects unvalidated, including host-run pending migrations, mutation guards and hooks. */
128
182
  unresolved_commit_constraints:readonly string[];
129
183
  }
184
+ /**
185
+ * Load the runtime schema (statuses, fields, workflows, custom types) with the
186
+ * preview's guards instead of reading the configured files in place. Hosts
187
+ * that scope settings reads to inline configuration (dry-run planning) use
188
+ * this so declared fields stay visible without opening a symlink, FIFO, or
189
+ * out-of-root schema path; such inputs refuse with
190
+ * `transaction_preview_non_regular_file` or `transaction_preview_external_schema`.
191
+ */
192
+ export declare function loadGuardedRuntimeSchema(pmRoot:string,schemaSettings:Partial<PmSettings["schema"]> | undefined):Promise<Awaited<ReturnType<typeof loadRuntimeSchemaFromOptionalFiles>>>;
130
193
  /** Validate ordered mutations using apply's coordinator in a disposable tracker, without source writes, journals or extension hooks. */
131
194
  export declare function previewItemMutations(options:Pick<CommitItemMutationsOptions,"pmRoot" | "transactionId" | "author" | "mutations">):Promise<ItemMutationPreviewValidation>;
132
195
  /**
@@ -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]="7ff78f44-c9db-5221-b09a-32b78876b461")}catch{}})();import crypto from"node:crypto";import{constants}from"node:fs";import{isFileMissingError,readRegularFile,transactionPreviewNonRegularFileError}from"../core/fs/fs-utils.js";import{cp,lstat,mkdir,mkdtemp,open,readdir,realpath,rm,stat,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{getActiveExtensionRegistrations,setActiveExtensionRegistrations}from"../core/extensions/index.js";import path from"node:path";import{transferMutationStdinTokenPolicy}from"../core/item/parse.js";import{EXIT_CODE,PM_REQUIRED_SUBDIRS,SETTINGS_DEFAULTS,SETTINGS_FILENAME}from"../core/shared/constants.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,filePathForSchemaSection,loadRuntimeSchemaFromOptionalFiles,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{validateSettings}from"../core/store/settings-validator.js";import{resolveWorkspaceRoot}from"../core/store/paths.js";import{getSessionStatePath}from"../core/session/session-state.js";import{PmCliError}from"../core/shared/errors.js";import{stableStringify}from"../core/shared/serialization.js";import{readHistoryEntries}from"./history-read.js";import{PM_CONTEXT_INTENTS_FILE}from"./context-intent-runtime.js";import{close,create,deleteItem,get,release,restore,update,runWithActiveExtensions}from"./runtime.js";import{commitWorkspaceTransaction,validateWorkspaceTransactionIdentity}from"./workspace-transaction.js";function mergeTransactionMutationOptions(source,additions){const merged={...source,...additions};return source===void 0?merged:transferMutationStdinTokenPolicy(source,merged)}async function readItemSnapshot(pmRoot,id){try{const item=(await get(id,{},{pmRoot})).item;return{id:item.id,closedAt:item.closed_at,updatedAt:item.updated_at,assignee:item.assignee,claimPrincipal:item.claim_principal}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.NOT_FOUND)return;throw error}}function deriveStepId(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),fingerprint=crypto.createHash("sha256").update(stableStringify(mutation)).digest("hex").slice(0,12);return`${index+1}-${mutation.op}-${sanitizedTarget}-${fingerprint}`}function deriveOutcomeKey(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${index+1}-${mutation.op}-${sanitizedTarget}`}function bulkHistoryMarker(transactionId,stepId,phase){return`bulk-item-transaction ${transactionId} ${stepId} ${phase}`}async function isUpdateMarkerApplied(pmRoot,canonicalId,transactionId,stepId){const entries=await readHistoryEntries(path.join(pmRoot,"history",`${canonicalId}.jsonl`),canonicalId),applyMarker=bulkHistoryMarker(transactionId,stepId,"apply"),compensateMarker=bulkHistoryMarker(transactionId,stepId,"compensate");for(let index=entries.length-1;index>=0;index-=1){const message=entries[index].message;if(message===applyMarker)return!0;if(message===compensateMarker)return!1}return!1}async function prepareRestoreCompensation(pmRoot,mutation){const snapshot=await readItemSnapshot(pmRoot,mutation.id);if(snapshot?.updatedAt===void 0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} does not exist or has no restorable version`,EXIT_CODE.NOT_FOUND);return{target_updated_at:snapshot.updatedAt}}async function compensateByRestore(config,itemId,stepId,data){const target=data!==null&&typeof data=="object"&&!Array.isArray(data)?data.target_updated_at:void 0;typeof target=="string"&&await readItemSnapshot(config.pmRoot,itemId)!==void 0&&await restore(itemId,target,{force:!0,author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"compensate")},{pmRoot:config.pmRoot})}function buildCreateStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"create"}}},async apply(){const createdItem=(await create(mergeTransactionMutationOptions(mutation.options,{author:config.author,id:mutation.id}),{pmRoot:config.pmRoot})).item;return{id:String(createdItem.id),op:"create"}},async compensate(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);if(snapshot!==void 0){if(config.createCompensation==="delete"){await deleteItem(mutation.id,{force:!0,author:config.author,message:`Compensate interrupted bulk transaction ${config.transactionId}`},{pmRoot:config.pmRoot});return}snapshot.closedAt===void 0&&await close(mutation.id,`Compensated: interrupted bulk transaction ${config.transactionId}`,{force:!0,author:config.author},{pmRoot:config.pmRoot})}}}}function buildUpdateStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const updatedItem=(await update(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return{id:String(updatedItem.id),op:"update"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildCloseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"close"}}:snapshot.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"close"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const closedItem=(await close(mutation.id,mutation.reason,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return{id:String(closedItem.id),op:"close"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildReleaseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"release"}}:snapshot.assignee!==void 0||snapshot.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"release"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const releasedItem=(await release(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return{id:String(releasedItem.id),op:"release"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildStepForMutation(config,mutation,index){const stepId=deriveStepId(mutation,index);switch(mutation.op){case"create":return buildCreateStep(config,mutation,stepId);case"update":return buildUpdateStep(config,mutation,stepId);case"close":return buildCloseStep(config,mutation,stepId);case"release":return buildReleaseStep(config,mutation,stepId)}}function assertValidBulkMutation(mutation,index){if(mutation===null||typeof mutation!="object"||Array.isArray(mutation))throw new TypeError(`Bulk mutation ${index+1} must be an object`);if(!["create","update","close","release"].includes(mutation.op))throw new TypeError(`Bulk mutation ${index+1} op must be create, update, close, or release`);if(typeof mutation.id!="string"||mutation.id.trim().length===0)throw new TypeError(`Bulk mutation ${index+1} requires a non-empty id`);if(mutation.op==="close"&&(typeof mutation.reason!="string"||mutation.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${index+1} requires a non-empty reason`)}async function validateMutationOperation(mutation,index,run){try{return await run()}catch(error){throw error instanceof PmCliError?new PmCliError(error.message,error.exitCode,{...error.context,transaction_operation:{index,op:mutation.op,id:mutation.id}}):error}}function includePreviewPath(root,file,ownedPaths,retainedPaths){const relative=path.relative(root,file);return["locks","runtime","search"].includes(relative.split(path.sep)[0])?retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`)):relative===""||ownedPaths===void 0||ownedPaths.some(owned=>relative===owned||relative.startsWith(`${owned}${path.sep}`)||owned.startsWith(`${relative}${path.sep}`))}async function previewEntryStat(file){const entry=await lstat(file);if(entry.isSymbolicLink())await stat(file);else if(entry.isDirectory()||entry.isFile())return entry;throw transactionPreviewNonRegularFileError()}async function previewFileDigest(file){const handle=await open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const entry=await handle.stat();if(!entry.isFile())throw transactionPreviewNonRegularFileError();const contents=crypto.createHash("sha256");if(entry.size>0)for await(const chunk of handle.createReadStream({highWaterMark:64*1024,end:entry.size-1,autoClose:!1}))contents.update(chunk);return contents.digest()}finally{await handle.close()}}async function previewTrackerFingerprint(root,ownedPaths,retainedPaths){const fingerprint=crypto.createHash("sha256");async function visit(directory){for(const name of(await readdir(directory)).sort()){const file=path.join(directory,name);includePreviewPath(root,file,ownedPaths,retainedPaths)&&((await previewEntryStat(file)).isDirectory()?await visit(file):(fingerprint.update(JSON.stringify(path.relative(root,file))),fingerprint.update(await previewFileDigest(file))))}}return await visit(root),fingerprint.digest("hex")}function previewSnapshotChangedError(){return new PmCliError("Tracker changed while preparing the transaction preview; retry against stable state.",EXIT_CODE.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function isDisappearingPreviewPath(error){if(!isFileMissingError(error))return!1;const file=error.path;if(typeof file!="string")return!1;const original=path.resolve(file);let candidate=original;for(;;)try{const entry=await lstat(candidate);return candidate!==original&&entry.isDirectory()}catch(lookupError){if(!isFileMissingError(lookupError))return!1;const parent=path.dirname(candidate);if(parent===candidate)return!1;candidate=parent}}async function readPreviewConfiguration(root,relative){const file=path.join(root,relative);try{let current=root;for(const component of relative.split(path.sep).slice(0,-1))current=path.join(current,component),await previewEntryStat(current);if(!(await previewEntryStat(file)).isFile())throw transactionPreviewNonRegularFileError();return await readRegularFile(file,transactionPreviewNonRegularFileError())}catch(error){if(await isDisappearingPreviewPath(error))return;throw error}}async function resolvePreviewStorage(root,configurationRoot,registrations){const configuration=new Map,rawSettings=await readPreviewConfiguration(root,SETTINGS_FILENAME);configuration.set(SETTINGS_FILENAME,rawSettings);let parsed;try{parsed=JSON.parse(rawSettings??"null")}catch{parsed=null}const validated=validateSettings(parsed),settings=validated.success?validated.data:void 0,schema=normalizeRuntimeSchemaSettings(settings?.schema);for(const[section,configuredPath]of Object.entries(schema.files)){const relative=path.relative(root,filePathForSchemaSection(root,configuredPath,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS[section]));if(relative===""||!path.resolve(root,relative).startsWith(path.join(root,path.sep)))throw new PmCliError("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",EXIT_CODE.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${section}`});schema.files[section]=relative;const contents=await readPreviewConfiguration(root,relative);if(configuration.set(relative,contents),contents!==void 0){const target=path.join(configurationRoot,relative);await mkdir(path.dirname(target),{recursive:!0}),await writeFile(target,contents)}}const sessionPath=path.relative(root,getSessionStatePath(root));configuration.set(sessionPath,await readPreviewConfiguration(root,sessionPath));const loaded=await loadRuntimeSchemaFromOptionalFiles(configurationRoot,schema),registry=resolveItemTypeRegistry({...SETTINGS_DEFAULTS,item_types:{definitions:[...settings?.item_types?.definitions??[],...loaded.type_definitions_from_file??[]]}},registrations),ownedPaths=resolveWorkspaceRoot(root)===root?[...PM_REQUIRED_SUBDIRS.filter(Boolean),SETTINGS_FILENAME,PM_CONTEXT_INTENTS_FILE,"transactions",...registry.folders,...configuration.keys()].map(entry=>path.normalize(entry)):void 0,stagedSettings=settings===void 0?void 0:JSON.stringify({...parsed,schema:{...settings.schema,files:schema.files}});return{configuration,ownedPaths,stagedSettings,registryFolders:registry.folders}}async function stagePreviewTracker(sourceRoot,stagedRoot,registrations){await stat(sourceRoot);try{const resolvedRoot=await realpath(sourceRoot),storage=await resolvePreviewStorage(resolvedRoot,path.join(path.dirname(stagedRoot),"configuration"),registrations),retainedPaths=[...storage.configuration.keys(),...storage.registryFolders].map(entry=>path.normalize(entry)),sourceFingerprint=await previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths);await cp(resolvedRoot,stagedRoot,{recursive:!0,dereference:!1,filter:async source=>includePreviewPath(resolvedRoot,source,storage.ownedPaths,retainedPaths)?(await previewEntryStat(source),!0):!1});const[currentFingerprint,stagedFingerprint]=await Promise.all([previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths),previewTrackerFingerprint(stagedRoot,storage.ownedPaths,retainedPaths)]);if(sourceFingerprint!==currentFingerprint||sourceFingerprint!==stagedFingerprint)throw previewSnapshotChangedError();for(const[relative,contents]of storage.configuration)if(await readPreviewConfiguration(stagedRoot,relative)!==contents)throw previewSnapshotChangedError();storage.stagedSettings!==void 0&&await writeFile(path.join(stagedRoot,SETTINGS_FILENAME),storage.stagedSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}}async function previewItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=[...options.mutations];if(mutations.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");for(const[index,mutation]of mutations.entries())assertValidBulkMutation(mutation,index);const registrations=getActiveExtensionRegistrations(),root=await mkdtemp(path.join(tmpdir(),"pm-transaction-preview-")),stagedRoot=path.join(root,"tracker");try{await stagePreviewTracker(identity.pmRoot,stagedRoot,registrations);let validated=!1;return await runWithActiveExtensions({path:stagedRoot,noExtensions:!0},async()=>{setActiveExtensionRegistrations(registrations);const config={...identity,pmRoot:stagedRoot,createCompensation:"close"},steps=mutations.map((mutation,index)=>{const step=buildStepForMutation(config,mutation,index);return{...step,inspect:()=>validateMutationOperation(mutation,index,()=>step.inspect()),prepareCompensation:()=>validateMutationOperation(mutation,index,async()=>step.prepareCompensation?.()),apply:()=>validateMutationOperation(mutation,index,()=>step.apply())}});await commitWorkspaceTransaction({...identity,pmRoot:stagedRoot,steps,onTransition:({transition})=>{transition==="committed"&&(validated=!0)}})}),{validated,state:validated?"staged_snapshot":"replayed_committed_plan",unresolved_commit_constraints:["concurrent_tracker_changes","extension_mutation_guards_and_hooks"]}}finally{await rm(root,{recursive:!0,force:!0})}}async function commitItemMutations(options){const mutations=[...options.mutations];if(mutations.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");for(const[index,mutation]of mutations.entries())assertValidBulkMutation(mutation,index);const createCompensation=options.createCompensation??"close";if(!["close","delete"].includes(createCompensation))throw new TypeError("Bulk item transaction createCompensation must be close or delete");const stepConfig={pmRoot:options.pmRoot,author:options.author,transactionId:options.transactionId,createCompensation},committed=await commitWorkspaceTransaction({pmRoot:options.pmRoot,transactionId:options.transactionId,author:options.author,steps:mutations.map((mutation,index)=>buildStepForMutation(stepConfig,mutation,index)),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}}),results={};for(const[index,mutation]of mutations.entries()){const stepId=deriveStepId(mutation,index),value=committed.results[stepId];results[deriveOutcomeKey(mutation,index)]=value}return{transactionId:committed.transactionId,status:"committed",recovered:committed.recovered,results}}function buildItemCompletionMutations(options){const mutations=[];return options.evidence!==void 0&&Object.keys(options.evidence).length>0&&mutations.push({op:"update",id:options.id,options:options.evidence}),mutations.push({op:"close",id:options.id,reason:options.reason,...options.closeOptions===void 0?{}:{options:options.closeOptions}},{op:"release",id:options.id,...options.releaseOptions===void 0?{}:{options:options.releaseOptions}}),mutations}function commitItemCompletion(options){return commitItemMutations({pmRoot:options.pmRoot,transactionId:options.transactionId,author:options.author,mutations:buildItemCompletionMutations(options),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}})}const _testOnlyItemTransaction={buildCreateStep,bulkHistoryMarker,compensateByRestore,deriveStepId,isUpdateMarkerApplied,readItemSnapshot};export{_testOnlyItemTransaction,buildItemCompletionMutations,commitItemCompletion,commitItemMutations,previewItemMutations};
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]="03112259-10b6-53a9-8e6b-e541ac8c7d5d")}catch{}})();import crypto from"node:crypto";import{constants}from"node:fs";import{isFileMissingError,readRegularFile,transactionPreviewNonRegularFileError}from"../core/fs/fs-utils.js";import{cp,lstat,mkdir,mkdtemp,open,readdir,realpath,rm,stat,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{getActiveExtensionRegistrations,setActiveExtensionRegistrations}from"../core/extensions/index.js";import path from"node:path";import{transferMutationStdinTokenPolicy}from"../core/item/parse.js";import{EXIT_CODE,PM_REQUIRED_SUBDIRS,SETTINGS_DEFAULTS,SETTINGS_FILENAME}from"../core/shared/constants.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{listAllItemMetadataLight}from"../core/store/item-store.js";import{runWithItemMutationPrecondition}from"../core/store/item-mutation-precondition.js";import{isConfigurationOnlySettingsRead,readSettings}from"../core/store/settings.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,filePathForSchemaSection,loadRuntimeSchemaFromOptionalFiles,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{validateSettings}from"../core/store/settings-validator.js";import{resolveWorkspaceRoot}from"../core/store/paths.js";import{getSessionStatePath}from"../core/session/session-state.js";import{PmCliError}from"../core/shared/errors.js";import{stableUpsertValue}from"./structured-mutations.js";import{stableStringify}from"../core/shared/serialization.js";import{assertMutationOptionValueTypes}from"./lifecycle/mutation-option-validation.js";import{readHistoryEntries}from"./history-read.js";import{PM_CONTEXT_INTENTS_FILE}from"./context-intent-runtime.js";import{close,create,deleteItem,get,release,restore,update,runWithActiveExtensions}from"./runtime.js";import{commitWorkspaceTransaction,validateWorkspaceTransactionIdentity}from"./workspace-transaction.js";async function resolveTransactionSchema(pmRoot,settings){if(!isConfigurationOnlySettingsRead(pmRoot))return{schema:normalizeRuntimeSchemaSettings(settings.schema),typeDefinitionsFromFile:[]};const loaded=await loadGuardedRuntimeSchema(pmRoot,settings.schema);return{schema:loaded.schema,typeDefinitionsFromFile:loaded.type_definitions_from_file??[]}}async function listUpsertKeyCandidates(pmRoot,settings,schemaContext,key){const typeRegistry=resolveItemTypeRegistry({...settings,item_types:{...settings.item_types,definitions:[...settings.item_types?.definitions??[],...schemaContext.typeDefinitionsFromFile]}},getActiveExtensionRegistrations());return(await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,schemaContext.schema)).flatMap(item=>{const value=item[key];return value==null?[]:[{id:item.id,value}]})}function createUniqueKeyIndex(pmRoot){const scans=new Map,scan=async key=>{const settings=await readSettings(pmRoot),schemaContext=await resolveTransactionSchema(pmRoot,settings),byValue=new Map;for(const candidate of await listUpsertKeyCandidates(pmRoot,settings,schemaContext,key)){const stable=stableUpsertValue(candidate.value);byValue.set(stable,[...byValue.get(stable)??[],candidate.id])}return byValue};return{lookup(key){const pending=scans.get(key)??scan(key);return scans.set(key,pending),pending},async recordCreate(item){for(const[key,pending]of scans){const value=item[key];if(value==null)continue;const byValue=await pending,stable=stableUpsertValue(value);byValue.set(stable,[...byValue.get(stable)??[],String(item.id)])}},invalidate(){scans.clear()}}}async function assertUniqueKeyFree(index,unique){const stable=stableUpsertValue(unique.value),existing=(await index.lookup(unique.key)).get(stable)??[];if(existing.length!==0)throw new PmCliError(`Upsert key "${unique.key}" value ${JSON.stringify(stable)} now matches existing item ${existing.join(", ")}; the plan was resolved before it existed.`,EXIT_CODE.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function assertUpsertMatchCurrent(document,id,match){const current=document.metadata[match.key],expected=stableUpsertValue(match.value);if(stableUpsertValue(current)!==expected)throw new PmCliError(`Item ${id} no longer carries upsert key "${match.key}" value ${JSON.stringify(expected)}; the plan selected it before the key changed.`,EXIT_CODE.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function isValidUniqueKey(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;const candidate=value;return typeof candidate.key=="string"&&candidate.key.trim().length>0&&candidate.value!==void 0&&candidate.value!==null}function mergeTransactionMutationOptions(source,additions){const merged={...source,...additions};return source===void 0?merged:transferMutationStdinTokenPolicy(source,merged)}async function readItemSnapshot(pmRoot,id){try{const item=(await get(id,{},{pmRoot})).item;return{id:item.id,closedAt:item.closed_at,updatedAt:item.updated_at,assignee:item.assignee,claimPrincipal:item.claim_principal}}catch(error){if(error instanceof PmCliError&&error.exitCode===EXIT_CODE.NOT_FOUND)return;throw error}}function deriveStepId(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),fingerprint=crypto.createHash("sha256").update(stableStringify(mutation)).digest("hex").slice(0,12);return`${index+1}-${mutation.op}-${sanitizedTarget}-${fingerprint}`}function deriveOutcomeKey(mutation,index){const sanitizedTarget=mutation.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${index+1}-${mutation.op}-${sanitizedTarget}`}function bulkHistoryMarker(transactionId,stepId,phase){return`bulk-item-transaction ${transactionId} ${stepId} ${phase}`}async function isUpdateMarkerApplied(pmRoot,canonicalId,transactionId,stepId){const entries=await readHistoryEntries(path.join(pmRoot,"history",`${canonicalId}.jsonl`),canonicalId),applyMarker=bulkHistoryMarker(transactionId,stepId,"apply"),compensateMarker=bulkHistoryMarker(transactionId,stepId,"compensate");for(let index=entries.length-1;index>=0;index-=1){const message=entries[index].message;if(message===applyMarker)return!0;if(message===compensateMarker)return!1}return!1}async function prepareRestoreCompensation(pmRoot,mutation){const snapshot=await readItemSnapshot(pmRoot,mutation.id);if(snapshot?.updatedAt===void 0)throw new PmCliError(`Bulk ${mutation.op} target ${mutation.id} does not exist or has no restorable version`,EXIT_CODE.NOT_FOUND);return{target_updated_at:snapshot.updatedAt}}async function compensateByRestore(config,itemId,stepId,data){const target=data!==null&&typeof data=="object"&&!Array.isArray(data)?data.target_updated_at:void 0;typeof target=="string"&&await readItemSnapshot(config.pmRoot,itemId)!==void 0&&await restore(itemId,target,{force:!0,author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"compensate")},{pmRoot:config.pmRoot})}function buildCreateStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);if(snapshot===void 0)return{state:"pending"};if(snapshot.closedAt!==void 0){const history=await readHistoryEntries(path.join(config.pmRoot,"history",`${snapshot.id}.jsonl`),snapshot.id),reason=`Compensated: interrupted bulk transaction ${config.transactionId}`;if(history.filter(entry=>entry.op==="close").at(-1)?.patch.some(change=>change.op==="add"||change.op==="replace"?change.path==="/metadata/close_reason"&&change.value===reason:!1)??!1)throw new PmCliError(`Created item ${snapshot.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,EXIT_CODE.CONFLICT,{code:"transaction_create_compensated",item_id:snapshot.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${snapshot.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:snapshot.id,op:"create"}}},async apply(){mutation.unique!==void 0&&await assertUniqueKeyFree(config.uniqueIndex,mutation.unique);const createdItem=(await create(mergeTransactionMutationOptions(mutation.options,{author:config.author,id:mutation.id}),{pmRoot:config.pmRoot})).item;return await config.uniqueIndex.recordCreate(createdItem),{id:String(createdItem.id),op:"create"}},async compensate(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);if(snapshot!==void 0){if(config.createCompensation==="delete"){await deleteItem(mutation.id,{force:!0,author:config.author,message:`Compensate interrupted bulk transaction ${config.transactionId}`},{pmRoot:config.pmRoot});return}snapshot.closedAt===void 0&&await close(mutation.id,`Compensated: interrupted bulk transaction ${config.transactionId}`,{force:!0,author:config.author},{pmRoot:config.pmRoot})}}}}function buildUpdateStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const applyUpdate=()=>update(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot}),match=mutation.match,updatedItem=(match===void 0?await applyUpdate():await runWithItemMutationPrecondition({pmRoot:config.pmRoot,id:String((await get(mutation.id,{},{pmRoot:config.pmRoot})).item.id),validate:document=>assertUpsertMatchCurrent(document,mutation.id,match)},applyUpdate)).item;return config.uniqueIndex.invalidate(),{id:String(updatedItem.id),op:"update"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildCloseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"close"}}:snapshot.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"close"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const closedItem=(await close(mutation.id,mutation.reason,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(closedItem.id),op:"close"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildReleaseStep(config,mutation,stepId){return{id:stepId,async inspect(){const snapshot=await readItemSnapshot(config.pmRoot,mutation.id);return snapshot===void 0?{state:"pending"}:await isUpdateMarkerApplied(config.pmRoot,snapshot.id,config.transactionId,stepId)?{state:"applied",result:{id:snapshot.id,op:"release"}}:snapshot.assignee!==void 0||snapshot.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:snapshot.id,op:"release"}}},async prepareCompensation(){return prepareRestoreCompensation(config.pmRoot,mutation)},async apply(){const releasedItem=(await release(mutation.id,mergeTransactionMutationOptions(mutation.options,{author:config.author,message:bulkHistoryMarker(config.transactionId,stepId,"apply")}),{pmRoot:config.pmRoot})).item;return config.uniqueIndex.invalidate(),{id:String(releasedItem.id),op:"release"}},async compensate(data){await compensateByRestore(config,mutation.id,stepId,data)}}}function buildStepForMutation(config,mutation,index){const stepId=deriveStepId(mutation,index);switch(mutation.op){case"create":return buildCreateStep(config,mutation,stepId);case"update":return buildUpdateStep(config,mutation,stepId);case"close":return buildCloseStep(config,mutation,stepId);case"release":return buildReleaseStep(config,mutation,stepId)}}function assertValidBulkMutation(mutation,index){if(mutation===null||typeof mutation!="object"||Array.isArray(mutation))throw new TypeError(`Bulk mutation ${index+1} must be an object`);if(!["create","update","close","release"].includes(mutation.op))throw new TypeError(`Bulk mutation ${index+1} op must be create, update, close, or release`);if(typeof mutation.id!="string"||mutation.id.trim().length===0)throw new TypeError(`Bulk mutation ${index+1} requires a non-empty id`);if(mutation.op==="close"&&(typeof mutation.reason!="string"||mutation.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${index+1} requires a non-empty reason`);if(mutation.op==="create"&&mutation.unique!==void 0&&!isValidUniqueKey(mutation.unique))throw new TypeError(`Bulk create mutation ${index+1} unique must be an object with a non-empty key and a value`);if(mutation.op==="update"&&mutation.match!==void 0&&!isValidUniqueKey(mutation.match))throw new TypeError(`Bulk update mutation ${index+1} match must be an object with a non-empty key and a value`);assertMutationOptionValueTypes(mutation.options,mutation.op,index)}function assertValidBulkMutations(mutations){if(mutations.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");const keys=new Map;for(const[index,mutation]of mutations.entries()){if(assertValidBulkMutation(mutation,index),mutation.op!=="create"||mutation.unique===void 0)continue;const{key,value}=mutation.unique,values=keys.get(key)??new Map,stable=stableUpsertValue(value),previous=values.get(stable);if(previous!==void 0)throw new PmCliError(`Bulk create mutations ${previous+1} and ${index+1} share the upsert key value ${JSON.stringify(stable)} for "${key}".`,EXIT_CODE.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});values.set(stable,index),keys.set(key,values)}}async function validateMutationOperation(mutation,index,run){try{return await run()}catch(error){throw error instanceof PmCliError?new PmCliError(error.message,error.exitCode,{...error.context,transaction_operation:{index,op:mutation.op,id:mutation.id}}):error}}function includePreviewPath(root,file,ownedPaths,retainedPaths){const relative=path.relative(root,file);return["locks","runtime","search"].includes(relative.split(path.sep)[0])?retainedPaths.some(retained=>relative===retained||relative.startsWith(`${retained}${path.sep}`)||retained.startsWith(`${relative}${path.sep}`)):relative===""||ownedPaths===void 0||ownedPaths.some(owned=>relative===owned||relative.startsWith(`${owned}${path.sep}`)||owned.startsWith(`${relative}${path.sep}`))}async function previewEntryStat(file){const entry=await lstat(file);if(entry.isSymbolicLink())await stat(file);else if(entry.isDirectory()||entry.isFile())return entry;throw transactionPreviewNonRegularFileError()}async function previewFileDigest(file){const handle=await open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const entry=await handle.stat();if(!entry.isFile())throw transactionPreviewNonRegularFileError();const contents=crypto.createHash("sha256");if(entry.size>0)for await(const chunk of handle.createReadStream({highWaterMark:64*1024,end:entry.size-1,autoClose:!1}))contents.update(chunk);return contents.digest()}finally{await handle.close()}}async function previewTrackerFingerprint(root,ownedPaths,retainedPaths){const fingerprint=crypto.createHash("sha256");async function visit(directory){for(const name of(await readdir(directory)).sort()){const file=path.join(directory,name);includePreviewPath(root,file,ownedPaths,retainedPaths)&&((await previewEntryStat(file)).isDirectory()?await visit(file):(fingerprint.update(JSON.stringify(path.relative(root,file))),fingerprint.update(await previewFileDigest(file))))}}return await visit(root),fingerprint.digest("hex")}function previewSnapshotChangedError(){return new PmCliError("Tracker changed while preparing the transaction preview; retry against stable state.",EXIT_CODE.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function isDisappearingPreviewPath(error){if(!isFileMissingError(error))return!1;const file=error.path;if(typeof file!="string")return!1;const original=path.resolve(file);let candidate=original;for(;;)try{const entry=await lstat(candidate);return candidate!==original&&entry.isDirectory()}catch(lookupError){if(!isFileMissingError(lookupError))return!1;const parent=path.dirname(candidate);if(parent===candidate)return!1;candidate=parent}}async function readPreviewConfiguration(root,relative){const file=path.join(root,relative);try{let current=root;for(const component of relative.split(path.sep).slice(0,-1))current=path.join(current,component),await previewEntryStat(current);if(!(await previewEntryStat(file)).isFile())throw transactionPreviewNonRegularFileError();return await readRegularFile(file,transactionPreviewNonRegularFileError())}catch(error){if(await isDisappearingPreviewPath(error))return;throw error}}async function stageGuardedSchemaSections(root,configurationRoot,schemaSettings,configuration){const schema=normalizeRuntimeSchemaSettings(schemaSettings);for(const[section,configuredPath]of Object.entries(schema.files)){const relative=path.relative(root,filePathForSchemaSection(root,configuredPath,DEFAULT_RUNTIME_SCHEMA_FILE_PATHS[section]));if(relative===""||!path.resolve(root,relative).startsWith(path.join(root,path.sep)))throw new PmCliError("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",EXIT_CODE.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${section}`});schema.files[section]=relative;const contents=await readPreviewConfiguration(root,relative);if(configuration?.set(relative,contents),contents!==void 0){const target=path.join(configurationRoot,relative);await mkdir(path.dirname(target),{recursive:!0}),await writeFile(target,contents)}}return loadRuntimeSchemaFromOptionalFiles(configurationRoot,schema)}async function loadGuardedRuntimeSchema(pmRoot,schemaSettings){await stat(pmRoot);const root=await mkdtemp(path.join(tmpdir(),"pm-schema-plan-"));try{const resolvedRoot=await realpath(pmRoot);return await stageGuardedSchemaSections(resolvedRoot,path.join(root,"configuration"),schemaSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}finally{await rm(root,{recursive:!0,force:!0})}}async function resolvePreviewStorage(root,configurationRoot,registrations){const configuration=new Map,rawSettings=await readPreviewConfiguration(root,SETTINGS_FILENAME);configuration.set(SETTINGS_FILENAME,rawSettings);let parsed;try{parsed=JSON.parse(rawSettings??"null")}catch{parsed=null}const validated=validateSettings(parsed),settings=validated.success?validated.data:void 0,loaded=await stageGuardedSchemaSections(root,configurationRoot,settings?.schema,configuration),schema=loaded.schema,sessionPath=path.relative(root,getSessionStatePath(root));configuration.set(sessionPath,await readPreviewConfiguration(root,sessionPath));const registry=resolveItemTypeRegistry({...SETTINGS_DEFAULTS,item_types:{definitions:[...settings?.item_types?.definitions??[],...loaded.type_definitions_from_file??[]]}},registrations),ownedPaths=resolveWorkspaceRoot(root)===root?[...PM_REQUIRED_SUBDIRS.filter(Boolean),SETTINGS_FILENAME,PM_CONTEXT_INTENTS_FILE,"transactions",...registry.folders,...configuration.keys()].map(entry=>path.normalize(entry)):void 0,stagedSettings=settings===void 0?void 0:JSON.stringify({...parsed,schema:{...settings.schema,files:schema.files}});return{configuration,ownedPaths,stagedSettings,registryFolders:registry.folders}}async function stagePreviewTracker(sourceRoot,stagedRoot,registrations){await stat(sourceRoot);try{const resolvedRoot=await realpath(sourceRoot),storage=await resolvePreviewStorage(resolvedRoot,path.join(path.dirname(stagedRoot),"configuration"),registrations),retainedPaths=[...storage.configuration.keys(),...storage.registryFolders].map(entry=>path.normalize(entry)),sourceFingerprint=await previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths);await cp(resolvedRoot,stagedRoot,{recursive:!0,dereference:!1,filter:async source=>includePreviewPath(resolvedRoot,source,storage.ownedPaths,retainedPaths)?(await previewEntryStat(source),!0):!1});const[currentFingerprint,stagedFingerprint]=await Promise.all([previewTrackerFingerprint(resolvedRoot,storage.ownedPaths,retainedPaths),previewTrackerFingerprint(stagedRoot,storage.ownedPaths,retainedPaths)]);if(sourceFingerprint!==currentFingerprint||sourceFingerprint!==stagedFingerprint)throw previewSnapshotChangedError();for(const[relative,contents]of storage.configuration)if(await readPreviewConfiguration(stagedRoot,relative)!==contents)throw previewSnapshotChangedError();storage.stagedSettings!==void 0&&await writeFile(path.join(stagedRoot,SETTINGS_FILENAME),storage.stagedSettings)}catch(error){throw await isDisappearingPreviewPath(error)?previewSnapshotChangedError():error}}async function previewItemMutations(options){const identity=validateWorkspaceTransactionIdentity(options),mutations=[...options.mutations];assertValidBulkMutations(mutations);const registrations=getActiveExtensionRegistrations(),root=await mkdtemp(path.join(tmpdir(),"pm-transaction-preview-")),stagedRoot=path.join(root,"tracker");try{await stagePreviewTracker(identity.pmRoot,stagedRoot,registrations);let validated=!1;return await runWithActiveExtensions({path:stagedRoot,noExtensions:!0},async()=>{setActiveExtensionRegistrations(registrations);const config={...identity,pmRoot:stagedRoot,createCompensation:"close",uniqueIndex:createUniqueKeyIndex(stagedRoot)},steps=mutations.map((mutation,index)=>{const step=buildStepForMutation(config,mutation,index);return{...step,inspect:()=>validateMutationOperation(mutation,index,()=>step.inspect()),prepareCompensation:()=>validateMutationOperation(mutation,index,async()=>step.prepareCompensation?.()),apply:()=>validateMutationOperation(mutation,index,()=>step.apply())}});await commitWorkspaceTransaction({...identity,pmRoot:stagedRoot,steps,onTransition:({transition})=>{transition==="committed"&&(validated=!0)}})}),{validated,state:validated?"staged_snapshot":"replayed_committed_plan",unresolved_commit_constraints:["concurrent_tracker_changes","extension_mutation_guards_and_hooks"]}}finally{await rm(root,{recursive:!0,force:!0})}}async function commitItemMutations(options){const mutations=[...options.mutations];assertValidBulkMutations(mutations);const createCompensation=options.createCompensation??"close";if(!["close","delete"].includes(createCompensation))throw new TypeError("Bulk item transaction createCompensation must be close or delete");const stepConfig={pmRoot:options.pmRoot,author:options.author,transactionId:options.transactionId,createCompensation,uniqueIndex:createUniqueKeyIndex(options.pmRoot)},committed=await commitWorkspaceTransaction({pmRoot:options.pmRoot,transactionId:options.transactionId,author:options.author,steps:mutations.map((mutation,index)=>buildStepForMutation(stepConfig,mutation,index)),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}}),results={};for(const[index,mutation]of mutations.entries()){const stepId=deriveStepId(mutation,index),value=committed.results[stepId];results[deriveOutcomeKey(mutation,index)]=value}return{transactionId:committed.transactionId,status:"committed",recovered:committed.recovered,results}}function buildItemCompletionMutations(options){const mutations=[];return options.evidence!==void 0&&Object.keys(options.evidence).length>0&&mutations.push({op:"update",id:options.id,options:options.evidence}),mutations.push({op:"close",id:options.id,reason:options.reason,...options.closeOptions===void 0?{}:{options:options.closeOptions}},{op:"release",id:options.id,...options.releaseOptions===void 0?{}:{options:options.releaseOptions}}),mutations}function commitItemCompletion(options){return commitItemMutations({pmRoot:options.pmRoot,transactionId:options.transactionId,author:options.author,mutations:buildItemCompletionMutations(options),...options.lockTtlSeconds===void 0?{}:{lockTtlSeconds:options.lockTtlSeconds},...options.lockWaitMs===void 0?{}:{lockWaitMs:options.lockWaitMs},...options.onTransition===void 0?{}:{onTransition:options.onTransition}})}const _testOnlyItemTransaction={buildCreateStep,bulkHistoryMarker,compensateByRestore,deriveStepId,isUpdateMarkerApplied,readItemSnapshot};export{_testOnlyItemTransaction,buildItemCompletionMutations,commitItemCompletion,commitItemMutations,listUpsertKeyCandidates,loadGuardedRuntimeSchema,previewItemMutations,resolveTransactionSchema};
2
2
  //# sourceMappingURL=item-transaction.js.map
@@ -70,6 +70,15 @@ forced:boolean;
70
70
  warnings?:string[];
71
71
  /** Concrete recovery commands when releasing ownership leaves work in progress. */
72
72
  suggestions?:string[];
73
+ /** Evidence and queue transition recorded with the ownership release. */
74
+ handoff?:{
75
+ /** Lifecycle status observed under the item lock. */
76
+ from_status:string;
77
+ /** Project-defined queue receiving the unclaimed work. */
78
+ to_status:string;
79
+ /** Author-supplied evidence retained in the release history event. */
80
+ message:string;
81
+ };
73
82
  }
74
83
  /** Documents the claim mutation options payload exchanged by command, SDK, and package integrations. */
75
84
  export interface ClaimMutationOptions {
@@ -83,7 +92,12 @@ ifAvailable?:boolean;
83
92
  maxAttempts?:string | number;
84
93
  }
85
94
  /** Documents the release mutation options payload exchanged by command, SDK, and package integrations. */
86
- export type ReleaseMutationOptions = ClaimMutationOptions;
95
+ export interface ReleaseMutationOptions extends ClaimMutationOptions {
96
+ /** Configured non-terminal queue to enter atomically with release. */
97
+ handoff?:string;
98
+ /** Pause composition, mutually exclusive with a handoff queue. */
99
+ pause?:boolean;
100
+ }
87
101
  /** Implements run claim for the public runtime surface of this module. */
88
102
  export declare function runClaim(id:string,force:boolean,global:GlobalOptions,options?:ClaimMutationOptions):Promise<ClaimResult>;
89
103
  /** Selects ranked actionable work and claims the first candidate still available under the item lock. Conflicts caused by parallel claimers advance to the next candidate instead of returning a thundering-herd failure. */
@@ -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]="ce03100c-3a4f-5ce4-a216-a3fabcfc655e")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{resolveRuntimeStatusRegistry,statusIsTerminal,EXIT_CODE,PmCliError,toItemRecord,mutateItem,resolvePmRoot,readSettings,resolveAuthor,resolveClaimPrincipal,normalizeStatusForRegistry}from"../runtime-primitives.js";import{wrapOwnershipConflict}from"../annotations.js";import{describeItemOwnershipConflict}from"../ownership-source.js";import{runNext}from"../query/next.js";import{recordClaimSemanticAttribution,recordReleaseSemanticAttribution}from"../context/semantic-session-attribution.js";const NO_AVAILABLE_NEXT_ITEM_CODE="no_available_next_item";function isAlreadyClaimedError(error){if(!(error instanceof Error)||error.name!=="PmCliError")return!1;const context=error.context;return typeof context=="object"&&context!==null&&"code"in context&&context.code==="already_claimed_by"}async function runClaim(id,force,global2,options={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),author=resolveAuthor(options.author,settings.author_default),claimPrincipal=resolveClaimPrincipal(author);let previousAssignee=null,skipped=!1;const mutationWarnings=[],result=await mutateItem({pmRoot,settings,id,op:"claim",author,message:options.message,force,skipNoop:!0,async mutate(document){const currentAssigneeText=document.metadata.assignee??"",currentClaimPrincipal=document.metadata.claim_principal?.trim()||currentAssigneeText;if(previousAssignee=currentAssigneeText.trim().length>0?currentAssigneeText:null,statusIsTerminal(document.metadata.status,statusRegistry)&&!force)throw new PmCliError(`Cannot claim terminal item ${document.metadata.id} without --force`,EXIT_CODE.CONFLICT);if(previousAssignee!==null&&currentClaimPrincipal!==claimPrincipal){if(options.ifAvailable===!0)return skipped=!0,mutationWarnings.push(`claim_skipped_held_by:${previousAssignee}`),{changedFields:[]};if(!force){const ownershipPhrase=await describeItemOwnershipConflict(pmRoot,document.metadata.id,currentAssigneeText);throw new PmCliError(`Item ${document.metadata.id} is already ${ownershipPhrase}. Use --force to take over, or --if-available to skip without failing.`,EXIT_CODE.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}mutationWarnings.push(`claim_takeover:${previousAssignee}->${author}`)}const ownership={assignee:author,claim_principal:claimPrincipal},changedFields=["assignee","claim_principal"].filter(field=>document.metadata[field]!==ownership[field]);return Object.assign(document.metadata,ownership),{changedFields,warnings:mutationWarnings}}});return skipped||await recordClaimSemanticAttribution({pmRoot,settings,principal:claimPrincipal,itemId:result.item.id}),{item:toItemRecord(result.item),changed_fields:result.changedFields,claimed_by:skipped&&previousAssignee!==null?previousAssignee:author,previous_assignee:previousAssignee,forced:force,...skipped?{skipped:!0}:{},...mutationWarnings.length>0?{warnings:mutationWarnings}:{}}}async function runClaimNext(force,global2,options={},nextOptions={}){const maxAttempts=parseClaimNextAttempts(options.maxAttempts),settings=await readSettings(resolvePmRoot(process.cwd(),global2.path)),claimOptions={...options,author:resolveAuthor(options.author,settings.author_default)},next=await runNext({...nextOptions,callerAuthor:claimOptions.author,limit:String(maxAttempts)},global2),recommendations=[next.recommended,...next.ready].filter(entry=>entry!==null).map(entry=>({...entry,reasons:"reasons"in entry?entry.reasons:["ranked ready candidate"]}));return claimNextFromRecommendations(recommendations.slice(0,maxAttempts),force,global2,claimOptions)}function parseClaimNextAttempts(raw){if(raw===void 0)return 10;const parsed=Number(raw);if(!Number.isSafeInteger(parsed)||parsed<1||parsed>100)throw new PmCliError("--max-attempts must be an integer from 1 to 100",EXIT_CODE.USAGE);return parsed}async function claimNextFromRecommendations(recommendations,force,global2,options={},claimRunner=runClaim){let attempts=0;for(const recommendation of recommendations){attempts+=1;try{const claimed=await claimRunner(recommendation.id,force,global2,options),result={...claimed,recommendation,attempts,available:!0};if(!claimed.skipped)return result}catch(error){if(!isAlreadyClaimedError(error))throw error}}if(options.ifAvailable===!0)return{available:!1,item:null,claimed_by:resolveAuthor(options.author,""),previous_assignee:null,forced:force,skipped:!0,recommendation:null,attempts,warnings:[NO_AVAILABLE_NEXT_ITEM_CODE]};const noCandidatesMatched=attempts===0;throw new PmCliError(noCandidatesMatched?"No actionable items matched the selection filters":"No actionable item remained available to claim",noCandidatesMatched?EXIT_CODE.NOT_FOUND:EXIT_CODE.CONFLICT,{code:NO_AVAILABLE_NEXT_ITEM_CODE,why:noCandidatesMatched?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[noCandidatesMatched?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function runRelease(id,force,global2,options={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),author=resolveAuthor(options.author,settings.author_default),claimPrincipal=resolveClaimPrincipal(author),ownershipReleaseBypass=options.ownershipReleaseBypass===!0;let previousAssignee=null,result;try{result=await mutateItem({pmRoot,settings,id,op:"release",author,message:options.message,force,bypassAssigneeConflict:ownershipReleaseBypass,mutate(document){return previousAssignee=document.metadata.assignee??null,!previousAssignee&&!document.metadata.claim_principal?{changedFields:[]}:(delete document.metadata.assignee,delete document.metadata.claim_principal,{changedFields:["assignee","claim_principal"]})}})}catch(error){wrapOwnershipConflict(error,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await recordReleaseSemanticAttribution({pmRoot,principal:claimPrincipal,itemId:result.item.id});const statusRegistry=resolveRuntimeStatusRegistry(settings.schema),stillInProgress=normalizeStatusForRegistry(result.item.status,statusRegistry)===normalizeStatusForRegistry(statusRegistry.in_progress_status,statusRegistry);return{item:toItemRecord(result.item),released_by:author,changed_fields:result.changedFields,previous_assignee:previousAssignee,forced:force,...stillInProgress?{warnings:["released_unclaimed_in_progress"],suggestions:[`${result.item.id} remains ${result.item.status} and unclaimed. If work is paused, run pm release ${result.item.id} --pause to move it to ${statusRegistry.open_status}.`]}:{}}}export{NO_AVAILABLE_NEXT_ITEM_CODE,claimNextFromRecommendations,isAlreadyClaimedError,parseClaimNextAttempts,runClaim,runClaimNext,runRelease};
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]="ca9fb199-0de6-5eea-bed8-7afac49123bc")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{resolveRuntimeStatusRegistry,statusIsTerminal,EXIT_CODE,PmCliError,toItemRecord,mutateItem,resolvePmRoot,readSettings,resolveAuthor,resolveClaimPrincipal,normalizeStatusForRegistry}from"../runtime-primitives.js";import{wrapOwnershipConflict}from"../annotations.js";import{describeItemOwnershipConflict}from"../ownership-source.js";import{applyReleaseHandoff,resolveReleaseHandoff}from"./release-handoff.js";import{runNext}from"../query/next.js";import{recordClaimSemanticAttribution,recordReleaseSemanticAttribution}from"../context/semantic-session-attribution.js";const NO_AVAILABLE_NEXT_ITEM_CODE="no_available_next_item";function isAlreadyClaimedError(error){if(!(error instanceof Error)||error.name!=="PmCliError")return!1;const context=error.context;return typeof context=="object"&&context!==null&&"code"in context&&context.code==="already_claimed_by"}async function runClaim(id,force,global2,options={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),author=resolveAuthor(options.author,settings.author_default),claimPrincipal=resolveClaimPrincipal(author);let previousAssignee=null,skipped=!1;const mutationWarnings=[],result=await mutateItem({pmRoot,settings,id,op:"claim",author,message:options.message,force,skipNoop:!0,async mutate(document){const currentAssigneeText=document.metadata.assignee??"",currentClaimPrincipal=document.metadata.claim_principal?.trim()||currentAssigneeText;if(previousAssignee=currentAssigneeText.trim().length>0?currentAssigneeText:null,statusIsTerminal(document.metadata.status,statusRegistry)&&!force)throw new PmCliError(`Cannot claim terminal item ${document.metadata.id} without --force`,EXIT_CODE.CONFLICT);if(previousAssignee!==null&&currentClaimPrincipal!==claimPrincipal){if(options.ifAvailable===!0)return skipped=!0,mutationWarnings.push(`claim_skipped_held_by:${previousAssignee}`),{changedFields:[]};if(!force){const ownershipPhrase=await describeItemOwnershipConflict(pmRoot,document.metadata.id,currentAssigneeText);throw new PmCliError(`Item ${document.metadata.id} is already ${ownershipPhrase}. Use --force to take over, or --if-available to skip without failing.`,EXIT_CODE.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}mutationWarnings.push(`claim_takeover:${previousAssignee}->${author}`)}const ownership={assignee:author,claim_principal:claimPrincipal},changedFields=["assignee","claim_principal"].filter(field=>document.metadata[field]!==ownership[field]);return Object.assign(document.metadata,ownership),{changedFields,warnings:mutationWarnings}}});return skipped||await recordClaimSemanticAttribution({pmRoot,settings,principal:claimPrincipal,itemId:result.item.id}),{item:toItemRecord(result.item),changed_fields:result.changedFields,claimed_by:skipped&&previousAssignee!==null?previousAssignee:author,previous_assignee:previousAssignee,forced:force,...skipped?{skipped:!0}:{},...mutationWarnings.length>0?{warnings:mutationWarnings}:{}}}async function runClaimNext(force,global2,options={},nextOptions={}){const maxAttempts=parseClaimNextAttempts(options.maxAttempts),settings=await readSettings(resolvePmRoot(process.cwd(),global2.path)),claimOptions={...options,author:resolveAuthor(options.author,settings.author_default)},next=await runNext({...nextOptions,callerAuthor:claimOptions.author,limit:String(maxAttempts)},global2),recommendations=[next.recommended,...next.ready].filter(entry=>entry!==null).map(entry=>({...entry,reasons:"reasons"in entry?entry.reasons:["ranked ready candidate"]}));return claimNextFromRecommendations(recommendations.slice(0,maxAttempts),force,global2,claimOptions)}function parseClaimNextAttempts(raw){if(raw===void 0)return 10;const parsed=Number(raw);if(!Number.isSafeInteger(parsed)||parsed<1||parsed>100)throw new PmCliError("--max-attempts must be an integer from 1 to 100",EXIT_CODE.USAGE);return parsed}async function claimNextFromRecommendations(recommendations,force,global2,options={},claimRunner=runClaim){let attempts=0;for(const recommendation of recommendations){attempts+=1;try{const claimed=await claimRunner(recommendation.id,force,global2,options),result={...claimed,recommendation,attempts,available:!0};if(!claimed.skipped)return result}catch(error){if(!isAlreadyClaimedError(error))throw error}}if(options.ifAvailable===!0)return{available:!1,item:null,claimed_by:resolveAuthor(options.author,""),previous_assignee:null,forced:force,skipped:!0,recommendation:null,attempts,warnings:[NO_AVAILABLE_NEXT_ITEM_CODE]};const noCandidatesMatched=attempts===0;throw new PmCliError(noCandidatesMatched?"No actionable items matched the selection filters":"No actionable item remained available to claim",noCandidatesMatched?EXIT_CODE.NOT_FOUND:EXIT_CODE.CONFLICT,{code:NO_AVAILABLE_NEXT_ITEM_CODE,why:noCandidatesMatched?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[noCandidatesMatched?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function runRelease(id,force,global2,options={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),author=resolveAuthor(options.author,settings.author_default),claimPrincipal=resolveClaimPrincipal(author),ownershipReleaseBypass=options.ownershipReleaseBypass===!0;let previousAssignee=null;const statusRegistry=resolveRuntimeStatusRegistry(settings.schema),handoffStatus=resolveReleaseHandoff(options,statusRegistry);if(handoffStatus!==void 0&&ownershipReleaseBypass)throw new PmCliError("Ownership-release bypass only clears ownership; it cannot change a handoff status.",EXIT_CODE.USAGE);let handoff,result;try{result=await mutateItem({pmRoot,settings,id,op:"release",author,message:options.message,force,bypassAssigneeConflict:ownershipReleaseBypass,mutate(document){previousAssignee=document.metadata.assignee??null;const transition=handoffStatus===void 0?void 0:applyReleaseHandoff(document.metadata,handoffStatus,settings,statusRegistry,options.message);return handoff=transition?.receipt,!previousAssignee&&!document.metadata.claim_principal?{changedFields:[]}:(delete document.metadata.assignee,delete document.metadata.claim_principal,{changedFields:["assignee","claim_principal",...transition?.changedFields??[]],warnings:transition?.warnings})}})}catch(error){wrapOwnershipConflict(error,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await recordReleaseSemanticAttribution({pmRoot,principal:claimPrincipal,itemId:result.item.id});const stillInProgress=normalizeStatusForRegistry(result.item.status,statusRegistry)===normalizeStatusForRegistry(statusRegistry.in_progress_status,statusRegistry);return{item:toItemRecord(result.item),released_by:author,changed_fields:result.changedFields,previous_assignee:previousAssignee,forced:force,...handoff===void 0?{}:{handoff},...result.warnings.length>0||stillInProgress?{warnings:[...result.warnings,...stillInProgress?["released_unclaimed_in_progress"]:[]]}:{},...stillInProgress?{suggestions:[`${result.item.id} remains ${result.item.status} and unclaimed. If work is paused, run pm release ${result.item.id} --pause to move it to ${statusRegistry.open_status}.`]}:{}}}export{NO_AVAILABLE_NEXT_ITEM_CODE,claimNextFromRecommendations,isAlreadyClaimedError,parseClaimNextAttempts,runClaim,runClaimNext,runRelease};
2
2
  //# sourceMappingURL=claim.js.map
@@ -1,12 +1,6 @@
1
- /**
2
- * @module sdk/lifecycle/close
3
- *
4
- * Implements the pm close command surface and its agent-facing runtime behavior.
5
- */
6
- import type { PmCliErrorRecoveryPayload } from "../../core/shared/errors.js";
7
1
  import { type GlobalOptions } from "../runtime-primitives.js";
8
2
  import { collectBlockedByIds } from "../actionability.js";
9
- import { type CloseOperationOptions,type CloseOperationResult } from "../lifecycle-policy.js";
3
+ import { type CloseOperationOptions,type CloseOperationResult,type CloseEvidenceFollowUp } from "../lifecycle-policy.js";
10
4
  /** Compatibility options for command-shaped close consumers. */
11
5
  export interface CloseCommandOptions {
12
6
  /** Mutation author. */
@@ -35,7 +29,7 @@ item:Record<string,unknown>;
35
29
  /** Changed metadata fields. */
36
30
  changed_fields:string[];
37
31
  /** Evidence-only update guidance when acceptance fields are missing. */
38
- recovery?:PmCliErrorRecoveryPayload;
32
+ follow_up?:CloseEvidenceFollowUp;
39
33
  /** Validation and lifecycle receipts. */
40
34
  warnings:string[];
41
35
  }
@@ -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]="ab15186d-b8bc-5740-bc16-d5af1eeeaa02")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{toItemRecord,isTerminalStatus,resolveItemTypeRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,mutateItem,readLocatedItem,resolvePmRoot,readSettings,resolveAuthor,resolveIsoOrRelative,shouldCompletePlanOnClose,getActiveExtensionRegistrations}from"../runtime-primitives.js";import{collectBlockedByIds,indexBlockedByIds}from"../actionability.js";import{applyTerminalOrderingPolicy,requireTerminalReason}from"../lifecycle-policy.js";import{nowIso}from"../../core/shared/time.js";import{renderPmCommand}from"../command-line.js";const CLOSE_VALIDATION_FIELDS=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function parseValidateCloseMode(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(normalized.length===0||normalized==="warn")return"warn";if(normalized==="off"||normalized==="none"||normalized==="disabled")return"off";if(normalized==="strict")return"strict";throw new PmCliError(`Invalid --validate-close mode "${raw}" (expected "off", "warn", or "strict")`,EXIT_CODE.USAGE)}function findMissingCloseValidationFields(itemMetadata){const missing=[];for(const field of CLOSE_VALIDATION_FIELDS){const rawValue=itemMetadata[field.key];(typeof rawValue!="string"||rawValue.trim().length===0)&&missing.push(field)}return missing}function closeEvidenceRecovery(metadata,pmRoot,options={}){const missing=findMissingCloseValidationFields(metadata);if(missing.length===0)return;const values={resolution:options.resolution,expected_result:options.expectedResult,actual_result:options.actualResult},missingFlags=missing.map(field=>`--${field.key.replaceAll("_","-")}`),args=["--pm-path",pmRoot,"update",metadata.id,...missing.flatMap((field,index)=>[missingFlags[index],values[field.key]?.trim()||"<value>"])];return{missing:missingFlags,suggested_retry:renderPmCommand(args),suggested_retry_args:args}}async function duplicateChainReferencesClosingItem(loadItemById,initialDuplicateOf,closingId){const visited=new Set;let current=initialDuplicateOf;for(;typeof current=="string"&&current.trim().length>0;){const currentId=current.trim();if(currentId===closingId)return!0;if(visited.has(currentId))return!1;visited.add(currentId),current=(await loadItemById(currentId))?.duplicate_of}return!1}function shouldApplyDuplicateFallback(value){return typeof value!="string"||value.trim().length===0}async function assertDuplicateTargetExists(pmRoot,settings,duplicateOf,closingId){const rawTarget=duplicateOf?.trim();if(!rawTarget)return;if(rawTarget===closingId)throw new PmCliError("An item cannot be closed as a duplicate of itself.",EXIT_CODE.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),itemCache=new Map,loadItemById=async id=>{if(itemCache.has(id))return itemCache.get(id)??null;const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)return itemCache.set(id,null),null;const{document}=await readLocatedItem(located,{schema:settings.schema});return itemCache.set(id,document.metadata),document.metadata},target=await loadItemById(rawTarget);if(!target)throw new PmCliError(`Duplicate target "${rawTarget}" was not found. Create or locate the canonical item first.`,EXIT_CODE.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${closingId} "Duplicate of ${rawTarget}" --duplicate-of ${rawTarget}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await duplicateChainReferencesClosingItem(loadItemById,target.duplicate_of,closingId))throw new PmCliError(`Circular duplicate reference detected. Target "${rawTarget}" points back to "${closingId}".`,EXIT_CODE.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof target.duplicate_of=="string"&&target.duplicate_of.trim().length>0)throw new PmCliError(`Duplicate target "${rawTarget}" is already marked as a duplicate of "${target.duplicate_of.trim()}".`,EXIT_CODE.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${closingId} "Duplicate of ${target.duplicate_of.trim()}" --duplicate-of ${target.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return target.id}function findActiveChildIds(items,parentId,statusRegistry){return items.filter(item=>item.parent===parentId&&!isTerminalStatus(item.status,statusRegistry)).map(item=>item.id).sort((left,right)=>left.localeCompare(right))}function findAutoUnblockCandidates(items,closedId,statusRegistry){const itemsById=new Map(items.map(item=>[item.id.trim().toLowerCase(),item])),blockerIdsByItem=indexBlockedByIds(items),normalizedClosedId=closedId.trim().toLowerCase(),blockedStatuses=statusRegistry.blocked_statuses;return items.filter(item=>blockedStatuses.has(item.status)).map(item=>({item,blockerIds:blockerIdsByItem.get(item.id.trim().toLowerCase())})).filter(({blockerIds})=>blockerIds.includes(normalizedClosedId)).filter(({blockerIds})=>blockerIds.every(blockerId=>{if(blockerId===normalizedClosedId)return!0;const blocker=itemsById.get(blockerId);return blocker!==void 0&&isTerminalStatus(blocker.status,statusRegistry)})).map(({item,blockerIds})=>({id:item.id,blocker_ids:blockerIds})).sort((left,right)=>left.id.localeCompare(right.id))}async function autoUnblockResolvedDependents(pmRoot,settings,items,closedId,author,statusRegistry){const candidates=findAutoUnblockCandidates(items,closedId,statusRegistry),warnings=[];for(const candidate of candidates)try{const unblocked=await mutateItem({pmRoot,settings,id:candidate.id,op:"update",author,message:`Auto-unblocked after blocker ${closedId} closed`,mutate(document){const dependencies=document.metadata.dependencies??[],remainingDependencies=dependencies.filter(dependency=>{const dependencyId=dependency.id.trim().toLowerCase();return dependency.kind!=="blocked_by"||!candidate.blocker_ids.includes(dependencyId)});document.metadata.status=statusRegistry.open_status,delete document.metadata.blocked_by,delete document.metadata.blocked_reason,document.metadata.unblock_note=`Auto-unblocked after blocker ${closedId} closed; all blockers resolved (${candidate.blocker_ids.join(", ")}).`,remainingDependencies.length>0?document.metadata.dependencies=remainingDependencies:delete document.metadata.dependencies;const changedFields=["status","blocked_by","blocked_reason","unblock_note"];return remainingDependencies.length!==dependencies.length&&changedFields.push("dependencies"),{changedFields}}});warnings.push(`auto_unblocked:${unblocked.item.id}:resolved_blockers=${candidate.blocker_ids.join(",")}`)}catch(error){const reason=error instanceof Error?error.message.replace(/\s+/g," ").trim():"unknown";warnings.push(`auto_unblock_failed:${candidate.id}:${reason}`)}return warnings}function applyInlineCloseFields(metadata,options){const changedFields=[],inlineCloseFields=[{option:options.resolution,key:"resolution"},{option:options.expectedResult,key:"expected_result"},{option:options.actualResult,key:"actual_result"}];for(const{option,key}of inlineCloseFields){if(typeof option!="string")continue;const trimmed=option.trim();trimmed.length!==0&&(metadata[key]=trimmed,changedFields.push(key))}return changedFields}function applyDuplicateCloseMetadata(metadata,duplicateOf){if(duplicateOf===void 0)return[];metadata.duplicate_of=duplicateOf;const duplicateFallbackFields=[],fallbackValues=[{key:"resolution",value:`Duplicate of ${duplicateOf}`},{key:"expected_result",value:`Canonical item ${duplicateOf} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${duplicateOf}.`}];for(const{key,value}of fallbackValues)shouldApplyDuplicateFallback(metadata[key])&&(metadata[key]=value,duplicateFallbackFields.push(key));return duplicateFallbackFields}function collectCloseValidationWarnings(metadata,validateCloseMode,activeChildIds,pmRoot){const warnings=[];if(validateCloseMode!=="off"){const missingFields=findMissingCloseValidationFields(metadata);if(missingFields.length>0){const missingLabels=missingFields.map(field=>field.label);if(validateCloseMode==="strict"){const missingFlags=missingFields.map(field=>`--${field.key.replaceAll("_","-")}`),updateTokens=["--pm-path",pmRoot,"update",metadata.id,...missingFlags.flatMap(flag=>[flag,"<value>"])];throw new PmCliError(`Cannot close item ${metadata.id}: missing ${missingLabels.join(", ")}. Populate fields or use --validate-close warn.`,EXIT_CODE.USAGE,{code:"close_validation_missing_fields",recovery:{missing:missingFlags,suggested_retry:renderPmCommand(updateTokens)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}warnings.push(`close_validation_missing_fields:${metadata.id}:${missingLabels.join(",")}`)}if(activeChildIds.length>0){if(validateCloseMode==="strict")throw new PmCliError(`Cannot close item ${metadata.id}: active child items remain open (${activeChildIds.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,EXIT_CODE.USAGE);warnings.push(`close_validation_active_children:${metadata.id}:${activeChildIds.join(",")}`)}return warnings}return activeChildIds.length>0&&warnings.push(`closed_with_active_children:${metadata.id}:${activeChildIds.join(",")}`),warnings}function applyCloseReason(metadata,closeReason){return closeReason!==void 0?(metadata.close_reason=closeReason,["close_reason"]):[]}function clearCloseAssignee(metadata){return metadata.assignee===void 0?[]:(delete metadata.assignee,["assignee"])}function mutateCloseMetadata(metadata,context){if(isTerminalStatus(metadata.status,context.statusRegistry)&&!context.force)throw new PmCliError(`Item ${metadata.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,EXIT_CODE.CONFLICT,{recovery:closeEvidenceRecovery(metadata,context.pmRoot,context.options)});const inlineChangedFields=applyInlineCloseFields(metadata,context.options),duplicateFallbackFields=applyDuplicateCloseMetadata(metadata,context.duplicateOf),mutationWarnings=collectCloseValidationWarnings(metadata,context.validateCloseMode,context.activeChildIds,context.pmRoot);metadata.status=context.statusRegistry.close_status,metadata.closed_at=context.closedAt;const shouldWriteCompletedAt=context.options.completedAt!==void 0||metadata.completed_at===void 0;shouldWriteCompletedAt&&(metadata.completed_at=context.completedAt);const changedFields=["status","closed_at",...shouldWriteCompletedAt?["completed_at"]:[],...applyCloseReason(metadata,context.closeReason),...inlineChangedFields];if(shouldCompletePlanOnClose(metadata)&&(metadata.plan_mode="completed",changedFields.push("plan_mode")),context.duplicateOf!==void 0){changedFields.push("duplicate_of");for(const key of duplicateFallbackFields)changedFields.includes(key)||changedFields.push(key)}changedFields.push(...clearCloseAssignee(metadata));const blockerCleanup=applyTerminalOrderingPolicy(metadata,context.lifecyclePolicy);return changedFields.push(...blockerCleanup.changedFields),mutationWarnings.push(...blockerCleanup.warnings),{changedFields,...mutationWarnings.length>0?{warnings:mutationWarnings}:{}}}const _testOnlyCloseCommand={blockedByIds:collectBlockedByIds};async function closeItem(id,closeReasonText,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),author=resolveAuthor(options.author,settings.author_default),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeToFolder);const duplicateOf=await assertDuplicateTargetExists(pmRoot,settings,options.duplicateOf,located.id),lifecyclePolicy={requireCloseReason:options.lifecyclePolicy?.requireCloseReason??settings.governance.require_close_reason,orderingEdges:options.lifecyclePolicy?.orderingEdges??"preserve"},closeReason=requireTerminalReason({explicit:closeReasonText,duplicateOf,resolution:options.resolution,message:options.message},lifecyclePolicy.requireCloseReason).closeReason,validateCloseMode=parseValidateCloseMode(options.validateClose)??settings.governance.close_validation_default,trackerItems=await listAllItemMetadataLight(pmRoot,settings.item_format,typeToFolder,void 0,settings.schema),activeChildIds=findActiveChildIds(trackerItems,located.id,statusRegistry),closedAt=nowIso(),completedAt=options.completedAt===void 0?closedAt:resolveIsoOrRelative(options.completedAt,new Date(closedAt),"completed-at"),result=await mutateItem({pmRoot,settings,id:located.id,op:"close",author,message:options.message,force:options.force,mutate(document){return mutateCloseMetadata(document.metadata,{pmRoot,statusRegistry,force:options.force,options,duplicateOf,validateCloseMode,activeChildIds,closeReason,closedAt,completedAt,lifecyclePolicy})}}),recovery=validateCloseMode==="warn"?closeEvidenceRecovery(result.item,pmRoot):void 0;return{item:toItemRecord(result.item),changed_fields:result.changedFields,...recovery?{recovery}:{},warnings:[...result.warnings,...await autoUnblockResolvedDependents(pmRoot,settings,trackerItems,located.id,author,statusRegistry)]}}function runClose(id,closeReasonText,options,global2){return closeItem(id,closeReasonText,options,global2)}export{_testOnlyCloseCommand,closeItem,runClose};
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]="6b7f5ee8-94ca-574f-b660-963eb574d571")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{toItemRecord,isTerminalStatus,resolveItemTypeRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,mutateItem,readLocatedItem,resolvePmRoot,readSettings,resolveAuthor,resolveIsoOrRelative,shouldCompletePlanOnClose,getActiveExtensionRegistrations}from"../runtime-primitives.js";import{collectBlockedByIds,indexBlockedByIds}from"../actionability.js";import{applyTerminalOrderingPolicy,requireTerminalReason}from"../lifecycle-policy.js";import{nowIso}from"../../core/shared/time.js";import{renderPmCommand}from"../command-line.js";const CLOSE_VALIDATION_FIELDS=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function parseValidateCloseMode(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(normalized.length===0||normalized==="warn")return"warn";if(normalized==="off"||normalized==="none"||normalized==="disabled")return"off";if(normalized==="strict")return"strict";throw new PmCliError(`Invalid --validate-close mode "${raw}" (expected "off", "warn", or "strict")`,EXIT_CODE.USAGE)}function findMissingCloseValidationFields(itemMetadata){const missing=[];for(const field of CLOSE_VALIDATION_FIELDS){const rawValue=itemMetadata[field.key];(typeof rawValue!="string"||rawValue.trim().length===0)&&missing.push(field)}return missing}function closeEvidenceRecovery(metadata,pmRoot,options={}){const missing=findMissingCloseValidationFields(metadata);if(missing.length===0)return;const values={resolution:options.resolution,expected_result:options.expectedResult,actual_result:options.actualResult},missingFlags=missing.map(field=>`--${field.key.replaceAll("_","-")}`),args=["--pm-path",pmRoot,"update",metadata.id,...missing.flatMap((field,index)=>[missingFlags[index],values[field.key]?.trim()||"<value>"])];return{missing:missingFlags,suggested_retry:renderPmCommand(args),suggested_retry_args:args}}async function duplicateChainReferencesClosingItem(loadItemById,initialDuplicateOf,closingId){const visited=new Set;let current=initialDuplicateOf;for(;typeof current=="string"&&current.trim().length>0;){const currentId=current.trim();if(currentId===closingId)return!0;if(visited.has(currentId))return!1;visited.add(currentId),current=(await loadItemById(currentId))?.duplicate_of}return!1}function shouldApplyDuplicateFallback(value){return typeof value!="string"||value.trim().length===0}async function assertDuplicateTargetExists(pmRoot,settings,duplicateOf,closingId){const rawTarget=duplicateOf?.trim();if(!rawTarget)return;if(rawTarget===closingId)throw new PmCliError("An item cannot be closed as a duplicate of itself.",EXIT_CODE.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),itemCache=new Map,loadItemById=async id=>{if(itemCache.has(id))return itemCache.get(id)??null;const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)return itemCache.set(id,null),null;const{document}=await readLocatedItem(located,{schema:settings.schema});return itemCache.set(id,document.metadata),document.metadata},target=await loadItemById(rawTarget);if(!target)throw new PmCliError(`Duplicate target "${rawTarget}" was not found. Create or locate the canonical item first.`,EXIT_CODE.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${closingId} "Duplicate of ${rawTarget}" --duplicate-of ${rawTarget}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await duplicateChainReferencesClosingItem(loadItemById,target.duplicate_of,closingId))throw new PmCliError(`Circular duplicate reference detected. Target "${rawTarget}" points back to "${closingId}".`,EXIT_CODE.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof target.duplicate_of=="string"&&target.duplicate_of.trim().length>0)throw new PmCliError(`Duplicate target "${rawTarget}" is already marked as a duplicate of "${target.duplicate_of.trim()}".`,EXIT_CODE.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${closingId} "Duplicate of ${target.duplicate_of.trim()}" --duplicate-of ${target.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return target.id}function findActiveChildIds(items,parentId,statusRegistry){return items.filter(item=>item.parent===parentId&&!isTerminalStatus(item.status,statusRegistry)).map(item=>item.id).sort((left,right)=>left.localeCompare(right))}function findAutoUnblockCandidates(items,closedId,statusRegistry){const itemsById=new Map(items.map(item=>[item.id.trim().toLowerCase(),item])),blockerIdsByItem=indexBlockedByIds(items),normalizedClosedId=closedId.trim().toLowerCase(),blockedStatuses=statusRegistry.blocked_statuses;return items.filter(item=>blockedStatuses.has(item.status)).map(item=>({item,blockerIds:blockerIdsByItem.get(item.id.trim().toLowerCase())})).filter(({blockerIds})=>blockerIds.includes(normalizedClosedId)).filter(({blockerIds})=>blockerIds.every(blockerId=>{if(blockerId===normalizedClosedId)return!0;const blocker=itemsById.get(blockerId);return blocker!==void 0&&isTerminalStatus(blocker.status,statusRegistry)})).map(({item,blockerIds})=>({id:item.id,blocker_ids:blockerIds})).sort((left,right)=>left.id.localeCompare(right.id))}async function autoUnblockResolvedDependents(pmRoot,settings,items,closedId,author,statusRegistry){const candidates=findAutoUnblockCandidates(items,closedId,statusRegistry),warnings=[];for(const candidate of candidates)try{const unblocked=await mutateItem({pmRoot,settings,id:candidate.id,op:"update",author,message:`Auto-unblocked after blocker ${closedId} closed`,mutate(document){const dependencies=document.metadata.dependencies??[],remainingDependencies=dependencies.filter(dependency=>{const dependencyId=dependency.id.trim().toLowerCase();return dependency.kind!=="blocked_by"||!candidate.blocker_ids.includes(dependencyId)});document.metadata.status=statusRegistry.open_status,delete document.metadata.blocked_by,delete document.metadata.blocked_reason,document.metadata.unblock_note=`Auto-unblocked after blocker ${closedId} closed; all blockers resolved (${candidate.blocker_ids.join(", ")}).`,remainingDependencies.length>0?document.metadata.dependencies=remainingDependencies:delete document.metadata.dependencies;const changedFields=["status","blocked_by","blocked_reason","unblock_note"];return remainingDependencies.length!==dependencies.length&&changedFields.push("dependencies"),{changedFields}}});warnings.push(`auto_unblocked:${unblocked.item.id}:resolved_blockers=${candidate.blocker_ids.join(",")}`)}catch(error){const reason=error instanceof Error?error.message.replace(/\s+/g," ").trim():"unknown";warnings.push(`auto_unblock_failed:${candidate.id}:${reason}`)}return warnings}function applyInlineCloseFields(metadata,options){const changedFields=[],inlineCloseFields=[{option:options.resolution,key:"resolution"},{option:options.expectedResult,key:"expected_result"},{option:options.actualResult,key:"actual_result"}];for(const{option,key}of inlineCloseFields){if(typeof option!="string")continue;const trimmed=option.trim();trimmed.length!==0&&(metadata[key]=trimmed,changedFields.push(key))}return changedFields}function applyDuplicateCloseMetadata(metadata,duplicateOf){if(duplicateOf===void 0)return[];metadata.duplicate_of=duplicateOf;const duplicateFallbackFields=[],fallbackValues=[{key:"resolution",value:`Duplicate of ${duplicateOf}`},{key:"expected_result",value:`Canonical item ${duplicateOf} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${duplicateOf}.`}];for(const{key,value}of fallbackValues)shouldApplyDuplicateFallback(metadata[key])&&(metadata[key]=value,duplicateFallbackFields.push(key));return duplicateFallbackFields}function collectCloseValidationWarnings(metadata,validateCloseMode,activeChildIds,pmRoot){const warnings=[];if(validateCloseMode!=="off"){const missingFields=findMissingCloseValidationFields(metadata);if(missingFields.length>0){const missingLabels=missingFields.map(field=>field.label);if(validateCloseMode==="strict"){const missingFlags=missingFields.map(field=>`--${field.key.replaceAll("_","-")}`),updateTokens=["--pm-path",pmRoot,"update",metadata.id,...missingFlags.flatMap(flag=>[flag,"<value>"])];throw new PmCliError(`Cannot close item ${metadata.id}: missing ${missingLabels.join(", ")}. Populate fields or use --validate-close warn.`,EXIT_CODE.USAGE,{code:"close_validation_missing_fields",recovery:{missing:missingFlags,suggested_retry:renderPmCommand(updateTokens)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}warnings.push(`close_validation_missing_fields:${metadata.id}:${missingLabels.join(",")}`)}if(activeChildIds.length>0){if(validateCloseMode==="strict")throw new PmCliError(`Cannot close item ${metadata.id}: active child items remain open (${activeChildIds.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,EXIT_CODE.USAGE);warnings.push(`close_validation_active_children:${metadata.id}:${activeChildIds.join(",")}`)}return warnings}return activeChildIds.length>0&&warnings.push(`closed_with_active_children:${metadata.id}:${activeChildIds.join(",")}`),warnings}function applyCloseReason(metadata,closeReason){return closeReason!==void 0?(metadata.close_reason=closeReason,["close_reason"]):[]}function clearCloseAssignee(metadata){return metadata.assignee===void 0?[]:(delete metadata.assignee,["assignee"])}function mutateCloseMetadata(metadata,context){if(isTerminalStatus(metadata.status,context.statusRegistry)&&!context.force)throw new PmCliError(`Item ${metadata.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,EXIT_CODE.CONFLICT,{recovery:closeEvidenceRecovery(metadata,context.pmRoot,context.options)});const inlineChangedFields=applyInlineCloseFields(metadata,context.options),duplicateFallbackFields=applyDuplicateCloseMetadata(metadata,context.duplicateOf),mutationWarnings=collectCloseValidationWarnings(metadata,context.validateCloseMode,context.activeChildIds,context.pmRoot);metadata.status=context.statusRegistry.close_status,metadata.closed_at=context.closedAt;const shouldWriteCompletedAt=context.options.completedAt!==void 0||metadata.completed_at===void 0;shouldWriteCompletedAt&&(metadata.completed_at=context.completedAt);const changedFields=["status","closed_at",...shouldWriteCompletedAt?["completed_at"]:[],...applyCloseReason(metadata,context.closeReason),...inlineChangedFields];if(shouldCompletePlanOnClose(metadata)&&(metadata.plan_mode="completed",changedFields.push("plan_mode")),context.duplicateOf!==void 0){changedFields.push("duplicate_of");for(const key of duplicateFallbackFields)changedFields.includes(key)||changedFields.push(key)}changedFields.push(...clearCloseAssignee(metadata));const blockerCleanup=applyTerminalOrderingPolicy(metadata,context.lifecyclePolicy);return changedFields.push(...blockerCleanup.changedFields),mutationWarnings.push(...blockerCleanup.warnings),{changedFields,...mutationWarnings.length>0?{warnings:mutationWarnings}:{}}}const _testOnlyCloseCommand={blockedByIds:collectBlockedByIds};async function closeItem(id,closeReasonText,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),author=resolveAuthor(options.author,settings.author_default),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeToFolder);const duplicateOf=await assertDuplicateTargetExists(pmRoot,settings,options.duplicateOf,located.id),lifecyclePolicy={requireCloseReason:options.lifecyclePolicy?.requireCloseReason??settings.governance.require_close_reason,orderingEdges:options.lifecyclePolicy?.orderingEdges??"preserve"},closeReason=requireTerminalReason({explicit:closeReasonText,duplicateOf,resolution:options.resolution,message:options.message},lifecyclePolicy.requireCloseReason).closeReason,validateCloseMode=parseValidateCloseMode(options.validateClose)??settings.governance.close_validation_default,trackerItems=await listAllItemMetadataLight(pmRoot,settings.item_format,typeToFolder,void 0,settings.schema),activeChildIds=findActiveChildIds(trackerItems,located.id,statusRegistry),closedAt=nowIso(),completedAt=options.completedAt===void 0?closedAt:resolveIsoOrRelative(options.completedAt,new Date(closedAt),"completed-at"),result=await mutateItem({pmRoot,settings,id:located.id,op:"close",author,message:options.message,force:options.force,mutate(document){return mutateCloseMetadata(document.metadata,{pmRoot,statusRegistry,force:options.force,options,duplicateOf,validateCloseMode,activeChildIds,closeReason,closedAt,completedAt,lifecyclePolicy})}}),evidence=validateCloseMode==="warn"?closeEvidenceRecovery(result.item,pmRoot):void 0;return{item:toItemRecord(result.item),changed_fields:result.changedFields,...evidence?{follow_up:{kind:"complete_close_evidence",missing:evidence.missing,suggested_command:evidence.suggested_retry,suggested_command_args:evidence.suggested_retry_args}}:{},warnings:[...result.warnings,...await autoUnblockResolvedDependents(pmRoot,settings,trackerItems,located.id,author,statusRegistry)]}}function runClose(id,closeReasonText,options,global2){return closeItem(id,closeReasonText,options,global2)}export{_testOnlyCloseCommand,closeItem,runClose};
2
2
  //# sourceMappingURL=close.js.map